repo_name
stringlengths
7
104
file_path
stringlengths
11
238
context
list
import_statement
stringlengths
103
6.85k
code
stringlengths
60
38.4k
next_line
stringlengths
10
824
gold_snippet_index
int32
0
8
goerlitz/rdffederator
src/de/uni_koblenz/west/splendid/optimizer/AbstractFederationOptimizer.java
[ "public abstract class AbstractCostEstimator extends QueryModelVisitorBase<RuntimeException> implements ModelEvaluator {\n\t\n\tprotected double cost;\n\t\n\tprotected AbstractCardinalityEstimator cardEst;\n\t\n\tpublic AbstractCardinalityEstimator getCardinalityEstimator() {\n\t\treturn cardEst;\n\t}\n\n\tpublic void setCardinalityEstimator(AbstractCardinalityEstimator cardEst) {\n\t\tthis.cardEst = cardEst;\n\t}\n\n\tpublic Double getCost(TupleExpr expr) {\n\t\tcost = 0;\n\t\texpr.visit(this);\n\t\treturn cost;\n\t}\n\t\n\t@Override\n\tpublic Double process(TupleExpr expr) {\n\t\tsynchronized (this) {\n\t\t\treturn getCost(expr);\n\t\t}\n\t}\n\t\n}", "public interface ModelEvaluator {\n\t\n\tpublic Double process(TupleExpr expr);\n\t\n\tpublic String getName();\n\n}", "public class AnnotatingTreePrinter extends QueryModelVisitorBase<RuntimeException> {\n\t\n\tprivate static final String LINE_SEPARATOR = System.getProperty(\"line.separator\");\n\t\n\tprivate static final String indentString = \" \";\n\n\tprivate StringBuilder buffer;\n\n\tprivate int indentLevel = 0;\n\t\n\tprivate ModelEvaluator eval;\n\tprivate String evalLabel;\n\t\n\tpublic AnnotatingTreePrinter(ModelEvaluator eval) {\n\t\tthis.buffer = new StringBuilder(256);\n\t\tthis.eval = eval;\n\t\tif (eval != null)\n\t\t\tthis.evalLabel = eval.getName();\n\t}\n\t\n\tpublic static String print(QueryModelNode root) {\n\t\treturn print(root, null);\n\t}\n\t\n\tpublic static String print(QueryModelNode root, ModelEvaluator eval) {\n\t\tAnnotatingTreePrinter printer = new AnnotatingTreePrinter(eval);\n\t\troot.visit(printer);\n\t\treturn printer.toString();\n\t}\n\t\n\tprivate void addIndent() {\n\t\tfor (int i = 0; i < indentLevel; i++) {\n\t\t\tbuffer.append(indentString);\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void meet(Compare node) throws RuntimeException {\n\t\tnode.getLeftArg().visit(this);\n\t\tbuffer.append(\" \").append(node.getOperator().getSymbol()).append(\" \");\n\t\tnode.getRightArg().visit(this);\n\t}\n\n\t@Override\n\tpublic void meet(Filter node) throws RuntimeException {\n\t\taddIndent();\n\t\tbuffer.append(\"FILTER (\");\n\t\tnode.getCondition().visit(this);\n\t\tbuffer.append(\")\").append(LINE_SEPARATOR);\n\t\tindentLevel++;\n\t\tnode.getArg().visit(this);\n\t\tindentLevel--;\n\t}\n\t\n\t@Override\n\tpublic void meet(StatementPattern node) throws RuntimeException {\n\t\taddIndent();\n\t\tfor (Var var : node.getVarList()) {\n\t\t\tvar.visit(this);\n\t\t\tbuffer.append(\" \");\n\t\t}\n\t\t\n\t\tif (eval instanceof AbstractCostEstimator) {\n\t\t\tAbstractCardinalityEstimator evalCard = ((AbstractCostEstimator) eval).getCardinalityEstimator();\n\t\t\tbuffer.append(\" [\").append(evalCard.getName()).append(\": \").append(evalCard.process(node)).append(\"]\");\n\t\t} else if (eval != null)\n\t\t\tbuffer.append(\" [\").append(evalLabel).append(\": \").append(eval.process(node)).append(\"]\");\n\t}\n\n\t@Override\n\tpublic void meet(Var node) throws RuntimeException {\n\t\tif (node.hasValue()) {\n\t\t\tValue value = node.getValue();\n\t\t\tif (value instanceof URI)\n\t\t\t\tbuffer.append(\"<\").append(value).append(\">\");\n\t\t\telse\n\t\t\t\tbuffer.append(node.getValue());\n\t\t} else\n\t\t\tbuffer.append(\"?\").append(node.getName());\n\t}\n\t\n\t@Override\n\tpublic void meet(ValueConstant node) throws RuntimeException {\n\t\tbuffer.append(node.getValue());\n\t}\n\n\t@Override\n\tprotected void meetBinaryTupleOperator(BinaryTupleOperator node)\n\t\t\tthrows RuntimeException {\n\t\taddIndent();\n\t\tbuffer.append(node.getSignature().toUpperCase());\n\t\t\n\t\tif (eval != null) {\n\t\t\tbuffer.append(\" [\").append(evalLabel).append(\": \").append(eval.process(node)).append(\"]\");\n\t\t\tif (eval instanceof AbstractCostEstimator) {\n\t\t\t\tAbstractCardinalityEstimator evalCard = ((AbstractCostEstimator) eval).getCardinalityEstimator();\n\t\t\t\tbuffer.append(\" [\").append(evalCard.getName()).append(\": \").append(evalCard.process(node)).append(\"]\");\n\t\t\t}\n\t\t}\n\t\t\n\t\tindentLevel++;\n\t\tbuffer.append(LINE_SEPARATOR);\n\t\tnode.getLeftArg().visit(this);\n\t\tbuffer.append(LINE_SEPARATOR);\n\t\tnode.getRightArg().visit(this);\n\t\tindentLevel--;\n\t}\n\t\n\t@Override\n\tprotected void meetUnaryTupleOperator(UnaryTupleOperator node)\n\t\t\tthrows RuntimeException {\n\t\tif (node instanceof RemoteQuery) {\n\t\t\tmeet((RemoteQuery) node);\n\t\t} else {\n\t\t\tsuper.meetUnaryTupleOperator(node);\n\t\t}\n\t}\n\t\n\tprotected void meet(RemoteQuery node) {\n\t\taddIndent();\n\t\tbuffer.append(\"###REMOTE QUERY### @\").append(node.getSources());\n\t\t\n\t\t// sub queries have no cost\n\t\tif (eval instanceof AbstractCostEstimator) {\n\t\t\tAbstractCardinalityEstimator evalCard = ((AbstractCostEstimator) eval).getCardinalityEstimator();\n\t\t\tbuffer.append(\" [\").append(evalCard.getName()).append(\": \").append(evalCard.process(node)).append(\"]\");\n\t\t\t\n\t\t\tfor (StatementPattern p : StatementPatternCollector.process(node.getArg())) {\n\t\t\t\tbuffer.append(LINE_SEPARATOR);\n\t\t\t\tmeet(p);\n\t\t\t}\n\t\t} else {\n\t\t\tbuffer.append(LINE_SEPARATOR);\n\t\t\tnode.getArg().visit(this);\n\t\t}\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn this.buffer.toString();\n\t}\n\n}", "public class FilterConditionCollector extends QueryModelVisitorBase<RuntimeException> {\n\n\tpublic static List<ValueExpr> process(QueryModelNode node) {\n\t\tFilterConditionCollector collector = new FilterConditionCollector();\n\t\tnode.visit(collector);\n\t\treturn collector.conditions;\n\t}\n\n\tprivate List<ValueExpr> conditions = new ArrayList<ValueExpr>();\n\n\t@Override\n\tpublic void meet(Filter node)\n\t{\n\t\tnode.getArg().visit(this);\n\t\tconditions.add(node.getCondition());\n\t}\n\n}", "public class BasicGraphPatternExtractor extends QueryModelVisitorBase<RuntimeException> {\n\t\n\tprivate TupleExpr lastBGPNode;\n\t\n\tprivate List<TupleExpr> bgpList = new ArrayList<TupleExpr>();\n\t\n\t/**\n\t * Prevents creation of extractor classes.\n\t * The static process() method must be used instead.\n\t */\n\tprivate BasicGraphPatternExtractor() {}\n\t\n\tpublic static List<TupleExpr> process(QueryModelNode node) {\n\t\tBasicGraphPatternExtractor ex = new BasicGraphPatternExtractor();\n\t\tnode.visit(ex);\n\t\treturn ex.bgpList;\n\t}\n\t\n\t// --------------------------------------------------------------\n\t\n\t/**\n\t * Handles binary nodes with potential BGPs as children (e.g. union, left join).\n\t */\n\t@Override\n\tpublic void meetBinaryTupleOperator(BinaryTupleOperator node) throws RuntimeException {\n\t\t\n\t\tfor (TupleExpr expr : new TupleExpr[] { node.getLeftArg(), node.getRightArg() }) {\n\t\t\texpr.visit(this);\n\t\t\tif (lastBGPNode != null) {\n\t\t\t\t// child is a BGP node but this node is not\n\t\t\t\tthis.bgpList.add(lastBGPNode);\n\t\t\t\tlastBGPNode = null;\n\t\t\t}\n\t\t}\n\t}\n\t\n\t/**\n\t * Handles unary nodes with a potential BGP as child (e.g. projection).\n\t */\n\t@Override\n\tpublic void meetUnaryTupleOperator(UnaryTupleOperator node) throws RuntimeException {\n\n\t\tnode.getArg().visit(this);\n\t\t\n\t\tif (lastBGPNode != null) {\n\t\t\t// child is a BGP node but this node is not\n\t\t\tthis.bgpList.add(lastBGPNode);\n\t\t\tlastBGPNode = null;\n\t\t}\n\t}\n\n\t/**\n\t * Handles statement patterns which are always a valid BGP node.\n\t */\n\t@Override\n\tpublic void meet(StatementPattern node) throws RuntimeException {\n\t\tthis.lastBGPNode = node;\n\t}\n\t\n\t@Override\n\tpublic void meet(Filter filter) throws RuntimeException {\n\t\t// visit the filter argument but ignore the filter condition\n\t\tfilter.getArg().visit(this);\n\t\t\n\t\tif (lastBGPNode != null) {\n\t\t\t// child is a BGP as well as the filter\n\t\t\tlastBGPNode = filter;\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void meet(Join join) throws RuntimeException {\n\t\t\n\t\tboolean valid = true;\n\t\t\n\t\t// visit join arguments and check that all are valid BGPS\n\t\tfor (TupleExpr expr : new TupleExpr[] { join.getLeftArg(), join.getRightArg() }) {\n\t\t\texpr.visit(this);\n\t\t\tif (lastBGPNode == null) {\n\t\t\t\t// child is not a BGP -> join is not a BGP\n\t\t\t\tvalid = false;\n\t\t\t} else {\n\t\t\t\tif (!valid) {\n\t\t\t\t\t// last child is a BGP but another child was not\n\t\t\t\t\tthis.bgpList.add(lastBGPNode);\n\t\t\t\t\tlastBGPNode = null;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (valid)\n\t\t\tlastBGPNode = join;\n\t}\n\t\n\t// --------------------------------------------------------------\n\n//\t@Override\n//\tpublic void meet(Filter filter) throws RuntimeException {\n//\t\t\n//\t\t// visit the filter argument but ignore the filter condition\n//\t\tfilter.getArg().visit(this);\n//\t\t\n//\t\t// TODO: need to check for valid child node\n//\t\t\n//\t\t// check if the parent node is a valid BGP node (Join or Filter)\n//\t\t// because invalid BGP (parent) nodes are not visited\n//\t\tQueryModelNode parent = filter.getParentNode();\n//\t\tif (parent instanceof Join || parent instanceof Filter) {\n////\t\t\tthis.filters.add(filter.getCondition());\n//\t\t\treturn;\n//\t\t}\n//\t\t// otherwise check if filter is a direct child of a Projection or\n//\t\t// inside a left join expression\n//\t\t// TODO: what if parent is Limit or OrderBy?\n//\t\tif (parent instanceof Projection || parent instanceof MultiProjection\n//\t\t\t\t|| parent instanceof LeftJoin || parent instanceof Order || parent instanceof Slice ) {\n////\t\t\tthis.filters.add(filter.getCondition());\n//\t\t}\n////\t\tsaveBGP(filter, parent);\n//\t\tthis.bgpList.add(filter);\n//\t}\n//\n//\t@Override\n//\tpublic void meet(Join join) throws RuntimeException {\n//\t\t\n//\t\tboolean valid = true;\n////\t\tList<? extends TupleExpr> joinArgs = join.getArgs();\n//\t\tTupleExpr[] joinArgs = { join.getLeftArg(), join.getRightArg()};\n//\t\t\n//\t\t// First check if Join is a valid BGP - only if all join arguments are valid BGPs\n//\t\tfor (TupleExpr expr : joinArgs) {\n//\t\t\tif (expr instanceof Join || expr instanceof Filter || expr instanceof StatementPattern)\n//\t\t\t\tcontinue;\n//\t\t\telse\n//\t\t\t\tvalid = false;\n//\t\t}\n//\t\t\n//\t\t// then process all join arguments but store each valid child BGPs if this join is not a valid BGP\n//\t\tfor (TupleExpr expr : joinArgs) {\n//\t\t\texpr.visit(this);\n//\t\t\tif (!valid && (expr instanceof Join || expr instanceof Filter || expr instanceof StatementPattern))\n////\t\t\t\tsaveBGP(expr, join);\n//\t\t\t\tthis.bgpList.add(expr);\n//\t\t}\n//\t\t\n//\t\t// check if the parent node is a valid BGP node (Join or Filter)\n//\t\t// because invalid BGP (parent) nodes are not visited\n//\t\tQueryModelNode parent = join.getParentNode();\n//\t\tif (valid && !(parent instanceof Join) && !(parent instanceof Filter)) {\n////\t\t\tsaveBGP(join, parent);\n//\t\t\tthis.bgpList.add(join);\n//\t\t}\n//\t}\n\n}", "public class MappedStatementPattern extends StatementPattern {\n\t\n\tprivate Set<Graph> sources = new HashSet<Graph>();\n\t\n\tpublic MappedStatementPattern(StatementPattern pattern, Set<Graph> sources) {\n\t\tsuper(pattern.getScope(), pattern.getSubjectVar(), pattern.getPredicateVar(), pattern.getObjectVar(), pattern.getContextVar());\n\t\tthis.setSources(sources);\n\t}\n\n\tpublic Set<Graph> getSources() {\n\t\treturn sources;\n\t}\n\n\tpublic void setSources(Set<Graph> sources) {\n\t\tif (sources == null)\n\t\t\tthrow new IllegalArgumentException(\"source set is null\");\n\t\tthis.sources = sources;\n\t}\n\t\n\tpublic void addSource(Graph source) {\n\t\tthis.sources.add(source);\n\t}\n\t\n\tpublic boolean removeSource(Graph source) {\n\t\treturn this.sources.remove(source);\n\t}\n\t\n\t// -------------------------------------------------------------------------\n\t\n\t@Override\n\tpublic <X extends Exception> void visit(QueryModelVisitor<X> visitor)\n\t\t\tthrows X {\n\t\tvisitor.meet(this);\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn OperatorTreePrinter.print(this);\n\t}\n\n}", "public class SubQueryBuilder {\n\t\n\tprivate static final Logger LOGGER = LoggerFactory.getLogger(SubQueryBuilder.class);\n\t\n\tprivate boolean groupBySameAs;\n\tprivate boolean groupBySource;\n\t\n\tpublic SubQueryBuilder(QueryOptimizerConfig config) {\n\t\tthis.groupBySource = config.isGroupBySource();\n\t\tthis.groupBySameAs = config.isGroupBySameAs();\n\t}\n\n\t/**\n\t * Creates sub queries for all mapped data sources.\n\t * \n\t * @param patterns the statement patterns with mapped data sources.\n\t * @param conditions the filter conditions to apply.\n\t * @return a list of created sub queries.\n\t */\n\tpublic List<TupleExpr> createSubQueries(List<MappedStatementPattern> patterns, List<ValueExpr> conditions) {\n\t\t\n\t\tif (patterns == null || patterns.size() == 0)\n\t\t\tthrow new IllegalArgumentException(\"need at least on triple pattern to create sub queries\");\n\t\t\n\t\tList<TupleExpr> subQueries = new ArrayList<TupleExpr>();\n\t\t\n\t\t// create groups of triple patterns according to the configuration\n\t\tList<List<MappedStatementPattern>> groups = getGroups(patterns);\n\t\t\n\t\t// create remote queries for all triple pattern groups\n\t\t// triple patterns in groups should all have the same sources\n\t\tfor (List<MappedStatementPattern> patternGroup : groups) {\n\t\t\t\n\t\t\t// check that all patterns in a group have the same set of source\n\t\t\t// TODO: needs improvement - not the best way to do it\n\t\t\tSet<Graph> sources = null;\n\t\t\tfor (MappedStatementPattern pattern : patternGroup) {\n\t\t\t\tif (sources == null)\n\t\t\t\t\tsources = pattern.getSources();\n\t\t\t\telse\n\t\t\t\t\tif (!sources.equals(pattern.getSources())) {\n\t\t\t\t\t\tLOGGER.warn(\"Statement Patterns with different sources in group\");\n\t\t\t\t\t\tsources.addAll(pattern.getSources());\n\t\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tTupleExpr baseExpr = null;\n\t\t\t\n\t\t\t// create a remote query if the pattern group has a single source\n\t\t\tif (sources.size() == 1) {\n\t\t\t\tfor (MappedStatementPattern pattern : patternGroup) {\n\t\t\t\t\tbaseExpr = (baseExpr == null) ? pattern : new Join(baseExpr, pattern);\n\t\t\t\t}\n\t\t\t\tbaseExpr = applyFilters(baseExpr, conditions);\n\t\t\t\tsubQueries.add(new RemoteQuery(baseExpr));\n\t\t\t}\n\t\t\t\n\t\t\t// create individual remote queries if there is more than one source \n\t\t\telse {\n\t\t\t\tfor (MappedStatementPattern pattern : patternGroup) {\n\t\t\t\t\tbaseExpr = applyFilters(pattern, conditions);\n\t\t\t\t\tsubQueries.add(new RemoteQuery(baseExpr));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn subQueries;\n\t}\n\t\n\tprivate TupleExpr applyFilters(TupleExpr expr, List<ValueExpr> conditions) {\n\t\tSet<String> varNames = VarNameCollector.process(expr);\n\t\tfor (ValueExpr condition : conditions) {\n\t\t\tif (varNames.containsAll(VarNameCollector.process(condition))) {\n\t\t\t\texpr = new Filter(expr, condition);\n\t\t\t}\n\t\t}\n\t\treturn expr;\n\t}\n\t\n\tpublic List<List<MappedStatementPattern>> getGroups(List<MappedStatementPattern> patterns) {\n\t\t\n\t\t// sameAs grouping example:\n\t\t// ?city :population ?x -> [A]\n\t\t// ?city :founded_in ?y -> [B]\n\t\t// ?city owl:sameAs ?z -> [A,C,D] ... group with first pattern only\n\t\t\n\t\t// 1. no grouping -> put each single pattern in a set\n\t\t// 2. group by source -> put pattern in set based on same source\n\t\t// 3. group by sameAs -> put sameAs pattern in set with matched pattern\n\t\t// 4. group by source and by sameAs\n\t\t\n\t\tList<MappedStatementPattern> sameAsPatterns = new ArrayList<MappedStatementPattern>();\n\t\tList<List<MappedStatementPattern>> patternGroups = new ArrayList<List<MappedStatementPattern>>();\n\t\t\n\t\t// start with grouping of sameAs patterns if applicable\n\t\t// this removes all sameAs patterns and matched pattern from the list\n\t\tif (groupBySameAs) {\n\t\t\t\n\t\t\t// move sameAs patterns from pattern list to sameAs pattern list\n\t\t\tIterator<MappedStatementPattern> it = patterns.iterator();\n\t\t\twhile (it.hasNext()) {\n\t\t\t\tMappedStatementPattern pattern = it.next();\n\t\t\t\tif (OWL.SAMEAS.equals(pattern.getPredicateVar().getValue()) && !pattern.getSubjectVar().hasValue()) {\n\t\t\t\t\tsameAsPatterns.add(pattern);\n\t\t\t\t\tit.remove();\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tSet<MappedStatementPattern> matchedPatterns = new HashSet<MappedStatementPattern>();\n\t\t\t\n\t\t\t// find all matching pattern for each sameAs pattern\n\t\t\tfor (MappedStatementPattern sameAsPattern : sameAsPatterns) {\n\t\t\t\t\n\t\t\t\tList<MappedStatementPattern> matchCandidates = new ArrayList<MappedStatementPattern>();\n\t\t\t\tSet<Graph> sameAsSources = sameAsPattern.getSources();\n\t\t\t\tVar sameAsSubjectVar = sameAsPattern.getSubjectVar();\n\t\t\t\t\n\t\t\t\t// find match candidates\n\t\t\t\tfor (MappedStatementPattern pattern : patterns) {\n\t\t\t\t\tSet<Graph> patternSources = pattern.getSources();\n\t\t\t\t\t// check if pattern meets condition\n\t\t\t\t\tif (containsVar(pattern, sameAsSubjectVar) && sameAsSources.containsAll(patternSources)) {\n\t\t\t\t\t\tmatchCandidates.add(pattern);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// check if any match candidate was found\n\t\t\t\tif (matchCandidates.size() == 0) {\n\t\t\t\t\t// found no patterns to match with sameAs\n\t\t\t\t\t// add sameAs pattern as its own group\n\t\t\t\t\tList<MappedStatementPattern> group = new ArrayList<MappedStatementPattern>();\n\t\t\t\t\tgroup.add(sameAsPattern);\n\t\t\t\t\tpatternGroups.add(group);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// group match candidates with sameAs pattern\n\t\t\t\tfor (MappedStatementPattern pattern : matchCandidates) {\n\t\t\t\t\tmatchedPatterns.add(pattern);\n\t\t\t\t\t// add sameAs pattern with the matched pattern's Sources\n\t\t\t\t\tList<MappedStatementPattern> group = new ArrayList<MappedStatementPattern>();\n\t\t\t\t\tgroup.add(pattern);\n\t\t\t\t\tgroup.add(new MappedStatementPattern(sameAsPattern, pattern.getSources()));\n\t\t\t\t\tpatternGroups.add(group);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// removed all matched patterns from the pattern list\n\t\t\tpatterns.removeAll(matchedPatterns);\n\t\t}\n\t\t\n\t\tif (groupBySource) {\n\t\t\t\n\t\t\t// create map for {Source}->{Pattern}\n\t\t\tMap<Set<Graph>, List<MappedStatementPattern>> sourceMap = new HashMap<Set<Graph>, List<MappedStatementPattern>>();\n\t\t\t\n\t\t\t// add all sameAs groups first, if applicable\n\t\t\tif (groupBySameAs) {\n\t\t\t\tfor (List<MappedStatementPattern> patternList : patternGroups) {\n\t\t\t\t\tSet<Graph> sources = patternList.get(0).getSources();\n\t\t\t\t\tList<MappedStatementPattern> pList = sourceMap.get(sources);\n\t\t\t\t\tif (pList == null) {\n\t\t\t\t\t\tpList = new ArrayList<MappedStatementPattern>();\n\t\t\t\t\t\tsourceMap.put(sources, pList);\n\t\t\t\t\t}\n\t\t\t\t\tpList.addAll(patternList);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t// add all pattern from the list to the source mapping\n\t\t\tfor (MappedStatementPattern pattern : patterns) {\n\t\t\t\tSet<Graph> sources = pattern.getSources();\n\t\t\t\tList<MappedStatementPattern> pList = sourceMap.get(sources);\n\t\t\t\tif (pList == null) {\n\t\t\t\t\tpList = new ArrayList<MappedStatementPattern>();\n\t\t\t\t\tsourceMap.put(sources, pList);\n\t\t\t\t}\n\t\t\t\tpList.add(pattern);\n\t\t\t}\n\t\t\t\n\t\t\t// finally create pattern groups for all source mappings\n\t\t\tpatternGroups.clear();\n//\t\t\tpatternGroups.addAll(sourceMap.values());\n\t\t\t\n\t\t\t// keep groups only if there is no more than one source assigned\n\t\t\tfor (Set<Graph> graphs : sourceMap.keySet()) {\n\t\t\t\tList<MappedStatementPattern> pGroup = sourceMap.get(graphs);\n\t\t\t\tif (graphs.size() == 1) {\n\t\t\t\t\tpatternGroups.add(pGroup);\n\t\t\t\t} else {\n\t\t\t\t\tfor (MappedStatementPattern pattern : pGroup) {\n\t\t\t\t\t\tList<MappedStatementPattern> pList = new ArrayList<MappedStatementPattern>();\n\t\t\t\t\t\tpList.add(pattern);\n\t\t\t\t\t\tpatternGroups.add(pList);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t} else {\n\t\t\t\n\t\t\t// add all patterns from the list as individual group\n\t\t\tfor (MappedStatementPattern pattern : patterns) {\n\t\t\t\tList<MappedStatementPattern> pList = new ArrayList<MappedStatementPattern>();\n\t\t\t\tpList.add(pattern);\n\t\t\t\tpatternGroups.add(pList);\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\t// debugging\n\t\tfor (List<MappedStatementPattern> pList : patternGroups) {\n\t\t\tStringBuffer buffer = new StringBuffer(\"Group [\");\n\t\t\tSet<Graph> sources = null;\n\t\t\tfor (MappedStatementPattern pattern : pList) {\n\t\t\t\tbuffer.append(OperatorTreePrinter.print(pattern)).append(\", \");\n\t\t\t\tif (sources == null) {\n\t\t\t\t\tsources = pattern.getSources();\n\t\t\t\t} else {\n\t\t\t\t\tif (!sources.equals(pattern.getSources()))\n\t\t\t\t\t\tLOGGER.warn(\"not the same sources: \" + sources + \" <-> \" + pattern.getSources());\n\t\t\t\t}\n\t\t\t}\n\t\t\tbuffer.setLength(buffer.length()-2);\n\t\t\tbuffer.append(\"] @\" + sources);\n\t\t\t\n\t\t\tif (LOGGER.isDebugEnabled())\n\t\t\t\tLOGGER.debug(buffer.toString());\n\t\t}\n\t\t\n\t\treturn patternGroups;\n\t}\n\n\tprivate boolean containsVar(StatementPattern pattern, Var var) {\n\t\tString varName = var.getName();\n\t\tVar sVar = pattern.getSubjectVar();\n\t\tVar oVar = pattern.getObjectVar();\n\t\treturn (!sVar.hasValue() && sVar.getName().equals(varName))\n\t\t\t|| (!oVar.hasValue() && oVar.getName().equals(varName));\n\t}\n\n}", "public interface SourceSelector {\n\t\n\tpublic void initialize() throws SailException;\n\t\n\tpublic void setStatistics(RDFStatistics stats);\n\t\n\t/**\n\t * Maps triple patterns to data sources which can contribute results.\n\t * \n\t * @param patterns the SPARQL triple patterns which need to be mapped.\n\t * @return a list triple patterns with mappings to sources.\n\t */\n\tpublic List<MappedStatementPattern> mapSources(List<StatementPattern> patterns);\n\n}" ]
import org.slf4j.LoggerFactory; import de.uni_koblenz.west.splendid.estimation.AbstractCostEstimator; import de.uni_koblenz.west.splendid.estimation.ModelEvaluator; import de.uni_koblenz.west.splendid.helpers.AnnotatingTreePrinter; import de.uni_koblenz.west.splendid.helpers.FilterConditionCollector; import de.uni_koblenz.west.splendid.model.BasicGraphPatternExtractor; import de.uni_koblenz.west.splendid.model.MappedStatementPattern; import de.uni_koblenz.west.splendid.model.SubQueryBuilder; import de.uni_koblenz.west.splendid.sources.SourceSelector; import java.util.List; import org.openrdf.query.BindingSet; import org.openrdf.query.Dataset; import org.openrdf.query.algebra.StatementPattern; import org.openrdf.query.algebra.TupleExpr; import org.openrdf.query.algebra.ValueExpr; import org.openrdf.query.algebra.evaluation.QueryOptimizer; import org.openrdf.query.algebra.helpers.StatementPatternCollector; import org.slf4j.Logger;
/* * This file is part of RDF Federator. * Copyright 2011 Olaf Goerlitz * * RDF Federator is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * RDF Federator is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.optimizer; /** * Base functionality for federated query optimizers * * @author Olaf Goerlitz */ public abstract class AbstractFederationOptimizer implements QueryOptimizer { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractFederationOptimizer.class); protected SourceSelector sourceSelector; protected SubQueryBuilder queryBuilder; protected AbstractCostEstimator costEstimator;
protected ModelEvaluator modelEvaluator;
1
campaignmonitor/createsend-java
src/com/createsend/General.java
[ "public class ExternalSessionOptions {\n\tpublic String Email;\n\tpublic String Chrome;\n\tpublic String Url;\n\tpublic String IntegratorID;\n\tpublic String ClientID;\n}", "public class ExternalSessionResult {\n\tpublic String SessionUrl;\n}", "public class OAuthTokenDetails {\n\tpublic String access_token;\n\tpublic int expires_in;\n\tpublic String refresh_token;\n}", "public class SystemDate {\r\n public Date SystemDate;\r\n}", "public abstract class AuthenticationDetails { }", "public class Configuration {\r\n public static Configuration Current = new Configuration();\r\n\r\n private Properties properties;\r\n private Configuration() {\r\n properties = new Properties();\r\n\r\n try {\r\n InputStream configProperties = getClass().getClassLoader().getResourceAsStream(\"com/createsend/util/config.properties\");\r\n if (configProperties == null) {\r\n throw new FileNotFoundException(\"Could not find config.properties\");\r\n }\r\n properties.load(configProperties);\r\n \r\n InputStream createsendProperties = getClass().getClassLoader().getResourceAsStream(\"createsend.properties\");\r\n if(createsendProperties != null) {\r\n properties.load(createsendProperties);\r\n } \r\n } catch (IOException e) {\r\n e.printStackTrace();\r\n } \r\n }\r\n\r\n public void addPropertiesFile(String filename) throws IOException {\r\n properties.load(ClassLoader.getSystemResourceAsStream(filename));\r\n }\r\n\r\n public String getApiEndpoint() {\r\n return properties.getProperty(\"createsend.endpoint\");\r\n }\r\n\r\n public String getOAuthBaseUri() {\r\n return properties.getProperty(\"createsend.oauthbaseuri\");\r\n }\r\n\r\n public String getWrapperVersion() {\r\n return properties.getProperty(\"createsend.version\");\r\n }\r\n\r\n public boolean isLoggingEnabled() {\r\n return Boolean.parseBoolean(properties.getProperty(\"createsend.logging\"));\r\n }\r\n}\r", "public interface JerseyClient {\r\n\tpublic AuthenticationDetails getAuthenticationDetails();\r\n\tpublic void setAuthenticationDetails(AuthenticationDetails authDetails);\r\n\t\r\n public <T> T get(Class<T> klass, String... pathElements) throws CreateSendException;\r\n public <T> T get(Class<T> klass, MultivaluedMap<String, String> queryString,\r\n String... pathElements) throws CreateSendException; \r\n public <T> T get(Class<T> klass, ErrorDeserialiser<?> errorDeserialiser, \r\n String... pathElements) throws CreateSendException;\r\n public <T> T get(Class<T> klass, MultivaluedMap<String, String> queryString, \r\n ResourceFactory resourceFactory, String... pathElements) throws CreateSendException;\r\n public <T> PagedResult<T> getPagedResult(Integer page, Integer pageSize, String orderField, \r\n String orderDirection, MultivaluedMap<String, String> queryString, String... pathElements) \r\n throws CreateSendException;\r\n\r\n public <T> T post(Class<T> klass, Object entity, String... pathElements) throws CreateSendException;\r\n public <T> T post(Class<T> klass, MultivaluedMap<String, String> queryString, Object entity, String... pathElements) throws CreateSendException;\r\n\r\n public <T> T post(Class<T> klass, Object entity, \r\n ErrorDeserialiser<?> errorDeserialiser, String... pathElements) throws CreateSendException;\r\n public <T> T post(String baseUri, Class<T> klass, Object entity, String... pathElements) throws CreateSendException;\r\n public <T> T post(String baseUri, Class<T> klass, Object entity,\r\n ErrorDeserialiser<?> errorDeserialiser, String... pathElements) throws CreateSendException;\r\n public <T> T post(Class<T> klass, Object entity,\r\n MediaType mediaType, String... pathElements) throws CreateSendException;\r\n public <T> T post(String baseUri, Class<T> klass, Object entity,\r\n MediaType mediaType, String... pathElements) throws CreateSendException;\r\n public <T> T post(String baseUri, Class<T> klass, Object entity,\r\n ErrorDeserialiser<?> errorDeserialiser,\r\n MediaType mediaType, String... pathElements) throws CreateSendException;\r\n\r\n public void put(Object entity, String... pathElements) throws CreateSendException;\r\n public <T> T put(Class<T> klass, Object entity, String... pathElements) throws CreateSendException;\r\n public void put(Object entity, MultivaluedMap<String, String> queryString, String... pathElements) throws CreateSendException;\r\n public void put(Object entity, ErrorDeserialiser<?> errorDeserialiser, String... pathElements) throws CreateSendException;\r\n \r\n public void delete(String... pathElements) throws CreateSendException;\r\n\tpublic void delete(MultivaluedMap<String, String> queryString, String... pathElements) throws CreateSendException;\r\n}\r", "public class JerseyClientImpl implements JerseyClient {\r\n\r\n /**\r\n * As per Jersey docs the creation of a Client is expensive. We cache the client\r\n */\r\n private static Client client;\r\n static {\r\n ClientConfig cc = new DefaultClientConfig(); \r\n cc.getClasses().add(JsonProvider.class); \r\n \r\n Map<String, Object> properties = cc.getProperties();\r\n properties.put(ClientConfig.PROPERTY_CHUNKED_ENCODING_SIZE, 64 * 1024);\r\n properties.put(com.sun.jersey.api.json.JSONConfiguration.FEATURE_POJO_MAPPING, \"true\");\r\n\r\n client = Client.create(cc);\r\n client.setFollowRedirects(false);\r\n\r\n if (Configuration.Current.isLoggingEnabled()) {\r\n client.addFilter(new LoggingFilter(System.out));\r\n }\r\n\r\n client.addFilter(new GZIPContentEncodingFilter(false));\r\n client.addFilter(new UserAgentFilter());\r\n }\r\n\r\n private ErrorDeserialiser<String> defaultDeserialiser = new ErrorDeserialiser<String>(){};\r\n private ResourceFactory authorisedResourceFactory;\r\n private AuthenticationDetails authDetails;\r\n\r\n /**\r\n * Constructs a JerseyClientImpl instance, including an OAuth access token and refresh token.\r\n * @param auth \r\n */\r\n public JerseyClientImpl(AuthenticationDetails auth) {\r\n \tthis.setAuthenticationDetails(auth);\r\n }\r\n \r\n public AuthenticationDetails getAuthenticationDetails() {\r\n \treturn this.authDetails;\r\n }\r\n\r\n\tpublic void setAuthenticationDetails(AuthenticationDetails authDetails) {\r\n\t\tthis.authDetails = authDetails;\r\n \tif (authDetails instanceof OAuthAuthenticationDetails) {\r\n\t\t\tOAuthAuthenticationDetails oauthDetails = (OAuthAuthenticationDetails)authDetails;\r\n\t\t\tauthorisedResourceFactory = new AuthorisedResourceFactory(oauthDetails.getAccessToken());\r\n \t} else if (authDetails instanceof ApiKeyAuthenticationDetails) {\r\n\t\t\tApiKeyAuthenticationDetails apiKeyDetails = (ApiKeyAuthenticationDetails)authDetails;\r\n\t\t\tauthorisedResourceFactory = new AuthorisedResourceFactory(apiKeyDetails.getApiKey(), \"x\");\r\n \t} else {\r\n \t\tauthorisedResourceFactory = new UnauthorisedResourceFactory();\r\n \t}\r\n\t}\r\n\r\n /**\r\n * Performs a HTTP GET on the route specified by the pathElements deserialising the \r\n * result to an instance of klass.\r\n * @param <T> The type of model expected from the API call.\r\n * @param klass The class of the model to deserialise. \r\n * @param pathElements The path of the API resource to access\r\n * @return The model returned from the API call\r\n * @throws CreateSendException If the API call results in a HTTP status code >= 400\r\n */\r\n public <T> T get(Class<T> klass, String... pathElements) throws CreateSendException {\r\n return get(klass, null, authorisedResourceFactory, pathElements);\r\n }\r\n \r\n public <T> T get(Class<T> klass, ErrorDeserialiser<?> errorDeserialiser, \r\n String... pathElements) throws CreateSendException {\r\n return get(klass, null, authorisedResourceFactory, errorDeserialiser, pathElements);\r\n }\r\n \r\n /**\r\n * Performs a HTTP GET on the route specified by the pathElements deserialising the \r\n * result to an instance of klass.\r\n * @param <T> The type of model expected from the API call.\r\n * @param klass The class of the model to deserialise. \r\n * @param queryString The query string params to use for the request. \r\n * Use <code>null</code> when no query string is required.\r\n * @param pathElements The path of the API resource to access\r\n * @return The model returned from the API call\r\n * @throws CreateSendException If the API call results in a HTTP status code >= 400\r\n */\r\n public <T> T get(Class<T> klass, MultivaluedMap<String, String> queryString,\r\n String... pathElements) throws CreateSendException {\r\n return get(klass, queryString, authorisedResourceFactory, pathElements);\r\n }\r\n \r\n public <T> T get(Class<T> klass, MultivaluedMap<String, String> queryString,\r\n ResourceFactory resourceFactory, String... pathElements) throws CreateSendException {\r\n return get(klass, queryString, resourceFactory, defaultDeserialiser, pathElements);\r\n }\r\n \r\n public <T> T get(Class<T> klass, MultivaluedMap<String, String> queryString,\r\n ResourceFactory resourceFactory, ErrorDeserialiser<?> errorDeserialiser, \r\n String... pathElements) throws CreateSendException {\r\n WebResource resource = resourceFactory.getResource(client, pathElements);\r\n \r\n if(queryString != null) {\r\n resource = resource.queryParams(queryString);\r\n }\r\n \r\n try {\r\n return fixStringResult(klass, resource.get(klass));\r\n } catch (UniformInterfaceException ue) {\r\n throw handleErrorResponse(ue, errorDeserialiser);\r\n } \r\n }\r\n \r\n /**\r\n * Performs a HTTP GET on the route specified attempting to deserialise the\r\n * result to a paged result of the given type.\r\n * @param <T> The type of paged result data expected from the API call. \r\n * @param queryString The query string values to use for the request.\r\n * @param pathElements The path of the API resource to access\r\n * @return The model returned from the API call\r\n * @throws CreateSendException If the API call results in a HTTP status code >= 400\r\n */\r\n public <T> PagedResult<T> getPagedResult(Integer page, Integer pageSize, String orderField, \r\n String orderDirection, MultivaluedMap<String, String> queryString, String... pathElements) \r\n throws CreateSendException {\r\n WebResource resource = authorisedResourceFactory.getResource(client, pathElements);\r\n if(queryString == null) queryString = new MultivaluedMapImpl();\r\n \r\n addPagingParams(queryString, page, pageSize, orderField, orderDirection);\r\n \r\n try {\r\n if(queryString != null) {\r\n resource = resource.queryParams(queryString);\r\n }\r\n \r\n return resource.get(new GenericType<PagedResult<T>>(getGenericReturnType()));\r\n } catch (UniformInterfaceException ue) {\r\n throw handleErrorResponse(ue, defaultDeserialiser);\r\n } catch (SecurityException e) {\r\n e.printStackTrace();\r\n }\r\n \r\n return null;\r\n }\r\n \r\n /**\r\n * Posts the provided entity to the url specified by the provided path elements. \r\n * The result of the call will be deserialised to an instance of the specified class.\r\n * @param <T> The class to use for model deserialisation\r\n * @param klass The class to use for model deserialisation\r\n * @param entity The entity to use as the body of the post request\r\n * @param pathElements The path to send the post request to\r\n * @return An instance of klass returned by the api call\r\n * @throws CreateSendException Thrown when the API responds with a HTTP Status >= 400\r\n */\r\n public <T> T post(Class<T> klass, Object entity, String... pathElements) throws CreateSendException {\r\n return post(null, klass, entity, defaultDeserialiser, MediaType.APPLICATION_JSON_TYPE, pathElements);\r\n }\r\n\r\n public <T> T post(Class<T> klass, MultivaluedMap<String, String> queryString, Object entity, String... pathElements) throws CreateSendException {\r\n return post(null, klass, queryString, entity, defaultDeserialiser, MediaType.APPLICATION_JSON_TYPE, pathElements);\r\n }\r\n\r\n public <T> T post(Class<T> klass, Object entity, \r\n ErrorDeserialiser<?> errorDeserialiser, String... pathElements) throws CreateSendException {\r\n \treturn post(null, klass, entity, errorDeserialiser, MediaType.APPLICATION_JSON_TYPE, pathElements);\r\n }\r\n\r\n public <T> T post(String baseUri, Class<T> klass, Object entity, String... pathElements) throws CreateSendException {\r\n return post(baseUri, klass, entity, defaultDeserialiser, MediaType.APPLICATION_JSON_TYPE, pathElements);\r\n }\r\n\r\n public <T> T post(String baseUri, Class<T> klass, Object entity,\r\n ErrorDeserialiser<?> errorDeserialiser, String... pathElements) throws CreateSendException {\r\n \treturn post(baseUri, klass, entity, errorDeserialiser, MediaType.APPLICATION_JSON_TYPE, pathElements);\r\n }\r\n\r\n public <T> T post(Class<T> klass, Object entity,\r\n MediaType mediaType, String... pathElements) throws CreateSendException {\r\n \treturn post(null, klass, entity, defaultDeserialiser, mediaType, pathElements);\r\n }\r\n\r\n public <T> T post(String baseUri, Class<T> klass, Object entity,\r\n MediaType mediaType, String... pathElements) throws CreateSendException {\r\n \treturn post(baseUri, klass, entity, defaultDeserialiser, mediaType, pathElements);\r\n }\r\n\r\n public <T> T post(String baseUri, Class<T> klass, Object entity,\r\n ErrorDeserialiser<?> errorDeserialiser,\r\n MediaType mediaType, String... pathElements) throws CreateSendException {\r\n \treturn post(baseUri, klass, null, entity, errorDeserialiser, mediaType, pathElements);\r\n }\r\n\r\n private <T> T post(String baseUri,\r\n Class<T> klass,\r\n MultivaluedMap<String, String> queryString,\r\n Object entity,\r\n ErrorDeserialiser<?> errorDeserialiser,\r\n MediaType mediaType,\r\n String... pathElements) throws CreateSendException {\r\n WebResource resource;\r\n if (baseUri != null)\r\n resource = authorisedResourceFactory.getResource(baseUri, client, pathElements);\r\n else\r\n resource = authorisedResourceFactory.getResource(client, pathElements);\r\n\r\n if( queryString != null )\r\n resource = resource.queryParams(queryString);\r\n\r\n try {\r\n WebResource.Builder builder = resource.type(mediaType);\r\n\r\n return fixStringResult(klass,\r\n entity == null ?\r\n builder.post(klass, \"\") :\r\n builder.post(klass, entity)\r\n );\r\n } catch (UniformInterfaceException ue) {\r\n throw handleErrorResponse(ue, errorDeserialiser);\r\n }\r\n }\r\n\r\n\r\n /**\r\n * Makes a HTTP PUT request to the path specified, using the provided entity as the \r\n * request body.\r\n * @param entity The entity to use as the request body\r\n * @param pathElements The path to make the request to.\r\n * @throws CreateSendException Raised when the API responds with a HTTP Status >= 400\r\n */\r\n public void put(Object entity, String... pathElements) throws CreateSendException {\r\n put(entity, null, defaultDeserialiser, pathElements);\r\n }\r\n \r\n public <T> T put(Class<T> klass, Object entity, String... pathElements) throws CreateSendException {\r\n WebResource resource = authorisedResourceFactory.getResource(client, pathElements);\r\n try { \r\n return fixStringResult(klass, resource.\r\n type(MediaType.APPLICATION_JSON_TYPE).\r\n put(klass, entity));\r\n } catch (UniformInterfaceException ue) {\r\n throw handleErrorResponse(ue, defaultDeserialiser);\r\n }\r\n }\r\n \r\n public void put(Object entity, MultivaluedMap<String, String> queryString, String... pathElements) throws CreateSendException {\r\n put(entity, queryString, defaultDeserialiser, pathElements);\r\n }\r\n \r\n public void put(Object entity, ErrorDeserialiser<?> errorDeserialiser,\r\n String... pathElements) throws CreateSendException {\r\n put(entity, null, errorDeserialiser, pathElements);\r\n }\r\n\r\n private void put(Object entity, MultivaluedMap<String, String> queryString, ErrorDeserialiser<?> errorDeserialiser,\r\n String... pathElements) throws CreateSendException {\r\n WebResource resource = authorisedResourceFactory.getResource(client, pathElements);\r\n \r\n if(queryString != null) {\r\n resource = resource.queryParams(queryString);\r\n }\r\n \r\n try { \r\n resource.\r\n type(MediaType.APPLICATION_JSON_TYPE).\r\n put(entity);\r\n } catch (UniformInterfaceException ue) {\r\n throw handleErrorResponse(ue, errorDeserialiser);\r\n }\r\n }\r\n\r\n /**\r\n * Makes a HTTP DELETE request to the specified path\r\n * @param pathElements The path of the resource to delete\r\n * @throws CreateSendException Raised when the API responds with a HTTP Status >= 400\r\n */\r\n public void delete(String... pathElements) throws CreateSendException {\r\n delete(null, pathElements);\r\n }\r\n \r\n /**\r\n * Makes a HTTP DELETE request to the specified path with the specified query string\r\n * @param pathElements The path of the resource to delete\r\n * @throws CreateSendException Raised when the API responds with a HTTP Status >= 400\r\n */\r\n @Override\r\n\tpublic void delete(MultivaluedMap<String, String> queryString, String... pathElements) throws CreateSendException {\r\n WebResource resource = authorisedResourceFactory.getResource(client, pathElements);\r\n \r\n if( queryString != null )\r\n \tresource = resource.queryParams(queryString);\r\n \r\n try { \r\n resource.delete();\r\n } catch (UniformInterfaceException ue) {\r\n throw handleErrorResponse(ue, defaultDeserialiser);\r\n }\r\n }\r\n\r\n protected void addPagingParams(MultivaluedMap<String, String> queryString, \r\n Integer page, Integer pageSize, String orderField, String orderDirection) { \r\n if(page != null) {\r\n queryString.add(\"page\", page.toString());\r\n }\r\n \r\n if(pageSize != null) {\r\n queryString.add(\"pagesize\", pageSize.toString());\r\n }\r\n \r\n if(orderField != null) {\r\n queryString.add(\"orderfield\", orderField); \r\n }\r\n \r\n if(orderDirection != null) {\r\n queryString.add(\"orderdirection\", orderDirection);\r\n }\r\n }\r\n \r\n /**\r\n * Jersey is awesome in that even though we specify a JSON response and to use \r\n * the {@link com.createsend.util.jersey.JsonProvider} it sees that we want a \r\n * String result and that the response is already a String so just use that. \r\n * This method strips any enclosing quotes required as per the JSON spec. \r\n * @param <T> The type of result we are expecting\r\n * @param klass The class of the provided result\r\n * @param result The result as deserialised by Jersey\r\n * @return If the result if anything but a String just return the result. \r\n * If the result is a String then strip any enclosing quotes (\"). \r\n */\r\n @SuppressWarnings(\"unchecked\")\r\n protected <T> T fixStringResult(Class<T> klass, T result) {\r\n if(klass == String.class) { \r\n String strResult = (String)result;\r\n if(strResult.startsWith(\"\\\"\")) { \r\n strResult = strResult.substring(1);\r\n }\r\n \r\n if(strResult.endsWith(\"\\\"\")) {\r\n strResult = strResult.substring(0, strResult.length() - 1);\r\n }\r\n \r\n return (T)strResult;\r\n }\r\n \r\n return result;\r\n }\r\n \r\n /**\r\n * Creates an exception, inheriting from @{link com.createsend.util.exceptions.CreateSendException} \r\n * to represent the API error resulting in the raised {@link com.sun.jersey.api.client.UniformInterfaceException}\r\n * @param ue The error raised during the failed API request\r\n * @return An exception representing the API error\r\n */\r\n private <T> CreateSendException handleErrorResponse(UniformInterfaceException ue, \r\n ErrorDeserialiser<T> deserialiser) {\r\n ClientResponse response = ue.getResponse();\r\n ApiErrorResponse<T> apiResponse = null;\r\n \r\n Status responseStatus = response.getClientResponseStatus();\r\n if(responseStatus == Status.BAD_REQUEST || \r\n responseStatus == Status.NOT_FOUND ||\r\n responseStatus == Status.UNAUTHORIZED ||\r\n responseStatus == Status.INTERNAL_SERVER_ERROR) {\r\n try { \r\n apiResponse = deserialiser.getResponse(response);\r\n } catch (Throwable t) { } \r\n }\r\n\r\n if (apiResponse == null) {\r\n return handleUnknownError(responseStatus);\r\n } else if (apiResponse.error != null && apiResponse.error.length() > 0) {\r\n return handleOAuthErrorResponse(responseStatus, apiResponse);\r\n } else {\r\n \treturn handleAPIErrorResponse(responseStatus, apiResponse);\r\n }\r\n }\r\n\r\n private <T> CreateSendException handleUnknownError(Status responseStatus) {\r\n return new CreateSendHttpException(responseStatus);\r\n }\r\n \r\n private <T> CreateSendException handleAPIErrorResponse(\r\n \t\tStatus responseStatus, ApiErrorResponse<T> apiResponse) {\r\n switch(responseStatus) {\r\n\t case BAD_REQUEST:\r\n\t return new BadRequestException(apiResponse.Code, apiResponse.Message, apiResponse.ResultData);\r\n\t case INTERNAL_SERVER_ERROR:\r\n\t return new ServerErrorException(apiResponse.Code, apiResponse.Message);\r\n\t case NOT_FOUND:\r\n\t return new NotFoundException(apiResponse.Code, apiResponse.Message);\r\n\t case UNAUTHORIZED:\r\n\t \tif (apiResponse.Code == 121)\r\n\t \t\treturn new ExpiredOAuthTokenException(apiResponse.Code, apiResponse.Message);\r\n\t return new UnauthorisedException(apiResponse.Code, apiResponse.Message);\r\n\t default:\r\n\t return new CreateSendHttpException(responseStatus);\r\n\t }\r\n }\r\n\r\n private <T> CreateSendException handleOAuthErrorResponse(\r\n \t\tStatus responseStatus, ApiErrorResponse<T> apiResponse) {\r\n \treturn new CreateSendHttpException(\r\n \t\t\tString.format(\"The CreateSend OAuth receiver responded with the following error - %s: %s\",\r\n \t\t\t\t\tapiResponse.error, apiResponse.error_description),\r\n \t\t\tresponseStatus.getStatusCode(), 0, apiResponse.error_description);\r\n }\r\n\r\n private ParameterizedType getGenericReturnType() {\r\n return getGenericReturnType(null, 4);\r\n }\r\n \r\n public static ParameterizedType getGenericReturnType(Class<?> klass, int stackFrame) { \r\n StackTraceElement element = Thread.currentThread().getStackTrace()[stackFrame];\r\n String callingMethodName = element.getMethodName();\r\n \r\n if(klass == null) {\r\n try { \r\n klass = Class.forName(element.getClassName());\r\n } catch (ClassNotFoundException e) { }\r\n }\r\n \r\n if (klass != null) {\r\n for (Method method : klass.getMethods()) {\r\n if (method.getName().equals(callingMethodName)) {\r\n return (ParameterizedType) method.getGenericReturnType();\r\n }\r\n }\r\n }\r\n \r\n return null;\r\n }\r\n}\r", "public class CreateSendException extends Exception {\r\n private static final long serialVersionUID = 1695317869199799783L;\r\n \r\n public CreateSendException(String message) {\r\n super(message);\r\n }\r\n}\r" ]
import com.createsend.models.OAuthTokenDetails; import com.createsend.models.SystemDate; import com.createsend.models.administrators.Administrator; import com.createsend.models.administrators.AdministratorResult; import com.createsend.models.clients.ClientBasics; import com.createsend.util.AuthenticationDetails; import com.createsend.util.Configuration; import com.createsend.util.JerseyClient; import com.createsend.util.JerseyClientImpl; import com.createsend.util.exceptions.CreateSendException; import com.sun.jersey.core.util.MultivaluedMapImpl; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Date; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import com.createsend.models.ExternalSessionOptions; import com.createsend.models.ExternalSessionResult;
/** * Copyright (c) 2011 Toby Brain * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.createsend; /** * Provides methods for accessing all * <a href="http://www.campaignmonitor.com/api/account/" target="_blank">Account</a> * methods in the Campaign Monitor API * */ public class General extends CreateSendBase { /** * Constructor. * @param auth The authentication details to use when making API calls. * May be either an OAuthAuthenticationDetails or * ApiKeyAuthenticationDetails instance. */ public General(AuthenticationDetails auth) { this.jerseyClient = new JerseyClientImpl(auth); } /** * Get the authorization URL for your application, given the application's * Client ID, Redirect URI, Scope, and optional State data. * @param clientID The Client ID value for your application. * @param redirectUri The Redirect URI value for your application. * @param scope The permission scope your application is requesting. * @param state Optional state data to include in the authorization URL. * @return The authorization URL to which your application should redirect * your users. */ public static String getAuthorizeUrl( int clientID, String redirectUri, String scope, String state) { String qs = "client_id=" + String.valueOf(clientID); try { qs += "&redirect_uri=" + URLEncoder.encode(redirectUri, URL_ENCODING_SCHEME); qs += "&scope=" + URLEncoder.encode(scope, URL_ENCODING_SCHEME); if (state != null) qs += "&state=" + URLEncoder.encode(state, URL_ENCODING_SCHEME); } catch (UnsupportedEncodingException e) { qs = null; } return Configuration.Current.getOAuthBaseUri() + "?" + qs; } /** * Exchange a provided OAuth code for an OAuth access token, 'expires in' * value, and refresh token. * @param clientID The Client ID value for your application. * @param clientSecret The Client Secret value for your application. * @param redirectUri The Redirect URI value for your application. * @param code A unique code provided to your user which can be exchanged * for an access token. * @return An OAuthTokenDetails object containing the access token, * 'expires in' value, and refresh token. */
public static OAuthTokenDetails exchangeToken(
2
Drusy/Wisper
wisper-libgdx/core/src/java/fr/wisper/screens/gamescreen/WisperChooseMenu.java
[ "public class WisperGame extends Game {\n // Fps\n private FPSLogger fps;\n\n // Preferences\n public static Preferences preferences;\n\n // Loader\n private LoadingScreen loader;\n\n // Camera\n static public OrthographicCameraWithVirtualViewport Camera;\n static public MultipleVirtualViewportBuilder MultipleVirtualViewportBuilder;\n static public VirtualViewport VirtualViewport;\n\n @Override\n\tpublic void create () {\n // Preferences\n preferences = Gdx.app.getPreferences(Config.GAME_NAME);\n\n // Fps\n fps = new FPSLogger();\n\n // Camera\n MultipleVirtualViewportBuilder = new MultipleVirtualViewportBuilder(\n Config.APP_WIDTH, Config.APP_HEIGHT,\n Config.APP_WIDTH, Config.APP_HEIGHT);\n VirtualViewport = MultipleVirtualViewportBuilder.getVirtualViewport(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());\n Camera = new OrthographicCameraWithVirtualViewport(VirtualViewport);\n\n // Loader\n loader = new LoadingScreen(this);\n loader.setNextScreen(new MainMenu());\n\n Debug.PrintDebugInformation();\n\t}\n\n public LoadingScreen getLoader() {\n return loader;\n }\n\n\t@Override\n\tpublic void render () {\n super.render();\n\n fps.log();\n\t}\n\n @Override\n public void pause() {\n super.pause();\n }\n\n @Override\n public void dispose() {\n super.dispose();\n\n loader.dispose();\n }\n\n @Override\n public void resume() {\n super.resume();\n }\n\n @Override\n public void resize(int width, int height) {\n VirtualViewport = MultipleVirtualViewportBuilder.getVirtualViewport(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());\n\n Camera.setVirtualViewport(VirtualViewport);\n Camera.updateViewport();\n Camera.position.set(Config.APP_WIDTH / 2, Config.APP_HEIGHT / 2, 0f);\n\n super.resize(width, height);\n }\n}", "public class WisperChooseAssets {\n\n public static AnnotationAssetManager manager;\n\n public static void load() {\n manager = new AnnotationAssetManager();\n manager.load(WisperChooseAssets.class);\n }\n\n\n @Asset\n public static final AssetDescriptor<Skin>\n GlobalSkin = new AssetDescriptor<Skin>(\"ui/skin.json\", Skin.class, new SkinLoader.SkinParameter(\"ui/atlas.pack\"));\n\n\n public static void dispose() {\n manager.dispose();\n }\n\n}", "public class AnimatedWisper extends Wisper {\n private List<WisperAnimation> animations = new ArrayList<WisperAnimation>();\n private Random random = new Random();\n private Timer animationTimer = new Timer();\n private Timer.Task animationTimerTask;\n\n public AnimatedWisper(String particleFile) {\n super(particleFile);\n\n initRightLeftAnimation();\n initTopBottomAnimation();\n }\n\n public void animate(final TweenManager tweenManager) {\n scheduleAnimation(tweenManager, Config.WISPER_TIME_FIRST_ANIMATIONS);\n }\n\n private void scheduleAnimation(final TweenManager tweenManager, final long delay) {\n animationTimerTask = new Timer.Task() {\n @Override\n public void run() {\n // Start animation\n animations.get(random.nextInt(animations.size())).animate(tweenManager);\n\n // Schedule next Animation\n scheduleAnimation(tweenManager, Config.WISPER_TIME_BETWEEN_ANIMATIONS);\n }\n };\n animationTimer.scheduleTask(animationTimerTask, delay);\n }\n\n private void initRightLeftAnimation() {\n animations.add(new WisperAnimation() {\n @Override\n public void animate(final TweenManager tweenManager) {\n final int baseX = (int)getX();\n final int baseY = (int)getY();\n final double duration = 2;\n final int offset = 100;\n final TweenEquation equation = Cubic.INOUT;\n\n final TweenCallback resetPositionCallback = new TweenCallback() {\n @Override\n public void onEvent(int type, BaseTween<?> source) {\n moveToWithDuration(baseX + AnimatedWisper.this.offset, baseY, tweenManager, duration, equation, null);\n }\n };\n\n TweenCallback moveRightCallBack = new TweenCallback() {\n @Override\n public void onEvent(int type, BaseTween<?> source) {\n moveToWithDuration(baseX + offset + AnimatedWisper.this.offset, baseY, tweenManager, duration, equation, resetPositionCallback);\n }\n };\n\n // First move left, then right callback, then reset\n moveToWithDuration(baseX - offset, baseY, tweenManager, duration, equation, moveRightCallBack);\n }\n });\n }\n\n public void initTopBottomAnimation() {\n\n animations.add(new WisperAnimation() {\n @Override\n public void animate(final TweenManager tweenManager) {\n final int baseX = (int)getX();\n final int baseY = (int)getY();\n final double duration = 2;\n final int offset = 100;\n final TweenEquation equation = Cubic.INOUT;\n\n final TweenCallback resetPositionCallback = new TweenCallback() {\n @Override\n public void onEvent(int type, BaseTween<?> source) {\n moveToWithDuration(baseX + AnimatedWisper.this.offset, baseY, tweenManager, duration, equation, null);\n }\n };\n\n TweenCallback moveRightCallBack = new TweenCallback() {\n @Override\n public void onEvent(int type, BaseTween<?> source) {\n moveToWithDuration(baseX + AnimatedWisper.this.offset, baseY + offset, tweenManager, duration, equation, resetPositionCallback);\n }\n };\n\n // First move left, then right callback, then reset\n moveToWithDuration(baseX + AnimatedWisper.this.offset, baseY - offset, tweenManager, duration, equation, moveRightCallBack);\n }\n });\n\n }\n}", "public class TableAccessor implements TweenAccessor<Table> {\n\n public static final int ALPHA = 0;\n\n @Override\n public int getValues(Table target, int tweenType, float[] returnValues) {\n switch (tweenType) {\n case ALPHA:\n returnValues[0] = target.getColor().a;\n return 1;\n default:\n assert false;\n return -1;\n }\n }\n\n @Override\n public void setValues(Table target, int tweenType, float[] newValues) {\n switch (tweenType) {\n case ALPHA:\n target.setColor(\n target.getColor().r,\n target.getColor().g,\n target.getColor().b,\n newValues[0]\n );\n break;\n default:\n assert false;\n }\n }\n}", "public class Wisper extends Actor {\n public static final int BLACK_WISPER = 0;\n public static final int BLUE_WISPER = 1;\n public static final int RED_WISPER = 2;\n\n protected ParticleEffect particleEffect;\n protected boolean isParticleOn = true;\n protected boolean isDashUp = true;\n protected Timer timer = new Timer();\n protected Timer.Task timerTask;\n protected float offset;\n protected SpeechBubble bubbleSpeech;\n\n private List<String> speechList = new ArrayList<String>();\n\n public Wisper(String particleFile) {\n particleEffect = new ParticleEffect();\n init(particleFile);\n }\n\n public void setPosition(float x, float y) {\n particleEffect.setPosition(x - offset, y);\n }\n\n public void scale(float scaleValue) {\n float scaling;\n\n for (ParticleEmitter emitter : particleEffect.getEmitters()) {\n scaling = emitter.getScale().getHighMax();\n emitter.getScale().setHigh(scaling * scaleValue);\n\n scaling = emitter.getScale().getLowMax();\n emitter.getScale().setLow(scaling * scaleValue);\n\n scaling = emitter.getVelocity().getHighMax();\n emitter.getVelocity().setHigh(scaling * scaleValue);\n\n scaling = emitter.getVelocity().getLowMax();\n emitter.getVelocity().setLow(scaling * scaleValue);\n\n scaling = emitter.getXOffsetValue().getLowMax();\n emitter.getXOffsetValue().setLow(scaling * scaleValue);\n\n scaling = emitter.getYOffsetValue().getLowMax();\n emitter.getYOffsetValue().setLow(scaling * scaleValue);\n }\n }\n\n public void draw(Batch batch, float delta) {\n if (isParticleOn) {\n particleEffect.draw(batch, delta);\n\n if (bubbleSpeech != null && bubbleSpeech.isAlive()) {\n bubbleSpeech.act(delta);\n bubbleSpeech.draw(batch, delta);\n } else if (!speechList.isEmpty()) {\n speech(speechList.get(0));\n speechList.remove(0);\n }\n }\n }\n\n public boolean isComplete() {\n return particleEffect.isComplete();\n }\n\n public void startIntroSpeech() {\n speechList.add(\"Hello, I'm a Wisper\");\n speechList.add(\"Click the world to make me move\");\n speechList.add(\"Double click to dash!\");\n }\n\n public void speech(String string) {\n NinePatch ninePatch = MenuAssets.manager.get(MenuAssets.BubbleAtlas).createPatch(\"bubble\");\n BitmapFont bubbleFont = MenuAssets.manager.get(MenuAssets.BubbleFont);\n bubbleSpeech = new SpeechBubble(ninePatch, bubbleFont);\n bubbleSpeech.init(string, getX(), getY());\n bubbleSpeech.setFollow(this);\n bubbleSpeech.setColor(new Color(0.3f, 0.3f, 0.3f, 0.7f));\n }\n\n public float getOffset() {\n return offset;\n }\n\n public void stopDraw() {\n speechList.clear();\n isParticleOn = false;\n }\n\n private void init(String particleFile) {\n particleEffect.load(Gdx.files.internal(particleFile), Gdx.files.internal(\"particles\"));\n particleEffect.setPosition(Config.APP_WIDTH / 2, Config.APP_HEIGHT / 2);\n particleEffect.start();\n\n offset = particleEffect.getEmitters().first().getXOffsetValue().getLowMax() / 2;\n }\n\n @Override\n public float getX() {\n return (int)particleEffect.getEmitters().first().getX();\n }\n\n @Override\n public float getY() {\n return (int)particleEffect.getEmitters().first().getY();\n }\n\n public void moveTo(float x, float y, TweenManager tweenManager, TweenCallback callback) {\n //Vector2 particlePos = Config.getProjectedCoordinates(getX(), getY(), viewport);\n //Vector2 requestedPos = Config.getProjectedCoordinates(x, y, viewport);\n\n Vector2 particlePos = new Vector2(getX(), getY());\n Vector2 requestedPos = new Vector2(x, y);\n\n double distance = Math.sqrt(\n (float)Math.pow(particlePos.x - requestedPos.x, 2) +\n (float)Math.pow(particlePos.y - requestedPos.y, 2));\n double duration = distance / Config.WISPER_SPEED;\n\n moveToWithDuration(x, y, tweenManager, duration, Quad.OUT, callback);\n }\n\n public void moveToWithDuration(float x, float y, TweenManager tweenManager, double duration, TweenEquation equation, TweenCallback callback) {\n tweenManager.killTarget(particleEffect);\n Tween.to(particleEffect, ParticleEffectAccessor.X, (float)duration)\n .target(x - (particleEffect.getEmitters().first().getXOffsetValue().getLowMax() / 2))\n .ease(equation).start(tweenManager);\n Tween.to(particleEffect, ParticleEffectAccessor.Y, (float)duration).target(y)\n .ease(equation).start(tweenManager).setCallback(callback);\n }\n\n public void dash(final float x, final float y, final TweenManager tweenManager) {\n if (isDashUp) {\n Vector2 particlePos = new Vector2(getX(), getY());\n Vector2 requestedPos = new Vector2(x, y);\n\n double distance = Math.max(\n Math.sqrt(Math.pow(particlePos.x - requestedPos.x, 2) + Math.pow(particlePos.y - requestedPos.y, 2)),\n 1);\n double dashDistance = Math.min(distance, Config.WISPER_DASH_DISTANCE);\n float alpha = (float)dashDistance / (float)distance;\n\n Vector2 AB = new Vector2(requestedPos.x - particlePos.x, requestedPos.y - particlePos.y);\n Vector2 ABPrim = new Vector2(alpha * AB.x, alpha * AB.y);\n Vector2 BPrim = new Vector2(ABPrim.x + particlePos.x, ABPrim.y + particlePos.y);\n\n tweenManager.killTarget(particleEffect);\n Tween.to(particleEffect, ParticleEffectAccessor.X, Config.WISPER_DASH_DURATION)\n .target(BPrim.x - (particleEffect.getEmitters().first().getXOffsetValue().getLowMax() / 2))\n .ease(Quad.OUT).start(tweenManager);\n Tween.to(particleEffect, ParticleEffectAccessor.Y, Config.WISPER_DASH_DURATION).target(BPrim.y)\n .ease(Quad.OUT).setCallback(new TweenCallback() {\n @Override\n public void onEvent(int type, BaseTween<?> source) {\n moveTo(x, y, tweenManager, null);\n }\n }).start(tweenManager);\n\n timerTask = new Timer.Task() {\n @Override\n public void run() {\n isDashUp = true;\n }\n };\n isDashUp = false;\n timer.scheduleTask(timerTask, (long) Config.WISPER_DASH_TIMEOUT);\n } else {\n moveTo(x, y, tweenManager, null);\n Debug.Log(\"Dash not ready yet, \" + (timerTask.getExecuteTimeMillis() - System.nanoTime() / 1000000) + \"ms remaining\");\n }\n }\n\n public void explode() {\n init(\"particles/spark.p\");\n }\n\n public void dispose() {\n stopDraw();\n if (bubbleSpeech != null) {\n bubbleSpeech.dispose();\n }\n particleEffect.dispose();\n }\n}", "public class LoadingScreen implements Screen {\n private final int LoadingBarWidth = 450;\n private final int LoadingBarHeight = 450;\n\n private Stage stage;\n private FadingScreen nextScreen;\n private WisperGame game;\n\n private Image logo;\n private Image loadingFrame;\n private Image loadingBarHidden;\n private Image loadingBg;\n\n private float startX, endX;\n private float percent;\n\n private Actor loadingBar;\n\n public LoadingScreen(WisperGame game) {\n // Assets\n LoaderAssets.load();\n LoaderAssets.manager.finishLoading();\n\n // Stage\n this.game = game;\n stage = new Stage();\n\n // Get our textureatlas from the manager\n TextureAtlas atlas = LoaderAssets.manager.get(LoaderAssets.LoaderPack);\n\n // Grab the regions from the atlas and create some images\n logo = new Image(atlas.findRegion(\"libgdx-logo\"));\n loadingFrame = new Image(atlas.findRegion(\"loading-frame\"));\n loadingBarHidden = new Image(atlas.findRegion(\"loading-bar-hidden\"));\n loadingBg = new Image(atlas.findRegion(\"loading-frame-bg\"));\n\n // Add the loading bar animation\n //Animation anim = new Animation(0.05f, atlas.findRegions(\"loading-bar-anim\") );\n //anim.setPlayMode(Animation.PlayMode.LOOP_REVERSED);\n //loadingBar = new LoadingBar(anim);\n\n // Or if you only need a static bar, you can do\n loadingBar = new Image(atlas.findRegion(\"loading-bar1\"));\n\n // Add all the actors to the stage\n stage.addActor(loadingBar);\n stage.addActor(loadingBg);\n stage.addActor(loadingBarHidden);\n stage.addActor(loadingFrame);\n stage.addActor(logo);\n\n initLoadingScreen();\n }\n\n @Override\n public void show() {\n percent = 0f;\n }\n\n private void initLoadingScreen() {\n // Place the logo in the middle of the screen and 100 px up\n logo.setX((Config.APP_WIDTH - logo.getWidth()) / 2);\n logo.setY((Config.APP_HEIGHT - logo.getHeight()) / 2 + 100);\n\n // Place the loading frame in the middle of the screen\n loadingFrame.setX((Config.APP_WIDTH - loadingFrame.getWidth()) / 2);\n loadingFrame.setY((Config.APP_HEIGHT - loadingFrame.getHeight()) / 2);\n\n // Place the loading bar at the same spot as the frame, adjusted a few px\n loadingBar.setX(loadingFrame.getX() + 15);\n loadingBar.setY(loadingFrame.getY() + 5);\n\n // Place the image that will hide the bar on top of the bar, adjusted a few px\n loadingBarHidden.setX(loadingBar.getX() + 35);\n loadingBarHidden.setY(loadingBar.getY() - 3);\n // The start position and how far to move the hidden loading bar\n startX = loadingBarHidden.getX();\n endX = LoadingBarWidth - 10;\n\n // The rest of the hidden bar\n loadingBg.setSize(LoadingBarWidth, LoadingBarHeight);\n loadingBg.setX(loadingBarHidden.getX() + 30);\n loadingBg.setY(loadingBarHidden.getY() + 3);\n }\n\n public void setNextScreen(FadingScreen screen) {\n Screen screenToLoad = this;\n\n screen.load();\n nextScreen = screen;\n\n if (screen.getAssetManager() == null || screen.getAssetManager().update()) {\n screenToLoad = screen;\n }\n\n game.setScreen(screenToLoad);\n }\n\n @Override\n public void resize(int width, int height) {\n WisperGame.Camera.zoom = 1f;\n WisperGame.Camera.updateViewport();\n\n ScalingViewport stageViewport = new ScalingViewport(\n Scaling.fit,\n WisperGame.VirtualViewport.getVirtualWidth(),\n WisperGame.VirtualViewport.getVirtualHeight(),\n WisperGame.Camera);\n\n stage.setViewport(stageViewport);\n stage.getViewport().update(width, height, true);\n }\n\n @Override\n public void render(float delta) {\n Gdx.gl.glClearColor(0.95f, 0.95f, 0.95f, 1);\n Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);\n\n // Interpolate the percentage to make it more smooth\n //percent = Interpolation.linear.apply(percent, nextScreen.getAssetManager().getProgress(), 0.1f);\n percent = nextScreen.getAssetManager().getProgress();\n\n // Update positions (and size) to match the percentage\n loadingBarHidden.setX(startX + endX * percent);\n loadingBg.setX(loadingBarHidden.getX() + 30);\n loadingBg.setWidth(LoadingBarWidth - LoadingBarWidth * percent);\n loadingBg.invalidate();\n\n // Show the loading screen\n stage.act();\n stage.draw();\n\n if (nextScreen.getAssetManager().update()) {\n ((Game) Gdx.app.getApplicationListener()).setScreen(nextScreen);\n }\n }\n\n @Override\n public void hide() {\n }\n\n @Override\n public void pause() {\n\n }\n\n @Override\n public void resume() {\n\n }\n\n @Override\n public void dispose() {\n LoaderAssets.dispose();\n }\n}", "public class Config {\n public static final String GAME_NAME = \"Wisper\";\n public static final String GAME_VERSION = \"v0.1\";\n public static final int APP_WIDTH = 1280;\n public static final int APP_HEIGHT = 768;\n public static final String DEFAULT_SAVE_FOLDER = Config.GAME_NAME + \"/saves\";\n public static final float ANIMATION_DURATION = 1.5f;\n public static final float WISPER_SPEED = 150;\n public static final float DOUBLE_TAP_INTERVAL = 500f;\n public static final float WISPER_DASH_DISTANCE = 300f;\n public static final float WISPER_DASH_DURATION = 0.25f;\n public static final float WISPER_DASH_TIMEOUT = 2f;\n public static final long WISPER_TIME_BETWEEN_ANIMATIONS = 8000;\n public static final long WISPER_TIME_FIRST_ANIMATIONS = 3000;\n public static final float GAME_RATIO = 0.1f;\n public static final float BOX2D_WISPER_MOVE_FORCE = 500f;\n public static final float BOX2D_WISPER_MOVE_DAMPING = 15f;\n public static final float BOX2D_WISPER_DASH_FORCE = 50000f;\n public static final float BOX2D_WISPER_DASH_DAMPING = 3.5f;\n public static final float BOX2D_WISPER_DASH_TIME = 0.35f;\n\n public static boolean isAndroid() {\n return (Gdx.app.getType() == Application.ApplicationType.Android);\n }\n\n public static Vector2 getProjectedCoordinates(int screenX, int screenY, Viewport viewport) {\n Vector2 touchPos = new Vector2(screenX, screenY);\n //touchPos = getCamera().unproject(touchPos);\n float xRatio = (float) Config.APP_WIDTH / (float) viewport.getViewportWidth();\n float yRatio = (float) Config.APP_HEIGHT / (float) viewport.getViewportHeight();\n\n touchPos.x -= (Gdx.graphics.getWidth() - viewport.getViewportWidth()) / 2;\n touchPos.x *= xRatio;\n\n touchPos.y = Gdx.graphics.getHeight() - touchPos.y;\n touchPos.y -= (Gdx.graphics.getHeight() - viewport.getViewportHeight()) / 2;\n touchPos.y *= yRatio;\n\n return touchPos;\n }\n}", "public class Debug {\n static final private String DebugTag = \"[Wisper Debug]\";\n\n static public void PrintDebugInformation() {\n long javaHeap = Gdx.app.getJavaHeap();\n long nativeHeap = Gdx.app.getNativeHeap();\n Application.ApplicationType appType = Gdx.app.getType();\n\n Gdx.app.log(DebugTag, \"------ Debug informations ------\");\n Gdx.app.log(DebugTag, \"Java Heap : \" + (javaHeap / 1000000f));\n Gdx.app.log(DebugTag, \"Native Heap : \" + (nativeHeap / 1000000f));\n Gdx.app.log(DebugTag, \"Application Type : \" + appType.toString());\n Gdx.app.log(DebugTag, \"--------------------------------\");\n }\n\n static public void Log(String logLine) {\n Gdx.app.log(DebugTag, logLine);\n }\n}", "public class ExtendedStage<T extends FadingScreen> extends Stage {\n private T screen;\n private boolean fading = false;\n private FadingScreen nextScreen;\n\n public ExtendedStage(T screen, FadingScreen nextScreen) {\n super();\n\n this.nextScreen = nextScreen;\n this.screen = screen;\n }\n\n @Override\n public boolean keyDown(int keyCode) {\n if(keyCode == Input.Keys.ESCAPE || keyCode == Input.Keys.BACK){\n if (!fading) {\n screen.fadeTo(nextScreen);\n fading = true;\n }\n }\n\n return super.keyDown(keyCode);\n }\n}" ]
import aurelienribon.tweenengine.BaseTween; import aurelienribon.tweenengine.Tween; import aurelienribon.tweenengine.TweenCallback; import aurelienribon.tweenengine.TweenManager; import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.List; import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.badlogic.gdx.utils.Scaling; import com.badlogic.gdx.utils.viewport.ScalingViewport; import fr.wisper.Game.WisperGame; import fr.wisper.assets.WisperChooseAssets; import fr.wisper.entities.AnimatedWisper; import fr.wisper.animations.tween.TableAccessor; import fr.wisper.entities.Wisper; import fr.wisper.screens.loading.LoadingScreen; import fr.wisper.utils.Config; import fr.wisper.utils.Debug; import fr.wisper.utils.ExtendedStage;
package fr.wisper.screens.gamescreen; public class WisperChooseMenu implements FadingScreen { // Stage private ExtendedStage<WisperChooseMenu> stage; private Table table; private Skin skin; List<String> list; // Wisper private final String CHOSEN_WISPER = "chosen-wisper"; private SpriteBatch batch;
private AnimatedWisper wisper;
2
exoplatform/task
services/src/test/java/org/exoplatform/task/rest/TestProjectRestService.java
[ "public class TestUtils {\n\n private static Connection conn;\n private static Liquibase liquibase;\n\n public static long EXISTING_TASK_ID = 1;\n public static long UNEXISTING_TASK_ID = 2;\n\n public static long EXISTING_PROJECT_ID = 1;\n public static long UNEXISTING_PROJECT_ID = 2;\n\n public static long EXISTING_STATUS_ID = 1;\n public static long UNEXISTING_STATUS_ID = 2;\n\n public static long EXISTING_COMMENT_ID = 1;\n public static long UNEXISTING_COMMENT_ID = 2;\n\n public static long EXISTING_LABEL_ID = 1;\n public static long UNEXISTING_LABEL_ID = 2;\n\n public static void initH2DB() throws SQLException,\n ClassNotFoundException, LiquibaseException {\n\n Class.forName(\"org.h2.Driver\");\n conn = DriverManager.getConnection(\"jdbc:h2:target/h2-db\", \"sa\", \"\");\n\n initDB();\n }\n\n public static void initHSQLDB() throws LiquibaseException, SQLException,\n ClassNotFoundException {\n\n Class.forName(\"org.hsqldb.jdbcDriver\");\n conn = DriverManager.getConnection(\"jdbc:hsqldb:file:target/hsql-db\", \"sa\", \"\");\n\n initDB();\n }\n\n private static void initDB() throws LiquibaseException {\n Database database = DatabaseFactory.getInstance()\n .findCorrectDatabaseImplementation(new JdbcConnection(conn));\n\n liquibase = new Liquibase(\"db/changelog/task.db.changelog-1.0.0.xml\", new ClassLoaderResourceAccessor(), database);\n liquibase.update((String)null);\n liquibase = new Liquibase(\"db/changelog/task.db.changelog-1.1.0.xml\", new ClassLoaderResourceAccessor(), database);\n liquibase.update((String)null);\n liquibase = new Liquibase(\"db/changelog/task.db.changelog-1.3.0.xml\", new ClassLoaderResourceAccessor(), database);\n liquibase.update((String)null);\n liquibase = new Liquibase(\"db/changelog/task.db.changelog-2.1.0.xml\", new ClassLoaderResourceAccessor(), database);\n liquibase.update((String)null);\n liquibase = new Liquibase(\"db/changelog/task.db.changelog-3.0.0.xml\", new ClassLoaderResourceAccessor(), database);\n liquibase.update((String)null);\n liquibase = new Liquibase(\"db/changelog/task.db.changelog-3.1.0.xml\", new ClassLoaderResourceAccessor(), database);\n liquibase.update((String)null);\n liquibase = new Liquibase(\"db/changelog/task.db.changelog-3.2.0.xml\", new ClassLoaderResourceAccessor(), database);\n liquibase.update((String)null);\n }\n\n public static void closeDB() throws LiquibaseException, SQLException {\n liquibase.rollback(1000, null);\n conn.close();\n }\n\n public static Task getDefaultTask() {\n return getDefaultTaskWithId(EXISTING_TASK_ID);\n }\n\n public static TaskDto getDefaultTaskDto() {\n return getDefaultTaskDtoWithId(EXISTING_TASK_ID);\n }\n\n public static Task getDefaultTaskWithId(long id) {\n Task task = new Task();\n task.setId(id);\n task.setTitle(\"Default task\");\n task.setAssignee(\"root\");\n task.setCreatedBy(\"root\");\n task.setCreatedTime(new Date());\n return task;\n }\n public static TaskDto getDefaultTaskDtoWithId(long id) {\n TaskDto task = new TaskDto();\n task.setId(id);\n task.setTitle(\"Default task\");\n task.setAssignee(\"root\");\n task.setCreatedBy(\"root\");\n task.setCreatedTime(new Date());\n return task;\n }\n\n public static Comment getDefaultComment() {\n Comment comment = new Comment();\n comment.setId(EXISTING_COMMENT_ID);\n comment.setComment(\"Bla bla\");\n comment.setAuthor(\"Tib\");\n comment.setCreatedTime(new Date());\n comment.setTask(getDefaultTask());\n return comment;\n }\n\n public static Comment getDefaultCommentWithMention() {\n Comment comment = new Comment();\n comment.setId(EXISTING_COMMENT_ID);\n comment.setComment(\"Bla bla @testa\");\n comment.setAuthor(\"Tib\");\n comment.setCreatedTime(new Date());\n comment.setTask(getDefaultTask());\n return comment;\n }\n\n public static CommentDto getDefaultCommentDto() {\n CommentDto comment = new CommentDto();\n comment.setId(EXISTING_COMMENT_ID);\n comment.setComment(\"Bla bla\");\n comment.setAuthor(\"Tib\");\n comment.setCreatedTime(new Date());\n comment.setTask(getDefaultTaskDto());\n return comment;\n }\n\n public static Status getDefaultStatus() {\n Status status = new Status();\n status.setId(EXISTING_STATUS_ID);\n status.setName(\"TODO\");\n status.setRank(1);\n return status;\n }\n public static StatusDto getDefaultStatusDto() {\n StatusDto status = new StatusDto();\n status.setId(EXISTING_STATUS_ID);\n status.setName(\"TODO\");\n status.setRank(1);\n return status;\n }\n\n public static UserSettingDto getDefaultUserSettingDto(){\n UserSettingDto userSettingDto = new UserSettingDto();\n userSettingDto.setUsername(\"user\");\n userSettingDto.setShowHiddenProject(true);\n userSettingDto.setShowHiddenLabel(true);\n return userSettingDto;\n }\n\n public static LabelDto getDefaultLabel() {\n LabelDto labelDto = new LabelDto();\n labelDto.setId(EXISTING_LABEL_ID);\n labelDto.setName(\"TODO\");\n labelDto.setUsername(\"label\");\n return labelDto;\n }\n\n public static Project getDefaultProject() {\n Project project = new Project();\n project.setId(EXISTING_PROJECT_ID);\n project.setName(\"Default project\");\n project.setDescription(\"The default project\");\n project.setDueDate(new Date());\n Set<String> managers = new HashSet<String>();\n managers.add(\"Tib\");\n project.setManager(managers);\n return project;\n }\n public static ProjectDto getDefaultProjectDto() {\n ProjectDto project = new ProjectDto();\n project.setId(EXISTING_PROJECT_ID);\n project.setName(\"Default project\");\n project.setDescription(\"The default project\");\n project.setDueDate(new Date());\n Set<String> managers = new HashSet<String>();\n managers.add(\"Tib\");\n project.setManager(managers);\n return project;\n }\n\n public static User getUser() {\n User user = new User();\n user.setUsername(\"root\");\n user.setDisplayName(\"root\");\n user.setFirstName(\"root\");\n user.setLastName(\"root\");\n user.setEmail(\"root@gmail.com\");\n\n return user;\n }\n\n public static User getUserA() {\n User user = new User();\n user.setUsername(\"userA\");\n user.setDisplayName(\"userA\");\n user.setFirstName(\"userA\");\n user.setLastName(\"userA\");\n user.setEmail(\"userA@gmail.com\");\n\n return user;\n }\n\n public static org.exoplatform.social.core.identity.model.Identity getUserAIdentity() {\n org.exoplatform.social.core.identity.model.Identity userIdentity = new org.exoplatform.social.core.identity.model.Identity(OrganizationIdentityProvider.NAME, \"userA\");\n\n userIdentity.setEnable(true);\n userIdentity.setDeleted(false);\n userIdentity.setRemoteId(\"userA\");\n\n Profile userProfile = new Profile(userIdentity);\n userProfile.setProperty(Profile.FULL_NAME, \"userA\");\n userProfile.setProperty(Profile.AVATAR, \"/userA.png\");\n userIdentity.setProfile(userProfile);\n\n return userIdentity;\n }\n\n}", "@Data\n@NoArgsConstructor\npublic class ProjectDto implements Serializable {\n private static final Log LOG = ExoLogger.getLogger(ProjectDto.class);\n\n\n private long id;\n\n private String name;\n\n private String description;\n\n private String color;\n\n private Set<StatusDto> status ;\n\n private Set<String> manager;\n\n private Set<String> participator;\n\n private Date dueDate;\n\n private Long lastModifiedDate;;\n\n private ProjectDto parent;\n\n private List<ProjectDto> children;\n\n private Set<UserSetting> hiddenOn;\n\n private String spaceName;\n\n public ProjectDto(String name, String description, HashSet<StatusDto> statuses, Set<String> managers, Set<String> participators) {\n this.name=name;\n this.description=description;\n this.status=statuses;\n this.manager=managers;\n this.participator=participators;\n }\n\n\n public ProjectDto clone(boolean cloneTask) {\n ProjectDto project = new ProjectDto();\n project.setId(getId());\n project.setName(this.getName());\n project.setDescription(this.getDescription());\n project.setColor(this.getColor());\n project.setDueDate(this.getDueDate());\n if (this.getParent() != null) {\n project.setParent(getParent().clone(false));\n }\n project.status = new HashSet<StatusDto>();\n project.children = new LinkedList<ProjectDto>();\n\n return project;\n }\n\n public boolean canView(Identity user) {\n Set<String> permissions = new HashSet<String>();\n Set<String> Participants = getParticipator();\n Set<String> managers = getManager();\n if(Participants!=null){\n permissions.addAll(Participants);\n }\n if(managers!=null){\n permissions.addAll(managers);\n }\n return hasPermission(user, permissions);\n }\n\n public boolean canEdit(Identity user) {\n return hasPermission(user, getManager());\n }\n\n private boolean hasPermission(Identity user, Set<String> permissions) {\n if (permissions.contains(user.getUserId())) {\n return true;\n } else {\n Set<MembershipEntry> memberships = new HashSet<MembershipEntry>();\n for (String per : permissions) {\n MembershipEntry entry = MembershipEntry.parse(per);\n if (entry != null) {\n memberships.add(entry);\n }\n }\n\n for (MembershipEntry entry : user.getMemberships()) {\n if (memberships.contains(entry)) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (!(obj instanceof ProjectDto))\n return false;\n ProjectDto other = (ProjectDto) obj;\n if (getId() != other.getId())\n return false;\n return true;\n }\n\n}", "@Data\n@NoArgsConstructor\npublic class StatusDto implements Serializable {\n private Long id;\n\n private String name;\n\n private Integer rank;\n\n private List<Task> tasks;\n\n private ProjectDto project;\n\n public StatusDto(StatusDto status) {\n this.id=status.getId();\n this.name=status.getName();\n this.rank=status.getRank();\n this.project=status.getProject();\n }\n\n public StatusDto(long id, String name) {\n this.id = id;\n this.name = name;\n }\n\n public StatusDto(long id, String name, Integer rank, ProjectDto project) {\n this.id = id;\n this.name = name;\n this.rank = rank;\n this.project = project;\n }\n\n public StatusDto clone() {\n StatusDto status = new StatusDto(getId(), getName(), getRank(), getProject().clone(false));\n\n return status;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n StatusDto status = (StatusDto) o;\n\n if (id != status.getId()) return false;\n if (name != null ? !name.equals(status.getName()) : status.getName() != null) return false;\n if (project != null ? !project.equals(status.getProject()) : status.getProject() != null) return false;\n if (rank != null ? !rank.equals(status.getRank()) : status.getRank() != null) return false;\n\n return true;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(id, name, rank, project);\n }\n\n}", "@Data\npublic class TaskDto implements Serializable {\n private long id;\n private String title;\n private String description;\n private Priority priority;\n private String context;\n private String assignee;\n private StatusDto status;\n private int rank;\n private boolean completed;\n private Set<String> coworker;\n private Set<String> watcher;\n private String createdBy;\n private Date createdTime;\n private Date startDate;\n private Date endDate;\n private Date dueDate;\n private String activityId;\n\n public TaskDto clone() {\n Set<String> coworkerClone = new HashSet<String>();\n Set<String> watcherClone = new HashSet<String>();\n if (getCoworker() != null) {\n coworkerClone = new HashSet<String>(getCoworker());\n }\n if (getWatcher() != null) {\n watcherClone = new HashSet<String>(getWatcher());\n }\n TaskDto newTask = new TaskDto();\n newTask.setTitle(this.getTitle());\n newTask.setDescription(this.getDescription());\n newTask.setPriority(this.getPriority());\n newTask.setContext(this.getContext());\n newTask.setAssignee(this.getAssignee());\n newTask.setCoworker(coworkerClone);\n newTask.setWatcher(watcherClone);\n newTask.setStatus(this.getStatus() != null ? this.getStatus().clone() : null);\n newTask.setRank(this.getRank());\n newTask.setActivityId(this.getActivityId());\n newTask.setCompleted(this.isCompleted());\n newTask.setCreatedBy(this.getCreatedBy());\n newTask.setCreatedTime(this.getCreatedTime());\n newTask.setEndDate(this.getEndDate());\n newTask.setStartDate(this.getStartDate());\n newTask.setDueDate(this.getDueDate());\n newTask.setCreatedTime(getCreatedTime());\n newTask.setActivityId(getActivityId());\n newTask.setCompleted(isCompleted());\n newTask.setRank(getRank());\n newTask.setId(getId());\n\n return newTask;\n }\n\n}", "public interface UserService {\n\n User loadUser(String username);\n\n /**\n * For now, this method is used only for search user in assignee, permission or mention.\n * These function use username, fullName and avatar, so some other infos will be null to avoid recall organizationService\n * @param keyword name of the user\n * @return List of users\n */\n ListAccess<User> findUserByName(String keyword);\n\n UserSetting getUserSetting(String username);\n\n void showHiddenProject(String username, boolean show);\n \n void showHiddenLabel(String username, boolean show);\n\n void hideProject(Identity identity, Long projectId, boolean hide) throws EntityNotFoundException, NotAllowedOperationOnEntityException;\n\n TimeZone getUserTimezone(String username);\n}", "public class User {\n private String username;\n private String email;\n private String firstName;\n private String lastName;\n private String displayName;\n private String avatar;\n private String url;\n private boolean enable;\n private boolean deleted;\n private boolean external;\n\n public User() {\n }\n\n public User(String username, String email, String firstName, String lastName, String displayName, String avatar, String url) {\n this.username = username;\n this.email = email;\n this.firstName = firstName;\n this.lastName = lastName;\n this.displayName = displayName;\n this.avatar = avatar;\n this.url = url;\n }\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getFirstName() {\n return firstName;\n }\n\n public void setFirstName(String firstName) {\n this.firstName = firstName;\n }\n\n public String getLastName() {\n return lastName;\n }\n\n public void setLastName(String lastName) {\n this.lastName = lastName;\n }\n\n public String getDisplayName() {\n return displayName;\n }\n\n public void setDisplayName(String displayName) {\n this.displayName = displayName;\n }\n\n public String getAvatar() {\n return avatar;\n }\n\n public void setAvatar(String avatar) {\n this.avatar = avatar;\n }\n\n public String getUrl() {\n return url;\n }\n\n public void setUrl(String url) {\n this.url = url;\n }\n\n public boolean isDeleted() {\n return deleted;\n }\n\n public void setDeleted(boolean deleted) {\n this.deleted = deleted;\n }\n\n public boolean isEnable() {\n return enable;\n }\n\n public void setEnable(boolean enable) {\n this.enable = enable;\n }\n public boolean isExternal() { return external; }\n\n public void setExternal(boolean external) { this.external = external; }\n}", "public interface ProjectStorage {\n\n /**\n * Return the project with given <code>projectId</code>.\n *\n * @param projectId the project id.\n * @return get the given project.\n * @throws EntityNotFoundException when user is not authorized to get project.\n */\n ProjectDto getProject(Long projectId) throws EntityNotFoundException;\n\n Set<String> getManager(long projectId);\n\n Set<String> getParticipator(long projectId);\n\n /**\n * Create a project with given <code>project</code> model object.\n *\n * @param project the given project.\n * @return create the given project.\n */\n ProjectDto createProject(ProjectDto project);\n\n /**\n * Create a sub-project with given <code>project</code> model object and parent project ID.\n *\n * @param project the project metadata to create.\n * @param parentId parent project ID\n * @return Create a sub-project.\n * @throws EntityNotFoundException the project associated with <code>parentId</code> doesn't exist.\n */\n ProjectDto createProject(ProjectDto project, long parentId) throws EntityNotFoundException;\n\n\n ProjectDto updateProject(ProjectDto project);\n\n void updateProjectNoReturn(ProjectDto project);\n\n /**\n * Remove the project with given <code>projectId</code>,\n * and also its descendants if <code>deleteChild</code> is true.\n *\n * @param projectId the given project id.\n * @param deleteChild delete Child.\n * @throws EntityNotFoundException when user is not authorized to remove project.\n */\n void removeProject(long projectId, boolean deleteChild) throws EntityNotFoundException;\n\n /**\n * Clone a project with given <code>projectId</code>. If <code>cloneTask</code> is true,\n * it will also clone all non-completed tasks from the project.\n *\n * @param projectId The id of a project which it copies from.\n * @param cloneTask If false, it will clone only project metadata.\n * Otherwise, it also clones all non-completed tasks from the project.\n * @return The cloned project.\n * @throws EntityNotFoundException when user is not authorized to clone project.\n */\n ProjectDto cloneProject(long projectId, boolean cloneTask) throws EntityNotFoundException;\n\n /**\n * Return a list of children of a parent project with given <code>parentId</code>.\n *\n * @param parentId The parent id of a project.\n * @param offset term to offset results.\n * @param limit term to limit results.\n * @return The list of children of a parent project.\n * @throws Exception when can't get sub projects.\n */\n List<ProjectDto> getSubProjects(long parentId,int offset ,int limit) throws Exception;\n\n List<ProjectDto> findProjects(ProjectQuery query,int offset ,int limit);\n\n int countProjects(ProjectQuery query);\n\n List<ProjectDto> findProjects(List<String> memberships, String keyword, OrderBy order,int offset ,int limit);\n\n List<ProjectDto> findCollaboratedProjects(String userName, String keyword,int offset ,int limit);\n\n List<ProjectDto> findNotEmptyProjects(List<String> memberships, String keyword,int offset ,int limit);\n\n int countCollaboratedProjects(String userName, String keyword);\n\n int countNotEmptyProjects(List<String> memberships, String keyword);\n\n int countProjects(List<String> memberships, String keyword);\n\n}", "public interface StatusStorage {\n\n /**\n * Return the <code>Status</code> with given <code>statusId</code>.\n *\n * @param statusId the given status id.\n * @return the status of the given statusId.\n */\n StatusDto getStatus(long statusId);\n\n /**\n * Return the default status of the project which is ideally the first step in\n * the project workflow.\n *\n * @param projectId the given project id.\n * @return the default status of the given project.\n */\n StatusDto getDefaultStatus(long projectId);\n\n /**\n * Return the list of statuses from a project with given <code>projectId</code>.\n *\n * @param projectId the given project id.\n * @return the status of the given project.\n */\n List<StatusDto> getStatuses(long projectId);\n\n StatusDto createStatus(ProjectDto project, String status);\n\n StatusDto createStatus(ProjectDto project, String status, int rank) throws NotAllowedOperationOnEntityException;\n\n void removeStatus(long statusId) throws Exception;\n\n StatusDto updateStatus(long statusId, String statusName) throws EntityNotFoundException, NotAllowedOperationOnEntityException;\n\n StatusDto updateStatus(StatusDto statusDto) throws EntityNotFoundException,\n NotAllowedOperationOnEntityException;\n\n\n}" ]
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.*; import java.util.*; import javax.ws.rs.core.Response; import javax.ws.rs.ext.RuntimeDelegate; import org.exoplatform.commons.utils.ListAccess; import org.exoplatform.social.core.identity.provider.OrganizationIdentityProvider; import org.exoplatform.social.core.manager.IdentityManager; import org.exoplatform.social.core.space.SpaceUtils; import org.exoplatform.social.core.space.model.Space; import org.exoplatform.task.dao.OrderBy; import org.exoplatform.task.rest.model.PaginatedTaskList; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.exoplatform.services.rest.impl.RuntimeDelegateImpl; import org.exoplatform.services.security.ConversationState; import org.exoplatform.services.security.Identity; import org.exoplatform.social.core.space.spi.SpaceService; import org.exoplatform.task.TestUtils; import org.exoplatform.task.dto.ProjectDto; import org.exoplatform.task.dto.StatusDto; import org.exoplatform.task.dto.TaskDto; import org.exoplatform.task.service.UserService; import org.exoplatform.task.model.User; import org.exoplatform.task.service.*; import org.exoplatform.task.storage.ProjectStorage; import org.exoplatform.task.storage.StatusStorage;
package org.exoplatform.task.rest; @RunWith(MockitoJUnitRunner.class) public class TestProjectRestService { @Mock TaskService taskService; @Mock ProjectService projectService; @Mock ProjectStorage projectStorage; @Mock StatusService statusService; @Mock StatusStorage statusStorage; @Mock UserService userService; @Mock SpaceService spaceService; @Mock CommentService commentService; @Mock LabelService labelService; @Mock IdentityManager identityManager; @Before public void setup() { RuntimeDelegate.setInstance(new RuntimeDelegateImpl()); } @Test public void testGetTasks() throws Exception { // Given TaskRestService taskRestService = new TaskRestService(taskService, commentService, projectService, statusService, userService, spaceService, labelService); Identity root = new Identity("root"); ConversationState.setCurrent(new ConversationState(root)); TaskDto task1 = new TaskDto(); TaskDto task2 = new TaskDto(); TaskDto task3 = new TaskDto(); TaskDto task4 = new TaskDto(); List<TaskDto> uncompletedTasks = new ArrayList<TaskDto>(); task1.setCompleted(true); uncompletedTasks.add(task2); uncompletedTasks.add(task3); uncompletedTasks.add(task4); List<TaskDto> overdueTasks = new ArrayList<TaskDto>(); overdueTasks.add(task1); overdueTasks.add(task2); List<TaskDto> incomingTasks = new ArrayList<TaskDto>(); incomingTasks.add(task1); incomingTasks.add(task2); when(taskService.getUncompletedTasks("root", 20)).thenReturn(uncompletedTasks); when(taskService.countUncompletedTasks("root")).thenReturn(Long.valueOf(uncompletedTasks.size())); when(taskService.getOverdueTasks("root", 20)).thenReturn(overdueTasks); when(taskService.countOverdueTasks("root")).thenReturn(Long.valueOf(overdueTasks.size())); when(taskService.getIncomingTasks("root", 0, 20)).thenReturn(incomingTasks); when(taskService.countIncomingTasks("root")).thenReturn(incomingTasks.size()); when(taskService.findTasks(eq("root"), eq("searchTerm"), anyInt())).thenReturn(Collections.singletonList(task4)); when(taskService.countTasks(eq("root"), eq("searchTerm"))).thenReturn(1L); // When Response response = taskRestService.getTasks("overdue", null, 0, 20, false, false); Response response1 = taskRestService.getTasks("incoming", null, 0, 20, false, false); Response response2 = taskRestService.getTasks("", null, 0, 20, false, false); Response response3 = taskRestService.getTasks("whatever", "searchTerm", 0, 20, true, false); // Then assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); PaginatedTaskList tasks = (PaginatedTaskList) response.getEntity(); assertNotNull(tasks); assertEquals(2, tasks.getTasksNumber()); assertEquals(Response.Status.OK.getStatusCode(), response1.getStatus()); PaginatedTaskList tasks1 = (PaginatedTaskList) response1.getEntity(); assertNotNull(tasks1); assertEquals(2, tasks1.getTasksNumber()); assertEquals(Response.Status.OK.getStatusCode(), response2.getStatus()); PaginatedTaskList tasks2 = (PaginatedTaskList) response2.getEntity(); assertNotNull(tasks2); assertEquals(3, tasks2.getTasksNumber()); assertEquals(Response.Status.OK.getStatusCode(), response3.getStatus()); // JSONObject tasks3JsonObject = (JSONObject) response3.getEntity(); // assertNotNull(tasks3JsonObject); // assertTrue(tasks3JsonObject.has("size")); // assertTrue(tasks3JsonObject.has("tasks")); // JSONArray tasks3 = (JSONArray) tasks3JsonObject.get("tasks"); // assertNotNull(tasks3); // assertEquals(1, tasks3.length()); // Long tasks3Size = (Long) tasks3JsonObject.get("size"); // assertEquals(1L, tasks3Size.longValue()); } @Test public void testGetProjects() throws Exception { // Given ProjectRestService projectRestService = new ProjectRestService(taskService, commentService, projectService, statusService, userService, spaceService, labelService, identityManager); Identity root = new Identity("root"); ConversationState.setCurrent(new ConversationState(root));
ProjectDto project1 = new ProjectDto();
1
mast-group/codemining-core
src/main/java/codemining/java/codeutils/binding/AbstractJavaNameBindingsExtractor.java
[ "public class JavaASTExtractor {\n\n\tprivate static final class TopMethodRetriever extends ASTVisitor {\n\t\tpublic MethodDeclaration topDcl;\n\n\t\t@Override\n\t\tpublic boolean visit(final MethodDeclaration node) {\n\t\t\ttopDcl = node;\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Remembers if the given Extractor will calculate the bindings.\n\t */\n\tprivate final boolean useBindings;\n\n\tprivate final boolean useJavadocs;\n\n\t/**\n\t * Constructor.\n\t *\n\t * @param useBindings\n\t * calculate bindings on the extracted AST.\n\t */\n\tpublic JavaASTExtractor(final boolean useBindings) {\n\t\tthis.useBindings = useBindings;\n\t\tuseJavadocs = false;\n\t}\n\n\tpublic JavaASTExtractor(final boolean useBindings, final boolean useJavadocs) {\n\t\tthis.useBindings = useBindings;\n\t\tthis.useJavadocs = useJavadocs;\n\t}\n\n\t/**\n\t * Get the AST of a file. It is assumed that a CompilationUnit will be\n\t * returned. A heuristic is used to set the file's path variable.\n\t *\n\t * @param file\n\t * @return the compilation unit of the file\n\t * @throws IOException\n\t */\n\tpublic final CompilationUnit getAST(final File file) throws IOException {\n\t\treturn getAST(file, new HashSet<String>());\n\t}\n\n\t/**\n\t * Get the AST of a file, including additional source paths to resolve\n\t * cross-file bindings. It is assumed that a CompilationUnit will be\n\t * returned. A heuristic is used to set the file's path variable.\n\t * <p>\n\t * Note: this may only yield a big improvement if the above heuristic fails\n\t * and srcPaths contains the correct source path.\n\t *\n\t * @param file\n\t * @param srcPaths\n\t * for binding resolution\n\t * @return the compilation unit of the file\n\t * @throws IOException\n\t */\n\tpublic final CompilationUnit getAST(final File file,\n\t\t\tfinal Set<String> srcPaths) throws IOException {\n\t\tfinal String sourceFile = FileUtils.readFileToString(file);\n\t\tfinal ASTParser parser = ASTParser.newParser(AST.JLS8);\n\t\tparser.setKind(ASTParser.K_COMPILATION_UNIT);\n\n\t\tfinal Map<String, String> options = new Hashtable<String, String>();\n\t\toptions.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM,\n\t\t\t\tJavaCore.VERSION_1_8);\n\t\toptions.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_8);\n\t\tif (useJavadocs) {\n\t\t\toptions.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED);\n\t\t}\n\t\tparser.setCompilerOptions(options);\n\t\tparser.setSource(sourceFile.toCharArray()); // set source\n\t\tparser.setResolveBindings(useBindings);\n\t\tparser.setBindingsRecovery(useBindings);\n\n\t\tparser.setStatementsRecovery(true);\n\n\t\tparser.setUnitName(file.getAbsolutePath());\n\n\t\t// Heuristic to retrieve source file path\n\t\tfinal String srcFilePath;\n\t\tif (file.getAbsolutePath().contains(\"/src\")) {\n\t\t\tsrcFilePath = file.getAbsolutePath().substring(0,\n\t\t\t\t\tfile.getAbsolutePath().indexOf(\"src\", 0) + 3);\n\t\t} else {\n\t\t\tsrcFilePath = \"\";\n\t\t}\n\n\t\t// Add file to source paths if not already present\n\t\tsrcPaths.add(srcFilePath);\n\n\t\tfinal String[] sourcePathEntries = srcPaths.toArray(new String[srcPaths\n\t\t\t\t.size()]);\n\t\tfinal String[] classPathEntries = new String[0];\n\t\tparser.setEnvironment(classPathEntries, sourcePathEntries, null, true);\n\n\t\tfinal CompilationUnit compilationUnit = (CompilationUnit) parser\n\t\t\t\t.createAST(null);\n\t\treturn compilationUnit;\n\t}\n\n\t/**\n\t * Get a compilation unit of the given file content.\n\t *\n\t * @param fileContent\n\t * @param parseType\n\t * @return the compilation unit\n\t */\n\tpublic final ASTNode getAST(final String fileContent,\n\t\t\tfinal ParseType parseType) {\n\t\treturn (ASTNode) getASTNode(fileContent, parseType);\n\t}\n\n\t/**\n\t * Return an ASTNode given the content\n\t *\n\t * @param content\n\t * @return\n\t */\n\tpublic final ASTNode getASTNode(final char[] content,\n\t\t\tfinal ParseType parseType) {\n\t\tfinal ASTParser parser = ASTParser.newParser(AST.JLS8);\n\t\tfinal int astKind;\n\t\tswitch (parseType) {\n\t\tcase CLASS_BODY:\n\t\tcase METHOD:\n\t\t\tastKind = ASTParser.K_CLASS_BODY_DECLARATIONS;\n\t\t\tbreak;\n\t\tcase COMPILATION_UNIT:\n\t\t\tastKind = ASTParser.K_COMPILATION_UNIT;\n\t\t\tbreak;\n\t\tcase EXPRESSION:\n\t\t\tastKind = ASTParser.K_EXPRESSION;\n\t\t\tbreak;\n\t\tcase STATEMENTS:\n\t\t\tastKind = ASTParser.K_STATEMENTS;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tastKind = ASTParser.K_COMPILATION_UNIT;\n\t\t}\n\t\tparser.setKind(astKind);\n\n\t\tfinal Map<String, String> options = new Hashtable<String, String>();\n\t\toptions.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM,\n\t\t\t\tJavaCore.VERSION_1_8);\n\t\toptions.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_8);\n\t\tif (useJavadocs) {\n\t\t\toptions.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED);\n\t\t}\n\t\tparser.setCompilerOptions(options);\n\t\tparser.setSource(content); // set source\n\t\tparser.setResolveBindings(useBindings);\n\t\tparser.setBindingsRecovery(useBindings);\n\n\t\tparser.setStatementsRecovery(true);\n\n\t\tif (parseType != ParseType.METHOD) {\n\t\t\treturn parser.createAST(null);\n\t\t} else {\n\t\t\tfinal ASTNode cu = parser.createAST(null);\n\t\t\treturn getFirstMethodDeclaration(cu);\n\t\t}\n\t}\n\n\t/**\n\t * Get the AST of a string. Path variables cannot be set.\n\t *\n\t * @param file\n\t * @param parseType\n\t * @return an AST node for the given file content\n\t * @throws IOException\n\t */\n\tpublic final ASTNode getASTNode(final String fileContent,\n\t\t\tfinal ParseType parseType) {\n\t\treturn getASTNode(fileContent.toCharArray(), parseType);\n\t}\n\n\t/**\n\t * Get the AST by making the best effort to guess the type of the node.\n\t *\n\t * @throws Exception\n\t */\n\tpublic final ASTNode getBestEffortAstNode(final char[] content)\n\t\t\tthrows Exception {\n\t\tfor (final ParseType parseType : ParseType.values()) {\n\t\t\tfinal ASTNode node = getASTNode(content, parseType);\n\t\t\tif (normalizeCode(node.toString().toCharArray()).equals(\n\t\t\t\t\tnormalizeCode(content))) {\n\t\t\t\treturn node;\n\t\t\t}\n\t\t}\n\t\tthrow new Exception(\n\t\t\t\t\"Code snippet could not be recognized as any of the known types\");\n\t}\n\n\t/**\n\t * Get the AST of a string. Path variables cannot be set.\n\t *\n\t * @param file\n\t * @return an AST node for the given file content\n\t * @throws Exception\n\t * @throws IOException\n\t */\n\tpublic final ASTNode getBestEffortAstNode(final String fileContent)\n\t\t\tthrows Exception {\n\t\treturn getBestEffortAstNode(fileContent.toCharArray());\n\t}\n\n\tprivate final MethodDeclaration getFirstMethodDeclaration(final ASTNode node) {\n\t\tfinal TopMethodRetriever visitor = new TopMethodRetriever();\n\t\tnode.accept(visitor);\n\t\treturn visitor.topDcl;\n\t}\n\n\t/**\n\t * Hacky way to compare snippets.\n\t *\n\t * @param snippet\n\t * @return\n\t */\n\tprivate String normalizeCode(final char[] snippet) {\n\t\tfinal List<String> tokens = (new JavaTokenizer())\n\t\t\t\t.tokenListFromCode(snippet);\n\n\t\tfinal StringBuffer bf = new StringBuffer();\n\t\tfor (final String token : tokens) {\n\t\t\tif (token.equals(ITokenizer.SENTENCE_START)\n\t\t\t\t\t|| token.equals(ITokenizer.SENTENCE_END)) {\n\t\t\t\tcontinue;\n\t\t\t} else {\n\t\t\t\tbf.append(token);\n\t\t\t}\n\t\t\tbf.append(\" \");\n\t\t}\n\t\treturn bf.toString();\n\n\t}\n\n}", "public interface ITokenizer extends Serializable {\n\n\tpublic static class FullToken implements Serializable {\n\n\t\tprivate static final long serialVersionUID = -49456240173307314L;\n\n\t\tpublic static final Function<FullToken, String> TOKEN_NAME_CONVERTER = new Function<FullToken, String>() {\n\t\t\t@Override\n\t\t\tpublic String apply(final FullToken input) {\n\t\t\t\treturn input.token;\n\t\t\t}\n\t\t};\n\n\t\tpublic final String token;\n\n\t\tpublic final String tokenType;\n\n\t\tpublic FullToken(final FullToken other) {\n\t\t\ttoken = other.token;\n\t\t\ttokenType = other.tokenType;\n\t\t}\n\n\t\tpublic FullToken(final String tokName, final String tokType) {\n\t\t\ttoken = tokName;\n\t\t\ttokenType = tokType;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean equals(final Object obj) {\n\t\t\tif (!(obj instanceof FullToken)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tfinal FullToken other = (FullToken) obj;\n\t\t\treturn other.token.equals(token)\n\t\t\t\t\t&& other.tokenType.equals(tokenType);\n\t\t}\n\n\t\t@Override\n\t\tpublic int hashCode() {\n\t\t\treturn Objects.hashCode(token, tokenType);\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn token + \" (\" + tokenType + \")\";\n\t\t}\n\n\t}\n\n\t/**\n\t * A sentence end (constant) token\n\t */\n\tstatic final String SENTENCE_END = \"<SENTENCE_END/>\";\n\n\t/**\n\t * A sentence start (constant) token\n\t */\n\tstatic final String SENTENCE_START = \"<SENTENCE_START>\";\n\n\t/**\n\t * Return a list with the full tokens.\n\t *\n\t * @param code\n\t * @return\n\t */\n\tSortedMap<Integer, FullToken> fullTokenListWithPos(final char[] code);\n\n\t/**\n\t * Return a file filter, filtering the files that can be tokenized.\n\t *\n\t * @return\n\t *\n\t */\n\tAbstractFileFilter getFileFilter();\n\n\t/**\n\t * Return the token type that signifies that a token is an identifier.\n\t *\n\t * @return\n\t */\n\tString getIdentifierType();\n\n\t/**\n\t * Return the token types that are keywords.\n\t * \n\t * @return\n\t */\n\tCollection<String> getKeywordTypes();\n\n\t/**\n\t * Return the types the represent literals.\n\t *\n\t * @return\n\t */\n\tCollection<String> getLiteralTypes();\n\n\t/**\n\t * Return a full token given a string token.\n\t *\n\t * @param token\n\t * @return\n\t */\n\tFullToken getTokenFromString(final String token);\n\n\t/**\n\t * Get the list of tokens from the code.\n\t *\n\t * @param code\n\t * @return\n\t */\n\tList<FullToken> getTokenListFromCode(final char[] code);\n\n\t/**\n\t * Get the list of tokens from the code.\n\t *\n\t * @param code\n\t * @return\n\t */\n\tList<FullToken> getTokenListFromCode(final File codeFile)\n\t\t\tthrows IOException;\n\n\t/**\n\t * Tokenize some code.\n\t *\n\t * @param code\n\t * the code\n\t * @return a list of tokens\n\t */\n\tList<String> tokenListFromCode(final char[] code);\n\n\t/**\n\t * Tokenize code given a file.\n\t *\n\t * @param codeFile\n\t * @return\n\t */\n\tList<String> tokenListFromCode(final File codeFile) throws IOException;\n\n\t/**\n\t * Return a list of tokens along with their positions.\n\t *\n\t * @param code\n\t * @return\n\t */\n\tSortedMap<Integer, String> tokenListWithPos(final char[] code);\n\n\t/**\n\t * Return a list of tokens along with their positions.\n\t *\n\t * @param file\n\t * @return\n\t * @throws IOException\n\t */\n\tSortedMap<Integer, FullToken> tokenListWithPos(File file)\n\t\t\tthrows IOException;\n\n}", "public static class FullToken implements Serializable {\n\n\tprivate static final long serialVersionUID = -49456240173307314L;\n\n\tpublic static final Function<FullToken, String> TOKEN_NAME_CONVERTER = new Function<FullToken, String>() {\n\t\t@Override\n\t\tpublic String apply(final FullToken input) {\n\t\t\treturn input.token;\n\t\t}\n\t};\n\n\tpublic final String token;\n\n\tpublic final String tokenType;\n\n\tpublic FullToken(final FullToken other) {\n\t\ttoken = other.token;\n\t\ttokenType = other.tokenType;\n\t}\n\n\tpublic FullToken(final String tokName, final String tokType) {\n\t\ttoken = tokName;\n\t\ttokenType = tokType;\n\t}\n\n\t@Override\n\tpublic boolean equals(final Object obj) {\n\t\tif (!(obj instanceof FullToken)) {\n\t\t\treturn false;\n\t\t}\n\t\tfinal FullToken other = (FullToken) obj;\n\t\treturn other.token.equals(token)\n\t\t\t\t&& other.tokenType.equals(tokenType);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hashCode(token, tokenType);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn token + \" (\" + tokenType + \")\";\n\t}\n\n}", "public abstract class AbstractNameBindingsExtractor {\n\n\tpublic abstract Set<?> getAvailableFeatures();\n\n\t/**\n\t * Return all the name bindings for file f\n\t *\n\t * @param f\n\t * @return a multimap containing for each name all the relavant name\n\t * bindings in the file.\n\t * @throws IOException\n\t */\n\tpublic Multimap<String, TokenNameBinding> getBindingsForName(final File f)\n\t\t\tthrows IOException {\n\t\treturn getBindingsForName(getNameBindings(f));\n\t}\n\n\tprotected Multimap<String, TokenNameBinding> getBindingsForName(\n\t\t\tfinal List<TokenNameBinding> bindings) {\n\t\tfinal Multimap<String, TokenNameBinding> toks = HashMultimap.create();\n\t\tfor (final TokenNameBinding binding : bindings) {\n\t\t\ttoks.put(binding.getName(), binding);\n\t\t}\n\t\treturn toks;\n\t}\n\n\t/**\n\t * Return the name bindings given the code.\n\t *\n\t * @param code\n\t * @return a multimap containing for each name all the relavant name\n\t * bindings in the code snippet.\n\t */\n\tpublic Multimap<String, TokenNameBinding> getBindingsForName(\n\t\t\tfinal String code) {\n\t\treturn getBindingsForName(getNameBindings(code));\n\t}\n\n\t/**\n\t * Get the name bindings for the given file.\n\t *\n\t * @param f\n\t * @return\n\t * @throws IOException\n\t */\n\tpublic abstract List<TokenNameBinding> getNameBindings(final File f)\n\t\t\tthrows IOException;\n\n\t/**\n\t * Get the name bindings given the code.\n\t *\n\t * @param code\n\t * @return\n\t */\n\tpublic abstract List<TokenNameBinding> getNameBindings(final String code);\n\n\t/**\n\t * Return a ResolvedSourceCode instance for the given code.\n\t *\n\t * @param f\n\t * @return\n\t * @throws IOException\n\t */\n\tpublic abstract ResolvedSourceCode getResolvedSourceCode(final File f)\n\t\t\tthrows IOException;\n\n\t/**\n\t * Return a ResolvedSourceCode instance for the given code.\n\t *\n\t * @param code\n\t * @return\n\t */\n\tpublic abstract ResolvedSourceCode getResolvedSourceCode(final String code);\n\n\tpublic abstract void setActiveFeatures(Set<?> activeFeatures);\n}", "public class ResolvedSourceCode {\n\n\tpublic final String name;\n\n\tpublic final List<String> codeTokens;\n\n\tprivate final ArrayListMultimap<String, TokenNameBinding> variableBindings;\n\n\t/**\n\t * Assumes that the variable bindings use the same (as in ==) token list.\n\t *\n\t * @param name\n\t * @param codeTokens\n\t * @param variableBindings\n\t */\n\tpublic ResolvedSourceCode(final List<String> codeTokens,\n\t\t\tfinal ArrayListMultimap<String, TokenNameBinding> variableBindings) {\n\t\tthis.name = \"UnkownSourceCodeName\";\n\t\tthis.codeTokens = codeTokens;\n\t\tthis.variableBindings = variableBindings;\n\t}\n\n\t/**\n\t * Assumes that the variable bindings use the same (as in ==) token list.\n\t *\n\t * @param name\n\t * @param codeTokens\n\t * @param variableBindings\n\t */\n\tpublic ResolvedSourceCode(final String name, final List<String> codeTokens,\n\t\t\tfinal ArrayListMultimap<String, TokenNameBinding> variableBindings) {\n\t\tthis.name = name;\n\t\tthis.codeTokens = codeTokens;\n\t\tthis.variableBindings = variableBindings;\n\t}\n\n\t/**\n\t * Return all the bindings in source code.\n\t *\n\t * @return\n\t */\n\tpublic Collection<TokenNameBinding> getAllBindings() {\n\t\treturn variableBindings.values();\n\t}\n\n\t/**\n\t * Return the bindings for a single name.\n\t *\n\t * @param name\n\t * @return\n\t */\n\tpublic Collection<TokenNameBinding> getBindingsForName(final String name) {\n\t\treturn variableBindings.get(name);\n\t}\n\n\t/**\n\t * Rename a single bound set of tokens.\n\t *\n\t * @param binding\n\t * @param name\n\t */\n\tpublic void renameVariableTo(final TokenNameBinding binding,\n\t\t\tfinal String name) {\n\t\tcheckArgument(variableBindings.values().contains(binding),\n\t\t\t\t\"Binding is not pointing to this source code\");\n\n\t\tfor (final int position : binding.nameIndexes) {\n\t\t\tcodeTokens.set(position, name);\n\t\t}\n\t}\n\n}", "public class TokenNameBinding implements Serializable {\n\tprivate static final long serialVersionUID = 2020613810485746430L;\n\n\t/**\n\t * The tokens of source code.\n\t */\n\tpublic final List<String> sourceCodeTokens;\n\n\t/**\n\t * The positions in sourceCodeTokens that contain the given name.\n\t */\n\tpublic final Set<Integer> nameIndexes;\n\n\t/**\n\t * Features of the binding\n\t */\n\tpublic final Set<String> features;\n\n\tpublic TokenNameBinding(final Set<Integer> nameIndexes,\n\t\t\tfinal List<String> sourceCodeTokens, final Set<String> features) {\n\t\tcheckArgument(nameIndexes.size() > 0);\n\t\tcheckArgument(sourceCodeTokens.size() > 0);\n\t\tthis.nameIndexes = Collections.unmodifiableSet(nameIndexes);\n\t\tthis.sourceCodeTokens = Collections.unmodifiableList(sourceCodeTokens);\n\t\tthis.features = features;\n\t}\n\n\t@Override\n\tpublic boolean equals(final Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (getClass() != obj.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tfinal TokenNameBinding other = (TokenNameBinding) obj;\n\t\treturn Objects.equal(nameIndexes, other.nameIndexes)\n\t\t\t\t&& Objects.equal(features, other.features)\n\t\t\t\t&& Objects.equal(sourceCodeTokens, other.sourceCodeTokens);\n\t}\n\n\tpublic String getName() {\n\t\treturn sourceCodeTokens.get(nameIndexes.iterator().next());\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hashCode(sourceCodeTokens, nameIndexes, features);\n\t}\n\n\t/**\n\t * Rename this name to the given binding. The source code tokens included in\n\t * this struct, now represent the new structure.\n\t *\n\t * @param name\n\t * @return\n\t */\n\tpublic TokenNameBinding renameTo(final String name) {\n\t\tfinal List<String> renamedCode = Lists.newArrayList(sourceCodeTokens);\n\t\tfor (final int position : nameIndexes) {\n\t\t\trenamedCode.set(position, name);\n\t\t}\n\t\treturn new TokenNameBinding(nameIndexes, renamedCode, features);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn getName() + nameIndexes + \" \" + features;\n\t}\n}" ]
import java.io.File; import java.io.IOException; import java.util.List; import java.util.Set; import java.util.SortedMap; import java.util.function.Predicate; import org.apache.commons.io.FileUtils; import org.eclipse.jdt.core.dom.ASTNode; import codemining.java.codeutils.JavaASTExtractor; import codemining.languagetools.ITokenizer; import codemining.languagetools.ITokenizer.FullToken; import codemining.languagetools.bindings.AbstractNameBindingsExtractor; import codemining.languagetools.bindings.ResolvedSourceCode; import codemining.languagetools.bindings.TokenNameBinding; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets;
/** * */ package codemining.java.codeutils.binding; /** * A name bindings extractor interface for Java. * * @author Miltos Allamanis <m.allamanis@ed.ac.uk> * */ public abstract class AbstractJavaNameBindingsExtractor extends AbstractNameBindingsExtractor { /** * Return the token index for the given position. * * @param sourceCode * @return */ protected static SortedMap<Integer, Integer> getTokenIndexForPostion( final SortedMap<Integer, String> tokenPositions) { final SortedMap<Integer, Integer> positionToIndex = Maps.newTreeMap(); int i = 0; for (final int position : tokenPositions.keySet()) { positionToIndex.put(position, i); i++; } return positionToIndex; } final ITokenizer tokenizer; public AbstractJavaNameBindingsExtractor(final ITokenizer tokenizer) { this.tokenizer = tokenizer; } protected JavaASTExtractor createExtractor() { return new JavaASTExtractor(false); } protected abstract Set<String> getFeatures(final Set<ASTNode> boundNodes); /** * Return a set of sets of SimpleName ASTNode objects that are bound * together * * @param node * @return */ public abstract Set<Set<ASTNode>> getNameBindings(final ASTNode node);
public final List<TokenNameBinding> getNameBindings(final ASTNode node,
5
CreativeMD/IGCM
src/main/java/com/creativemd/igcm/IGCMGuiManager.java
[ "public class ConfigTab extends ConfigGroupElement {\n\t\n\tpublic static final ConfigTab root = new ConfigTab(\"root\", ItemStack.EMPTY);\n\t\n\tpublic static ConfigSegment getSegmentByPath(String path) {\n\t\tif (path.equals(\"root\"))\n\t\t\treturn root;\n\t\tif (path.startsWith(\"root.\"))\n\t\t\treturn root.getChildByPath(path.substring(\"root.\".length()));\n\t\treturn null;\n\t}\n\t\n\tpublic ConfigTab(String title, ItemStack avatar) {\n\t\tsuper(title, avatar);\n\t}\n\t\n\tpublic ConfigSegment getChildByPath(String path) {\n\t\tString[] patterns = path.split(\"\\\\.\");\n\t\tConfigSegment currentElement = this;\n\t\tfor (int i = 0; i < patterns.length; i++) {\n\t\t\tif (currentElement instanceof ConfigGroupElement) {\n\t\t\t\tcurrentElement = ((ConfigGroupElement) currentElement).getChildByKey(patterns[i]);\n\t\t\t\tif (currentElement == null)\n\t\t\t\t\treturn null;\n\t\t\t} else\n\t\t\t\treturn null;\n\t\t}\n\t\treturn currentElement;\n\t}\n\t\n\t@Override\n\tpublic void loadExtra(NBTTagCompound nbt) {\n\t\t\n\t}\n\t\n\t@Override\n\tpublic void saveExtra(NBTTagCompound nbt) {\n\t\t\n\t}\n\t\n\t@Override\n\tpublic void saveFromControls() {\n\t\t\n\t}\n\t\n}", "public class SubContainerAdvancedWorkbench extends SubContainer {\n\t\n\tpublic InventoryBasic crafting = new InventoryBasic(\"crafting\", false, (int) Math.pow(BlockAdvancedWorkbench.gridSize, 2));\n\tpublic InventoryBasic output = new InventoryBasic(\"output\", false, BlockAdvancedWorkbench.outputs);\n\t\n\tpublic SubContainerAdvancedWorkbench(EntityPlayer player) {\n\t\tsuper(player);\n\t}\n\t\n\t@Override\n\tpublic void createControls() {\n\t\tfor (int y = 0; y < BlockAdvancedWorkbench.gridSize; y++) {\n\t\t\tfor (int x = 0; x < BlockAdvancedWorkbench.gridSize; x++) {\n\t\t\t\taddSlotToContainer(new Slot(crafting, y * BlockAdvancedWorkbench.gridSize + x, 8 + x * 18, 5 + y * 18));\n\t\t\t}\n\t\t}\n\t\tfor (int i = 0; i < BlockAdvancedWorkbench.outputs; i++) {\n\t\t\taddSlotToContainer(new SlotOutput(output, i, 132 + (i - i / 2 * 2) * 18, 41 + i / 2 * 18));\n\t\t}\n\t\t\n\t\t//System.out.println(\"Creating!\");\n\t\taddPlayerSlotsToContainer(player, 8, 120);\n\t}\n\t\n\t@Override\n\tpublic void onPacketReceive(NBTTagCompound nbt) {\n\t\tif (nbt.getInteger(\"type\") == 0) {\n\t\t\tAdvancedGridRecipe recipe = null;\n\t\t\tfor (int i = 0; i < BlockAdvancedWorkbench.recipes.size(); i++) {\n\t\t\t\tif (BlockAdvancedWorkbench.recipes.get(i).isValidRecipe(crafting, 6, 6)) {\n\t\t\t\t\trecipe = BlockAdvancedWorkbench.recipes.get(i);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (recipe != null) {\n\t\t\t\t\n\t\t\t\tfor (int i = 0; i < recipe.output.length; i++) {\n\t\t\t\t\tif (recipe.output[i] != null && !recipe.output[i].isEmpty()) {\n\t\t\t\t\t\tItemStack stack = recipe.output[i].copy();\n\t\t\t\t\t\tif (!InventoryUtils.addItemStackToInventory(output, stack))\n\t\t\t\t\t\t\tif (!InventoryUtils.addItemStackToInventory(player.inventory, stack))\n\t\t\t\t\t\t\t\tWorldUtils.dropItem(player, stack);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\trecipe.consumeRecipe(crafting, BlockAdvancedWorkbench.gridSize, BlockAdvancedWorkbench.gridSize);\n\t\t\t}\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void onClosed() {\n\t\tfor (int i = 0; i < crafting.getSizeInventory(); i++) {\n\t\t\tif (crafting.getStackInSlot(i) != null)\n\t\t\t\tWorldUtils.dropItem(player, crafting.getStackInSlot(i));\n\t\t}\n\t\t\n\t\tfor (int i = 0; i < output.getSizeInventory(); i++) {\n\t\t\tif (output.getStackInSlot(i) != null)\n\t\t\t\tWorldUtils.dropItem(player, output.getStackInSlot(i));\n\t\t}\n\t}\n\t\n}", "public class SubGuiAdvancedWorkbench extends SubGui {\n\t\n\tpublic SubGuiAdvancedWorkbench() {\n\t\tsuper(176, 200);\n\t}\n\t\n\tpublic boolean crafting = false;\n\t\n\t@Override\n\tpublic void createControls() {\n\t\tcontrols.add(new GuiButton(\"Craft!\", 130, 85) {\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void onClicked(int x, int y, int button) {\n\t\t\t}\n\t\t});\n\t\tcontrols.add(new GuiProgressBar(\"progress\", 132, 30, 30, 3, 100, 0));\n\t}\n\t\n\tpublic static long lastTick;\n\t\n\t@Override\n\tpublic void onTick() {\n\t\tif (crafting) {\n\t\t\tif (lastTick == 0)\n\t\t\t\tlastTick = System.currentTimeMillis();\n\t\t\tGuiProgressBar bar = (GuiProgressBar) get(\"progress\");\n\t\t\t\n\t\t\tdouble timeLeft = (System.currentTimeMillis() - lastTick);\n\t\t\t\n\t\t\tbar.pos += timeLeft;\n\t\t\tif (bar.pos >= bar.max) {\n\t\t\t\tNBTTagCompound nbt = new NBTTagCompound();\n\t\t\t\tnbt.setInteger(\"type\", 0);\n\t\t\t\tsendPacketToServer(nbt);\n\t\t\t\tbar.pos = bar.max;\n\t\t\t\tcrafting = false;\n\t\t\t\tget(\"Craft!\").enabled = true;\n\t\t\t\t\n\t\t\t\tfor (int i = 0; i < controls.size(); i++) {\n\t\t\t\t\tif (controls.get(i) instanceof GuiSlotControl)\n\t\t\t\t\t\tcontrols.get(i).enabled = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t}\n\t\tlastTick = System.currentTimeMillis();\n\t}\n\t\n\t@CustomEventSubscribe\n\tpublic void onClicked(GuiControlClickEvent event) {\n\t\tif (event.source.is(\"Craft!\")) {\n\t\t\tAdvancedGridRecipe recipe = null;\n\t\t\tfor (int i = 0; i < BlockAdvancedWorkbench.recipes.size(); i++) {\n\t\t\t\tif (BlockAdvancedWorkbench.recipes.get(i).isValidRecipe(((SubContainerAdvancedWorkbench) container).crafting, 6, 6)) {\n\t\t\t\t\trecipe = BlockAdvancedWorkbench.recipes.get(i);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (recipe != null) {\n\t\t\t\tfor (int i = 0; i < controls.size(); i++) {\n\t\t\t\t\tif (controls.get(i) instanceof GuiSlotControl)\n\t\t\t\t\t\tcontrols.get(i).enabled = false;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tGuiProgressBar bar = (GuiProgressBar) get(\"progress\");\n\t\t\t\tbar.pos = 0;\n\t\t\t\tbar.max = recipe.duration;\n\t\t\t\tevent.source.enabled = false;\n\t\t\t\tcrafting = true;\n\t\t\t}\n\t\t}\n\t}\n\t\n}", "public class SubGuiConfigSegement extends SubGui {\n\t\n\tpublic static final int loadPerTick = 20;\n\t\n\tpublic SubGuiConfigSegement(ConfigSegment element) {\n\t\tsuper(250, 250);\n\t\tthis.element = element;\n\t}\n\t\n\tpublic int aimedScrollPos = -1;\n\tpublic int index;\n\tpublic int height;\n\tpublic ConfigSegment element;\n\tpublic ArrayList<ConfigSegment> childs;\n\t\n\tpublic boolean forceRecreation = true;\n\tpublic boolean isCreatingControls = false;\n\t\n\tpublic static int maxWidth = 220;\n\t\n\tpublic String search = \"\";\n\t\n\tpublic void removeSegment(ConfigSegment segment) {\n\t\tif (!isCreatingControls) {\n\t\t\tint indexOf = childs.indexOf(segment);\n\t\t\tif (indexOf != -1) {\n\t\t\t\tchilds.remove(indexOf);\n\t\t\t\t\n\t\t\t\tGuiScrollBox box = (GuiScrollBox) get(\"scrollbox\");\n\t\t\t\tbox.controls.clear();\n\t\t\t\tbox.maxScroll = 0;\n\t\t\t\tbox.scrolled.setStart(0);\n\t\t\t\t\n\t\t\t\tif (get(\"Save\") != null)\n\t\t\t\t\tget(\"Save\").setEnabled(false);\n\t\t\t\t\n\t\t\t\theight = 5;\n\t\t\t\tindex = 0;\n\t\t\t\t\n\t\t\t\tisCreatingControls = true;\n\t\t\t\tforceRecreation = false;\n\t\t\t\tonTick();\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void createSegmentControls(boolean force) {\n\t\tforceRecreation = force;\n\t\tGuiScrollBox box = (GuiScrollBox) get(\"scrollbox\");\n\t\tCollection<ConfigSegment> segments = element.getChilds();\n\t\taimedScrollPos = (int) box.scrolled.aimed();\n\t\tbox.controls.clear();\n\t\tbox.maxScroll = 0;\n\t\tbox.scrolled.setStart(0);\n\t\t\n\t\tif (get(\"Save\") != null)\n\t\t\tget(\"Save\").setEnabled(false);\n\t\t\n\t\tthis.childs = new ArrayList<ConfigSegment>(segments);\n\t\theight = 5;\n\t\tindex = 0;\n\t\t\n\t\tif (element instanceof ConfigBranch)\n\t\t\t((ConfigBranch) element).onGuiCreatesSegments(this, childs);\n\t\t\n\t\tisCreatingControls = true;\n\t\t\n\t\tonTick();\n\t}\n\t\n\t@Override\n\tpublic void onTick() {\n\t\tif (childs != null && (isCreatingControls || index < childs.size())) {\n\t\t\tisCreatingControls = true;\n\t\t\tGuiScrollBox box = (GuiScrollBox) get(\"scrollbox\");\n\t\t\tint count = 0;\n\t\t\tint countLoaded = 0;\n\t\t\tString search = this.search.toLowerCase();\n\t\t\tfor (int i = index; i < childs.size() && countLoaded < loadPerTick; i++) {\n\t\t\t\tif (search.equals(\"\") || childs.get(i).canBeFound(search)) {\n\t\t\t\t\tConfigSegment child = childs.get(i);\n\t\t\t\t\tint x = 0;\n\t\t\t\t\tint y = height;\n\t\t\t\t\t\n\t\t\t\t\tif (forceRecreation || child.getGuiControls() == null) {\n\t\t\t\t\t\tArrayList<GuiControl> guiControls = child.createGuiControls(this, x, y, maxWidth);\n\t\t\t\t\t\tArrayList<ContainerControl> containerControls = child.createContainerControls(container, x, y, maxWidth);\n\t\t\t\t\t\t\n\t\t\t\t\t\tchild.setGuiControls(guiControls);\n\t\t\t\t\t\tchild.setContainerControls(containerControls);\n\t\t\t\t\t\t\n\t\t\t\t\t\tchild.onSegmentLoaded(x, y, maxWidth);\n\t\t\t\t\t\t\n\t\t\t\t\t\tfor (int j = 0; j < guiControls.size(); j++) {\n\t\t\t\t\t\t\tbox.addControl(guiControls.get(j));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (int j = 0; j < containerControls.size(); j++) {\n\t\t\t\t\t\t\tcontainerControls.get(j).parent = container;\n\t\t\t\t\t\t\tGuiControl control = containerControls.get(j).getGuiControl();\n\t\t\t\t\t\t\tbox.addControl(control);\n\t\t\t\t\t\t\tchild.getGuiControls().add(control);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (element instanceof ConfigBranch)\n\t\t\t\t\t\t\t((ConfigBranch) element).onGuiLoadSegment(this, box, childs, child);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfor (int j = 0; j < child.getGuiControls().size(); j++) {\n\t\t\t\t\t\t\tGuiControl control = child.getGuiControls().get(j);\n\t\t\t\t\t\t\tcontrol.posX = control.posX - child.lastX + x;\n\t\t\t\t\t\t\tcontrol.posY = control.posY - child.lastY + y;\n\t\t\t\t\t\t\tbox.addControl(control);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tchild.onSegmentLoaded(x, y, maxWidth);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\theight += child.getHeight() + 5;\n\t\t\t\t\t\n\t\t\t\t\tcountLoaded++;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tcount++;\n\t\t\t}\n\t\t\t\n\t\t\tif (aimedScrollPos != -1) {\n\t\t\t\tbox.scrolled.setStart(Math.min(height, aimedScrollPos));\n\t\t\t\tif (height >= aimedScrollPos)\n\t\t\t\t\taimedScrollPos = -1;\n\t\t\t}\n\t\t\t\n\t\t\tindex += count;\n\t\t\tif (index >= childs.size()) {\n\t\t\t\tif (element instanceof ConfigBranch) {\n\t\t\t\t\tif (has(\"Save\"))\n\t\t\t\t\t\tget(\"Save\").setEnabled(true);\n\t\t\t\t\t((ConfigBranch) element).onGuiLoadedAllSegments(this, box, childs);\n\t\t\t\t\tisCreatingControls = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n\t@Override\n\tpublic boolean closeGuiUsingEscape() {\n\t\tif (element instanceof ConfigBranch) {\n\t\t\tif (!Minecraft.getMinecraft().isSingleplayer())\n\t\t\t\tMinecraft.getMinecraft().addScheduledTask(new Runnable() {\n\t\t\t\t\t\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void run() {\n\t\t\t\t\t\tPacketHandler.sendPacketToServer(new RequestInformationPacket((ConfigBranch) element));\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t}\n\t\treturn true;\n\t}\n\t\n\t@Override\n\tpublic void createControls() {\n\t\tGuiScrollBox box = new GuiScrollBox(\"scrollbox\", 0, 0, 244, 220);\n\t\tcontrols.add(box);\n\t\tcontrols.add(new GuiButton(\"Cancel\", 0, 228, 50) {\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void onClicked(int x, int y, int button) {\n\t\t\t\tcloseGuiUsingEscape();\n\t\t\t\tif (element.parent != null)\n\t\t\t\t\tIGCMGuiManager.openConfigGui(getPlayer(), element.parent.getPath());\n\t\t\t\telse\n\t\t\t\t\tcloseGui();\n\t\t\t}\n\t\t});\n\t\tif (element instanceof ConfigBranch) {\n\t\t\tcontrols.add((GuiControl) new GuiButton(\"Save\", 194, 228, 50) {\n\t\t\t\t\n\t\t\t\t@Override\n\t\t\t\tpublic void onClicked(int x, int y, int button) {\n\t\t\t\t\tSubGuiConfigSegement parent = (SubGuiConfigSegement) getParent();\n\t\t\t\t\tfor (int i = 0; i < parent.childs.size(); i++) {\n\t\t\t\t\t\tparent.childs.get(i).saveFromControls();\n\t\t\t\t\t}\n\t\t\t\t\tif (element instanceof ConfigBranch) {\n\t\t\t\t\t\t((ConfigBranch) element).onGuiSavesSegments((SubGuiConfigSegement) getParent(), parent.childs);\n\t\t\t\t\t\tIGCM.sendUpdatePacket((ConfigBranch) element);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}.setEnabled(false));\n\t\t}\n\t\tcontrols.add(new GuiTextfield(\"search\", \"\", 60, 228, 124, 14));\n\t\tif (element == ConfigTab.root) {\n\t\t\tcontrols.add(new GuiButton(\"Profiles\", 194, 228, 50) {\n\t\t\t\t@Override\n\t\t\t\tpublic void onClicked(int x, int y, int button) {\n\t\t\t\t\tIGCMGuiManager.openProfileGui(container.player);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\tcreateSegmentControls(true);\n\t}\n\t\n\tpublic GuiSlotControl openedSlot;\n\t\n\t@CustomEventSubscribe\n\tpublic void onButtonClicked(GuiControlClickEvent event) {\n\t\tif (event.source instanceof GuiSlotControl) {\n\t\t\tif (((GuiSlotControl) event.source).slot instanceof InfoSlotControl) {\n\t\t\t\topenedSlot = (GuiSlotControl) event.source;\n\t\t\t\tNBTTagCompound nbt = new NBTTagCompound();\n\t\t\t\tnbt.setBoolean(\"ItemDialog\", true);\n\t\t\t\tnbt.setBoolean(\"fullEdit\", true);\n\t\t\t\topenNewLayer(nbt);\n\t\t\t} else if (((GuiSlotControl) event.source).slot instanceof SlotControlNoSync) {\n\t\t\t\topenedSlot = (GuiSlotControl) event.source;\n\t\t\t\tNBTTagCompound nbt = new NBTTagCompound();\n\t\t\t\tnbt.setBoolean(\"ItemDialog\", true);\n\t\t\t\tnbt.setBoolean(\"fullEdit\", false);\n\t\t\t\topenNewLayer(nbt);\n\t\t\t}\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void onLayerClosed(SubGui gui, NBTTagCompound nbt) {\n\t\tif (gui instanceof SubGuiFullItemDialog && !nbt.getBoolean(\"canceled\") && openedSlot != null) {\n\t\t\t((InfoSlotControl) openedSlot.slot).putInfo(((SubGuiFullItemDialog) gui).info);\n\t\t}\n\t\tif (gui instanceof SubGuiItemDialog && !nbt.getBoolean(\"canceled\") && openedSlot != null) {\n\t\t\topenedSlot.slot.slot.putStack(((SubGuiItemDialog) gui).stack);\n\t\t}\n\t\topenedSlot = null;\n\t}\n\t\n\t@Override\n\tpublic SubGui createLayerFromPacket(World world, EntityPlayer player, NBTTagCompound nbt) {\n\t\tSubGui gui = super.createLayerFromPacket(world, player, nbt);\n\t\tif (!(element instanceof ConfigBranch))\n\t\t\treturn null;\n\t\tif (gui == null && nbt.getBoolean(\"ItemDialog\")) {\n\t\t\tif (nbt.getBoolean(\"fullEdit\")) {\n\t\t\t\tSubGuiFullItemDialog dialog = new SubGuiFullItemDialog(((ConfigBranch) element).doesInputSupportStackSize());\n\t\t\t\tdialog.info = ((InfoSlotControl) openedSlot.slot).info;\n\t\t\t\treturn dialog;\n\t\t\t} else {\n\t\t\t\tSubGuiItemDialog dialog = new SubGuiItemDialog();\n\t\t\t\tdialog.stack = openedSlot.slot.slot.getStack();\n\t\t\t\tif (dialog.stack != null)\n\t\t\t\t\tdialog.stack = dialog.stack.copy();\n\t\t\t\treturn dialog;\n\t\t\t}\n\t\t}\n\t\treturn gui;\n\t}\n\t\n\t@CustomEventSubscribe\n\tpublic void onTextfieldChanged(GuiControlChangedEvent event) {\n\t\tif (event.source instanceof GuiTextfield && event.source.is(\"search\")) {\n\t\t\tsearch = ((GuiTextfield) event.source).text.toLowerCase();\n\t\t\t\n\t\t\t//Temporarily\n\t\t\tcreateSegmentControls(false);\n\t\t}\n\t}\n\t\n}", "public class SubGuiProfile extends SubGui {\n\t\n\tpublic List<String> profiles;\n\tpublic String current;\n\t\n\tpublic SubGuiProfile() {\n\t\tsuper(250, 250);\n\t}\n\t\n\t@Override\n\tpublic void receiveContainerPacket(NBTTagCompound nbt) {\n\t\tsuper.receiveContainerPacket(nbt);\n\t\tNBTTagList list = nbt.getTagList(\"profiles\", 8);\n\t\tprofiles = new ArrayList<>();\n\t\tfor (int i = 0; i < list.tagCount(); i++) {\n\t\t\tprofiles.add(list.getStringTagAt(i));\n\t\t}\n\t\tthis.current = nbt.getString(\"profile\");\n\t\t\n\t\tcontrols.clear();\n\t\t\n\t\tGuiComboBox box = new GuiComboBox(\"profiles\", 5, 5, 100, profiles);\n\t\tbox.caption = current;\n\t\tcontrols.add(box);\n\t\tcontrols.add(new GuiButton(\"Remove\", 120, 5, 40) {\n\t\t\t@Override\n\t\t\tpublic void onClicked(int x, int y, int button) {\n\t\t\t\tGuiComboBox combobox = (GuiComboBox) get(\"profiles\");\n\t\t\t\tif (combobox.lines.size() > 1) {\n\t\t\t\t\t\n\t\t\t\t\tcombobox.lines.remove(combobox.caption);\n\t\t\t\t\tcombobox.caption = combobox.lines.get(0);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tcontrols.add(new GuiTextfield(\"Name\", \"\", 5, 40, 100, 16));\n\t\tcontrols.add(new GuiButton(\"Add\", 120, 40, 40) {\n\t\t\t@Override\n\t\t\tpublic void onClicked(int x, int y, int button) {\n\t\t\t\tGuiTextfield field = (GuiTextfield) get(\"name\");\n\t\t\t\tif (!field.text.equals(\"\")) {\n\t\t\t\t\tGuiComboBox combobox = (GuiComboBox) get(\"profiles\");\n\t\t\t\t\tif (!combobox.lines.contains(field.text))\n\t\t\t\t\t\tcombobox.lines.add(field.text);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tcontrols.add(new GuiButton(\"Cancel\", 5, 228, 40) {\n\t\t\t@Override\n\t\t\tpublic void onClicked(int x, int y, int button) {\n\t\t\t\tIGCMGuiManager.openConfigGui(getPlayer());\n\t\t\t}\n\t\t});\n\t\tcontrols.add(new GuiButton(\"Save\", 200, 228, 40) {\n\t\t\t@Override\n\t\t\tpublic void onClicked(int x, int y, int button) {\n\t\t\t\tGuiComboBox combobox = (GuiComboBox) get(\"profiles\");\n\t\t\t\tNBTTagCompound nbt = new NBTTagCompound();\n\t\t\t\tnbt.setString(\"profile\", combobox.caption);\n\t\t\t\tNBTTagList list = new NBTTagList();\n\t\t\t\tfor (int i = 0; i < combobox.lines.size(); i++) {\n\t\t\t\t\tlist.appendTag(new NBTTagString(combobox.lines.get(i)));\n\t\t\t\t}\n\t\t\t\tnbt.setTag(\"profiles\", list);\n\t\t\t\tsendPacketToServer(nbt);\n\t\t\t}\n\t\t});\n\t\t\n\t\trefreshControls();\n\t}\n\t\n\t@Override\n\tpublic void createControls() {\n\t\tcontrols.add(new GuiLabel(\"Loading ...\", 0, 0));\n\t}\n\t\n}", "public class SubContainerConfigSegment extends SubContainer {\n\t\n\tpublic ConfigSegment element;\n\t\n\tpublic SubContainerConfigSegment(EntityPlayer player, ConfigSegment element) {\n\t\tsuper(player);\n\t\tthis.element = element;\n\t}\n\t\n\t@Override\n\tpublic SubContainer createLayerFromPacket(World world, EntityPlayer player, NBTTagCompound nbt) {\n\t\tif (nbt.getBoolean(\"ItemDialog\"))\n\t\t\treturn new SubContainerEmpty(player);\n\t\treturn super.createLayerFromPacket(world, player, nbt);\n\t}\n\t\n\t@Override\n\tpublic void createControls() {\n\t\t\n\t}\n\t\n\t@Override\n\tpublic void onPacketReceive(NBTTagCompound nbt) {\n\t\t\n\t}\n\t\n}", "public class SubContainerProfile extends SubContainer {\n\t\n\tpublic SubContainerProfile(EntityPlayer player) {\n\t\tsuper(player);\n\t}\n\t\n\t@Override\n\tpublic void createControls() {\n\t\tif (!player.world.isRemote) {\n\t\t\tNBTTagCompound nbt = new NBTTagCompound();\n\t\t\tnbt.setString(\"profile\", IGCMConfig.profileName);\n\t\t\tNBTTagList list = new NBTTagList();\n\t\t\tfor (int i = 0; i < IGCMConfig.profiles.size(); i++) {\n\t\t\t\tlist.appendTag(new NBTTagString(IGCMConfig.profiles.get(i)));\n\t\t\t}\n\t\t\tnbt.setTag(\"profiles\", list);\n\t\t\tsendNBTToGui(nbt);\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void onPacketReceive(NBTTagCompound nbt) {\n\t\tIGCMConfig.profileName = nbt.getString(\"profile\");\n\t\tNBTTagList list = nbt.getTagList(\"profiles\", 8);\n\t\tIGCMConfig.profiles = new ArrayList<>();\n\t\tfor (int i = 0; i < list.tagCount(); i++) {\n\t\t\tIGCMConfig.profiles.add(list.getStringTagAt(i));\n\t\t}\n\t\tIGCMConfig.saveProfiles();\n\t\tIGCMConfig.loadConfig();\n\t\tIGCM.sendAllUpdatePackets();\n\t\tIGCMGuiManager.openConfigGui(getPlayer());\n\t\tIGCMConfig.saveConfig();\n\t}\n\t\n}" ]
import com.creativemd.creativecore.common.gui.container.SubContainer; import com.creativemd.creativecore.common.gui.container.SubGui; import com.creativemd.creativecore.common.gui.opener.CustomGuiHandler; import com.creativemd.creativecore.common.gui.opener.GuiHandler; import com.creativemd.igcm.api.ConfigTab; import com.creativemd.igcm.block.SubContainerAdvancedWorkbench; import com.creativemd.igcm.block.SubGuiAdvancedWorkbench; import com.creativemd.igcm.client.gui.SubGuiConfigSegement; import com.creativemd.igcm.client.gui.SubGuiProfile; import com.creativemd.igcm.container.SubContainerConfigSegment; import com.creativemd.igcm.container.SubContainerProfile; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly;
package com.creativemd.igcm; public class IGCMGuiManager extends CustomGuiHandler { public static void openConfigGui(EntityPlayer player) { openConfigGui(player, "root"); } public static void openConfigGui(EntityPlayer player, String path) { NBTTagCompound nbt = new NBTTagCompound(); nbt.setInteger("gui", 0); nbt.setString("path", path); GuiHandler.openGui(IGCM.guiID, nbt, player); } public static void openProfileGui(EntityPlayer player) { NBTTagCompound nbt = new NBTTagCompound(); nbt.setInteger("gui", 1); nbt.setInteger("index", 0); GuiHandler.openGui(IGCM.guiID, nbt, player); } @Override public SubContainer getContainer(EntityPlayer player, NBTTagCompound nbt) { int gui = nbt.getInteger("gui"); String name = nbt.getString("path"); switch (gui) { case 0: return new SubContainerConfigSegment(player, ConfigTab.getSegmentByPath(name)); case 1: return new SubContainerProfile(player); case 2: return new SubContainerAdvancedWorkbench(player); } return null; } @Override @SideOnly(Side.CLIENT) public SubGui getGui(EntityPlayer player, NBTTagCompound nbt) { int gui = nbt.getInteger("gui"); String name = nbt.getString("path"); switch (gui) { case 0:
return new SubGuiConfigSegement(ConfigTab.getSegmentByPath(name));
3
susom/database
src/test/java/com/github/susom/database/example/VertxServer.java
[ "public interface Config extends Function<String, String>, Supplier<Config> {\n /**\n * Convenience method for fluent syntax.\n *\n * @return a builder for specifying from where configuration should be loaded\n */\n static @Nonnull ConfigFrom from() {\n return new ConfigFromImpl();\n }\n\n // TODO add: String originalKey(String key) to find out the key before prefixing or other manipulation\n\n /**\n * @return a trimmed, non-empty string, or null\n */\n @Nullable String getString(@Nonnull String key);\n\n /**\n * @return a trimmed, non-empty string\n * @throws ConfigMissingException if no value could be read for the specified key\n */\n @Nonnull String getStringOrThrow(@Nonnull String key);\n\n @Nonnull String getString(String key, @Nonnull String defaultValue);\n\n /**\n * Same as {@link #getString(String)}. Useful for passing configs around\n * without static dependencies.\n */\n @Override\n default String apply(String key) {\n return getString(key);\n }\n\n @Override\n default Config get() { return this; }\n\n @Nullable Integer getInteger(@Nonnull String key);\n\n int getInteger(@Nonnull String key, int defaultValue);\n\n /**\n * @throws ConfigMissingException if no value could be read for the specified key\n */\n int getIntegerOrThrow(@Nonnull String key);\n\n @Nullable Long getLong(@Nonnull String key);\n\n long getLong(@Nonnull String key, long defaultValue);\n\n /**\n * @throws ConfigMissingException if no value could be read for the specified key\n */\n long getLongOrThrow(@Nonnull String key);\n\n @Nullable Float getFloat(@Nonnull String key);\n\n float getFloat(@Nonnull String key, float defaultValue);\n\n /**\n * @throws ConfigMissingException if no value could be read for the specified key\n */\n float getFloatOrThrow(@Nonnull String key);\n\n @Nullable Double getDouble(@Nonnull String key);\n\n double getDouble(@Nonnull String key, double defaultValue);\n\n /**\n * @throws ConfigMissingException if no value could be read for the specified key\n */\n double getDoubleOrThrow(@Nonnull String key);\n\n @Nullable\n BigDecimal getBigDecimal(@Nonnull String key);\n\n @Nonnull BigDecimal getBigDecimal(String key, @Nonnull BigDecimal defaultValue);\n\n /**\n * @throws ConfigMissingException if no value could be read for the specified key\n */\n @Nonnull BigDecimal getBigDecimalOrThrow(String key);\n\n /**\n * Read a boolean value from the configuration. The value is not case-sensitivie,\n * and may be either true/false or yes/no. If no value was provided or an invalid\n * value is provided, false will be returned.\n */\n boolean getBooleanOrFalse(@Nonnull String key);\n\n /**\n * Read a boolean value from the configuration. The value is not case-sensitivie,\n * and may be either true/false or yes/no. If no value was provided or an invalid\n * value is provided, true will be returned.\n */\n boolean getBooleanOrTrue(@Nonnull String key);\n\n /**\n * @throws ConfigMissingException if no value could be read for the specified key\n */\n boolean getBooleanOrThrow(@Nonnull String key);\n\n /**\n * Show where configuration is coming from. This is useful to drop in your logs\n * for troubleshooting.\n */\n String sources();\n}", "public interface ConfigFrom extends Supplier<Config> {\n /**\n * Convenience method for fluent syntax.\n *\n * @return a builder for specifying from where configuration should be loaded\n */\n @Nonnull\n static ConfigFrom firstOf() {\n return new ConfigFromImpl();\n }\n\n @Nonnull\n static Config other(Function<String, String> other) {\n if (other instanceof Config) {\n return (Config) other;\n }\n return new ConfigFromImpl().custom(other::apply).get();\n }\n\n ConfigFrom custom(Function<String, String> keyValueLookup);\n\n ConfigFrom value(String key, String value);\n\n ConfigFrom systemProperties();\n\n ConfigFrom env();\n\n ConfigFrom properties(Properties properties);\n\n ConfigFrom config(Config config);\n\n ConfigFrom config(Supplier<Config> config);\n\n /**\n * Adds a set of properties files to read from, which can be overridden by a system property \"properties\".\n * Equivalent to:\n * <pre>\n * defaultPropertyFiles(\"properties\", \"conf/app.properties\", \"local.properties\", \"sample.properties\")\n * </pre>\n */\n ConfigFrom defaultPropertyFiles();\n\n /**\n * Adds a set of properties files to read from, which can be overridden by a specified system property.\n * Equivalent to:\n * <pre>\n * defaultPropertyFiles(systemPropertyKey, Charset.defaultCharset().newDecoder(), filenames)\n * </pre>\n */\n ConfigFrom defaultPropertyFiles(String systemPropertyKey, String... filenames);\n\n /**\n * Adds a set of properties files to read from, which can be overridden by a specified system property.\n * Equivalent to:\n * <pre>\n * propertyFile(Charset.defaultCharset().newDecoder(),\n * System.getProperty(systemPropertyKey, String.join(File.pathSeparator, filenames))\n * .split(File.pathSeparator));\n * </pre>\n */\n ConfigFrom defaultPropertyFiles(String systemPropertyKey, CharsetDecoder decoder, String... filenames);\n\n ConfigFrom propertyFile(String... filenames);\n\n ConfigFrom propertyFile(CharsetDecoder decoder, String... filenames);\n\n ConfigFrom propertyFile(File... files);\n\n ConfigFrom propertyFile(CharsetDecoder decoder, File... files);\n\n ConfigFrom rename(String key, String newKey);\n\n ConfigFrom includeKeys(String... keys);\n\n ConfigFrom includePrefix(String... prefixes);\n\n ConfigFrom includeRegex(String regex);\n\n ConfigFrom excludeKeys(String... keys);\n\n ConfigFrom excludePrefix(String... prefixes);\n\n ConfigFrom excludeRegex(String regex);\n\n ConfigFrom removePrefix(String... prefixes);\n\n ConfigFrom addPrefix(String prefix);\n\n ConfigFrom substitutions(Config config);\n\n Config get();\n\n}", "public final class DatabaseProviderVertx implements Supplier<Database> {\n private static final Logger log = LoggerFactory.getLogger(DatabaseProviderVertx.class);\n private static final AtomicInteger poolNameCounter = new AtomicInteger(1);\n private WorkerExecutor executor;\n private DatabaseProviderVertx delegateTo = null;\n private Supplier<Connection> connectionProvider;\n private Connection connection = null;\n private Database database = null;\n private final Options options;\n\n public DatabaseProviderVertx(WorkerExecutor executor, Supplier<Connection> connectionProvider, Options options) {\n if (executor == null) {\n throw new IllegalArgumentException(\"Worker executor cannot be null\");\n }\n if (connectionProvider == null) {\n throw new IllegalArgumentException(\"Connection provider cannot be null\");\n }\n this.executor = executor;\n this.connectionProvider = connectionProvider;\n this.options = options;\n }\n\n private DatabaseProviderVertx(DatabaseProviderVertx delegateTo) {\n this.delegateTo = delegateTo;\n this.executor = delegateTo.executor;\n this.options = delegateTo.options;\n }\n\n /**\n * Configure the database from the following properties read from the provided configuration:\n * <br/>\n * <pre>\n * database.url=... Database connect string (required)\n * database.user=... Authenticate as this user (optional if provided in url)\n * database.password=... User password (optional if user and password provided in\n * url; prompted on standard input if user is provided and\n * password is not)\n * database.pool.size=... How many connections in the connection pool (default 10).\n * database.driver.class The driver to initialize with Class.forName(). This will\n * be guessed from the database.url if not provided.\n * database.flavor One of the enumerated values in {@link Flavor}. If this\n * is not provided the flavor will be guessed based on the\n * value for database.url, if possible.\n * </pre>\n *\n * <p>The database flavor will be guessed based on the URL.</p>\n *\n * <p>A database pool will be created using HikariCP.</p>\n *\n * <p>Be sure to retain a copy of the builder so you can call close() later to\n * destroy the pool. You will most likely want to register a JVM shutdown hook\n * to make sure this happens. See VertxServer.java in the demo directory for\n * an example of how to do this.</p>\n */\n @CheckReturnValue\n public static Builder pooledBuilder(Vertx vertx, Config config) {\n return fromPool(vertx, DatabaseProvider.createPool(config));\n }\n\n /**\n * Use an externally configured DataSource, Flavor, and optionally a shutdown hook.\n * The shutdown hook may be null if you don't want calls to Builder.close() to attempt\n * any shutdown. The DataSource and Flavor are mandatory.\n */\n @CheckReturnValue\n public static Builder fromPool(Vertx vertx, Pool pool) {\n WorkerExecutor executor = vertx.createSharedWorkerExecutor(\"DbWorker-\" + poolNameCounter.getAndAdd(1), pool.size);\n return new BuilderImpl(executor, () -> {\n try {\n executor.close();\n } catch (Exception e) {\n log.warn(\"Problem closing database worker executor\", e);\n }\n if (pool.poolShutdown != null) {\n pool.poolShutdown.close();\n }\n }, () -> {\n try {\n return pool.dataSource.getConnection();\n } catch (Exception e) {\n throw new DatabaseException(\"Unable to obtain a connection from DriverManager\", e);\n }\n }, new OptionsDefault(pool.flavor));\n }\n\n /**\n * Execute a transaction on the current thread, with default semantics (commit if\n * the code completes successfully, or rollback if it throws an error). Note you\n * will get a DatabaseException if you try to call this from the event loop thread.\n * If the provided code block throws anything, it will be wrapped into a DatabaseException\n * unless it was a ThreadDeath or was already a DatabaseException.\n */\n public void transact(final DbCode code) {\n if (io.vertx.core.Context.isOnEventLoopThread()) {\n throw new DatabaseException(\"Do not call transact() from event loop threads; use transactAsync() instead\");\n }\n\n boolean complete = false;\n try {\n code.run(this);\n complete = true;\n } catch (ThreadDeath | DatabaseException t) {\n throw t;\n } catch (Throwable t) {\n throw new DatabaseException(\"Error during transaction\", t);\n } finally {\n if (!complete) {\n rollbackAndClose();\n } else {\n commitAndClose();\n }\n }\n }\n\n public <T> T transactReturning(final DbCodeTyped<T> code) {\n if (io.vertx.core.Context.isOnEventLoopThread()) {\n throw new DatabaseException(\"Do not call transact() from event loop threads; use transactAsync() instead\");\n }\n\n T result;\n boolean complete = false;\n try {\n result = code.run(this);\n complete = true;\n } catch (ThreadDeath | DatabaseException t) {\n throw t;\n } catch (Throwable t) {\n throw new DatabaseException(\"Error during transaction\", t);\n } finally {\n if (!complete) {\n rollbackAndClose();\n } else {\n commitAndClose();\n }\n }\n return result;\n }\n\n /**\n * Execute a transaction on a Vert.x worker thread, with default semantics (commit if\n * the code completes successfully, or rollback if it throws an error). The provided\n * result handler will be call after the commit or rollback, and will run on the event\n * loop thread (the same thread that is calling this method).\n */\n public <T> void transactAsync(final DbCodeTyped<T> code, Handler<AsyncResult<T>> resultHandler) {\n VertxUtil.executeBlocking(executor, future -> {\n try {\n T returnValue;\n boolean complete = false;\n try {\n returnValue = code.run(this);\n complete = true;\n } catch (ThreadDeath | DatabaseException t) {\n throw t;\n } catch (Throwable t) {\n throw new DatabaseException(\"Error during transaction\", t);\n } finally {\n if (!complete) {\n rollbackAndClose();\n } else {\n commitAndClose();\n }\n }\n future.complete(returnValue);\n } catch (ThreadDeath t) {\n throw t;\n } catch (Throwable t) {\n future.fail(t);\n }\n }, resultHandler);\n }\n\n /**\n * Same as {@link #transact(DbCode)}, but your code block can explicitly\n * manage the behavior of the transaction.\n */\n public void transact(final DbCodeTx code) {\n if (io.vertx.core.Context.isOnEventLoopThread()) {\n throw new DatabaseException(\"Do not call transact() from event loop threads; use transactAsync() instead\");\n }\n\n Transaction tx = new TransactionImpl();\n tx.setRollbackOnError(true);\n tx.setRollbackOnly(false);\n boolean complete = false;\n try {\n code.run(this, tx);\n complete = true;\n } catch (ThreadDeath | DatabaseException t) {\n throw t;\n } catch (Throwable t) {\n throw new DatabaseException(\"Error during transaction\", t);\n } finally {\n if ((!complete && tx.isRollbackOnError()) || tx.isRollbackOnly()) {\n rollbackAndClose();\n } else {\n commitAndClose();\n }\n }\n }\n\n /**\n * Execute a transaction on a Vert.x worker thread, with default semantics (commit if\n * the code completes successfully, or rollback if it throws an error). The provided\n * result handler will be call after the commit or rollback, and will run on the event\n * loop thread (the same thread that is calling this method).\n */\n public <T> void transactAsync(final DbCodeTypedTx<T> code, Handler<AsyncResult<T>> resultHandler) {\n VertxUtil.executeBlocking(executor, future -> {\n try {\n T returnValue = null;\n Transaction tx = new TransactionImpl();\n tx.setRollbackOnError(true);\n tx.setRollbackOnly(false);\n boolean complete = false;\n try {\n returnValue = code.run(this, tx);\n complete = true;\n } catch (ThreadDeath | DatabaseException t) {\n throw t;\n } catch (Throwable t) {\n throw new DatabaseException(\"Error during transaction\", t);\n } finally {\n if ((!complete && tx.isRollbackOnError()) || tx.isRollbackOnly()) {\n rollbackAndClose();\n } else {\n commitAndClose();\n }\n }\n future.complete(returnValue);\n } catch (ThreadDeath t) {\n throw t;\n } catch (Throwable t) {\n future.fail(t);\n }\n }, resultHandler);\n }\n\n /**\n * This builder is immutable, so setting various options does not affect\n * the previous instance. This is intended to make it safe to pass builders\n * around without risk someone will reconfigure it.\n */\n public interface Builder {\n @CheckReturnValue\n Builder withOptions(OptionsOverride options);\n\n /**\n * Enable logging of parameter values along with the SQL.\n */\n @CheckReturnValue\n Builder withSqlParameterLogging();\n\n /**\n * Include SQL in exception messages. This will also include parameters in the\n * exception messages if SQL parameter logging is enabled. This is handy for\n * development, but be careful as this is an information disclosure risk,\n * dependent on how the exception are caught and handled.\n */\n @CheckReturnValue\n Builder withSqlInExceptionMessages();\n\n /**\n * Wherever argDateNowPerDb() is specified, use argDateNowPerApp() instead. This is\n * useful for testing purposes as you can use OptionsOverride to provide your\n * own system clock that will be used for time travel.\n */\n @CheckReturnValue\n Builder withDatePerAppOnly();\n\n /**\n * Allow provided Database instances to explicitly control transactions using the\n * commitNow() and rollbackNow() methods. Otherwise calling those methods would\n * throw an exception.\n */\n @CheckReturnValue\n Builder withTransactionControl();\n\n /**\n * This can be useful when testing code, as it can pretend to use transactions,\n * while giving you control over whether it actually commits or rolls back.\n */\n @CheckReturnValue\n Builder withTransactionControlSilentlyIgnored();\n\n /**\n * Allow direct access to the underlying database connection. Normally this is\n * not allowed, and is a bad idea, but it can be helpful when migrating from\n * legacy code that works with raw JDBC.\n */\n @CheckReturnValue\n Builder withConnectionAccess();\n\n /**\n * WARNING: You should try to avoid using this method. If you use it more\n * that once or twice in your entire codebase you are probably doing\n * something wrong.\n *\n * <p>If you use this method you are responsible for managing\n * the transaction and commit/rollback/close.</p>\n */\n @CheckReturnValue\n DatabaseProviderVertx create();\n\n /**\n * This is a convenience method to eliminate the need for explicitly\n * managing the resources (and error handling) for this class. After\n * the run block is complete the transaction will commit unless either the\n * {@link DbCode#run(Supplier)} method threw a {@link Throwable}.\n *\n * <p>Here is a typical usage:\n * <pre>\n * dbp.transact(dbs -> {\n * List<String> r = dbs.get().toSelect(\"select a from b where c=?\").argInteger(1).queryStrings();\n * });\n * </pre>\n * </p>\n *\n * @param code the code you want to run as a transaction with a Database\n * @see #transact(DbCodeTx)\n */\n void transact(DbCode code);\n\n /**\n * This method is the same as {@link #transact(DbCode)} but allows a return value.\n *\n * <p>Here is a typical usage:\n * <pre>\n * List<String> r = dbp.transact(dbs -> {\n * return dbs.get().toSelect(\"select a from b where c=?\").argInteger(1).queryStrings();\n * });\n * </pre>\n * </p>\n */\n <T> T transactReturning(DbCodeTyped<T> code);\n\n <T> void transactAsync(DbCodeTyped<T> code, Handler<AsyncResult<T>> resultHandler);\n\n /**\n * This is a convenience method to eliminate the need for explicitly\n * managing the resources (and error handling) for this class. After\n * the run block is complete commit() will be called unless either the\n * {@link DbCodeTx#run(Supplier, Transaction)} method threw a {@link Throwable}\n * while {@link Transaction#isRollbackOnError()} returns true, or\n * {@link Transaction#isRollbackOnly()} returns a true value.\n *\n * @param code the code you want to run as a transaction with a Database\n */\n void transact(DbCodeTx code);\n\n <T> void transactAsync(DbCodeTypedTx<T> code, Handler<AsyncResult<T>> resultHandler);\n\n void close();\n }\n\n private static class BuilderImpl implements Builder {\n private final WorkerExecutor executor;\n private Closeable pool;\n private final Supplier<Connection> connectionProvider;\n private final Options options;\n\n private BuilderImpl(WorkerExecutor executor, Closeable pool, Supplier<Connection> connectionProvider,\n Options options) {\n this.executor = executor;\n this.pool = pool;\n this.connectionProvider = connectionProvider;\n this.options = options;\n }\n\n @Override\n public Builder withOptions(OptionsOverride options) {\n return new BuilderImpl(executor, pool, connectionProvider, options.withParent(this.options));\n }\n\n @Override\n public Builder withSqlParameterLogging() {\n return new BuilderImpl(executor, pool, connectionProvider, new OptionsOverride() {\n @Override\n public boolean isLogParameters() {\n return true;\n }\n }.withParent(this.options));\n }\n\n @Override\n public Builder withSqlInExceptionMessages() {\n return new BuilderImpl(executor, pool, connectionProvider, new OptionsOverride() {\n @Override\n public boolean isDetailedExceptions() {\n return true;\n }\n }.withParent(this.options));\n }\n\n @Override\n public Builder withDatePerAppOnly() {\n return new BuilderImpl(executor, pool, connectionProvider, new OptionsOverride() {\n @Override\n public boolean useDatePerAppOnly() {\n return true;\n }\n }.withParent(this.options));\n }\n\n @Override\n public Builder withTransactionControl() {\n return new BuilderImpl(executor, pool, connectionProvider, new OptionsOverride() {\n @Override\n public boolean allowTransactionControl() {\n return true;\n }\n }.withParent(this.options));\n }\n\n @Override\n public Builder withTransactionControlSilentlyIgnored() {\n return new BuilderImpl(executor, pool, connectionProvider, new OptionsOverride() {\n @Override\n public boolean ignoreTransactionControl() {\n return true;\n }\n }.withParent(this.options));\n }\n\n @Override\n public Builder withConnectionAccess() {\n return new BuilderImpl(executor, pool, connectionProvider, new OptionsOverride() {\n @Override\n public boolean allowConnectionAccess() {\n return true;\n }\n }.withParent(this.options));\n }\n\n @Override\n public DatabaseProviderVertx create() {\n return new DatabaseProviderVertx(executor, connectionProvider, options);\n }\n\n @Override\n public void transact(DbCode tx) {\n create().transact(tx);\n }\n\n @Override\n public <T> T transactReturning(DbCodeTyped<T> tx) {\n return create().transactReturning(tx);\n }\n\n @Override\n public <T> void transactAsync(DbCodeTyped<T> code, Handler<AsyncResult<T>> resultHandler) {\n create().transactAsync(code, resultHandler);\n }\n\n @Override\n public void transact(DbCodeTx tx) {\n create().transact(tx);\n }\n\n @Override\n public <T> void transactAsync(DbCodeTypedTx<T> code, Handler<AsyncResult<T>> resultHandler) {\n create().transactAsync(code, resultHandler);\n }\n\n public void close() {\n if (pool != null) {\n try {\n pool.close();\n } catch (IOException e) {\n log.warn(\"Unable to close connection pool\", e);\n }\n pool = null;\n }\n }\n }\n\n public Database get() {\n if (delegateTo != null) {\n return delegateTo.get();\n }\n\n if (database != null) {\n return database;\n }\n\n if (connectionProvider == null) {\n throw new DatabaseException(\"Called get() on a DatabaseProviderVertx after close()\");\n }\n\n Metric metric = new Metric(log.isDebugEnabled());\n try {\n connection = connectionProvider.get();\n metric.checkpoint(\"getConn\");\n try {\n // JDBC specifies that autoCommit is the default for all new connections.\n // Don't try to be clever about clearing it conditionally.\n if (!options.flavor().autoCommitOnly()) {\n connection.setAutoCommit(false);\n metric.checkpoint(\"setAutoCommit\");\n }\n } catch (SQLException e) {\n throw new DatabaseException(\"Unable to set autoCommit for the connection\", e);\n }\n database = new DatabaseImpl(connection, options);\n metric.checkpoint(\"dbInit\");\n } catch (RuntimeException e) {\n metric.checkpoint(\"fail\");\n throw e;\n } finally {\n metric.done();\n if (log.isDebugEnabled()) {\n StringBuilder buf = new StringBuilder(\"Get \").append(options.flavor()).append(\" database: \");\n metric.printMessage(buf);\n log.debug(buf.toString());\n }\n }\n return database;\n }\n\n\n public Builder fakeBuilder() {\n return new Builder() {\n @Override\n public Builder withOptions(OptionsOverride optionsOverride) {\n return this;\n }\n\n @Override\n public Builder withSqlParameterLogging() {\n return this;\n }\n\n @Override\n public Builder withSqlInExceptionMessages() {\n return this;\n }\n\n @Override\n public Builder withDatePerAppOnly() {\n return this;\n }\n\n @Override\n public Builder withTransactionControl() {\n return this;\n }\n\n @Override\n public Builder withTransactionControlSilentlyIgnored() {\n return this;\n }\n\n @Override\n public Builder withConnectionAccess() {\n return this;\n }\n\n @Override\n public DatabaseProviderVertx create() {\n return new DatabaseProviderVertx(DatabaseProviderVertx.this);\n }\n\n @Override\n public void transact(DbCode tx) {\n create().transact(tx);\n }\n\n @Override\n public <T> T transactReturning(DbCodeTyped<T> tx) {\n return create().transactReturning(tx);\n }\n\n @Override\n public <T> void transactAsync(DbCodeTyped<T> code, Handler<AsyncResult<T>> resultHandler) {\n create().transactAsync(code, resultHandler);\n }\n\n @Override\n public void transact(DbCodeTx tx) {\n create().transact(tx);\n }\n\n @Override\n public <T> void transactAsync(DbCodeTypedTx<T> code, Handler<AsyncResult<T>> resultHandler) {\n create().transactAsync(code, resultHandler);\n }\n\n @Override\n public void close() {\n log.debug(\"Ignoring close call on fakeBuilder\");\n }\n };\n }\n\n public void commitAndClose() {\n if (delegateTo != null) {\n log.debug(\"Ignoring commitAndClose() because this is a fake provider\");\n return;\n }\n\n if (connection != null) {\n try {\n if (!options.flavor().autoCommitOnly()) {\n connection.commit();\n }\n } catch (Exception e) {\n throw new DatabaseException(\"Unable to commit the transaction\", e);\n }\n close();\n }\n }\n\n public void rollbackAndClose() {\n if (delegateTo != null) {\n log.debug(\"Ignoring rollbackAndClose() because this is a fake provider\");\n return;\n }\n\n if (connection != null) {\n try {\n if (!options.flavor().autoCommitOnly()) {\n connection.rollback();\n }\n } catch (Exception e) {\n log.error(\"Unable to rollback the transaction\", e);\n }\n close();\n }\n }\n\n private void close() {\n if (connection != null) {\n try {\n connection.close();\n } catch (Exception e) {\n log.error(\"Unable to close the database connection\", e);\n }\n }\n connection = null;\n database = null;\n connectionProvider = null;\n }\n}", "public interface Builder {\n @CheckReturnValue\n Builder withOptions(OptionsOverride options);\n\n /**\n * Enable logging of parameter values along with the SQL.\n */\n @CheckReturnValue\n Builder withSqlParameterLogging();\n\n /**\n * Include SQL in exception messages. This will also include parameters in the\n * exception messages if SQL parameter logging is enabled. This is handy for\n * development, but be careful as this is an information disclosure risk,\n * dependent on how the exception are caught and handled.\n */\n @CheckReturnValue\n Builder withSqlInExceptionMessages();\n\n /**\n * Wherever argDateNowPerDb() is specified, use argDateNowPerApp() instead. This is\n * useful for testing purposes as you can use OptionsOverride to provide your\n * own system clock that will be used for time travel.\n */\n @CheckReturnValue\n Builder withDatePerAppOnly();\n\n /**\n * Allow provided Database instances to explicitly control transactions using the\n * commitNow() and rollbackNow() methods. Otherwise calling those methods would\n * throw an exception.\n */\n @CheckReturnValue\n Builder withTransactionControl();\n\n /**\n * This can be useful when testing code, as it can pretend to use transactions,\n * while giving you control over whether it actually commits or rolls back.\n */\n @CheckReturnValue\n Builder withTransactionControlSilentlyIgnored();\n\n /**\n * Allow direct access to the underlying database connection. Normally this is\n * not allowed, and is a bad idea, but it can be helpful when migrating from\n * legacy code that works with raw JDBC.\n */\n @CheckReturnValue\n Builder withConnectionAccess();\n\n /**\n * WARNING: You should try to avoid using this method. If you use it more\n * that once or twice in your entire codebase you are probably doing\n * something wrong.\n *\n * <p>If you use this method you are responsible for managing\n * the transaction and commit/rollback/close.</p>\n */\n @CheckReturnValue\n DatabaseProviderVertx create();\n\n /**\n * This is a convenience method to eliminate the need for explicitly\n * managing the resources (and error handling) for this class. After\n * the run block is complete the transaction will commit unless either the\n * {@link DbCode#run(Supplier)} method threw a {@link Throwable}.\n *\n * <p>Here is a typical usage:\n * <pre>\n * dbp.transact(dbs -> {\n * List<String> r = dbs.get().toSelect(\"select a from b where c=?\").argInteger(1).queryStrings();\n * });\n * </pre>\n * </p>\n *\n * @param code the code you want to run as a transaction with a Database\n * @see #transact(DbCodeTx)\n */\n void transact(DbCode code);\n\n /**\n * This method is the same as {@link #transact(DbCode)} but allows a return value.\n *\n * <p>Here is a typical usage:\n * <pre>\n * List<String> r = dbp.transact(dbs -> {\n * return dbs.get().toSelect(\"select a from b where c=?\").argInteger(1).queryStrings();\n * });\n * </pre>\n * </p>\n */\n <T> T transactReturning(DbCodeTyped<T> code);\n\n <T> void transactAsync(DbCodeTyped<T> code, Handler<AsyncResult<T>> resultHandler);\n\n /**\n * This is a convenience method to eliminate the need for explicitly\n * managing the resources (and error handling) for this class. After\n * the run block is complete commit() will be called unless either the\n * {@link DbCodeTx#run(Supplier, Transaction)} method threw a {@link Throwable}\n * while {@link Transaction#isRollbackOnError()} returns true, or\n * {@link Transaction#isRollbackOnly()} returns a true value.\n *\n * @param code the code you want to run as a transaction with a Database\n */\n void transact(DbCodeTx code);\n\n <T> void transactAsync(DbCodeTypedTx<T> code, Handler<AsyncResult<T>> resultHandler);\n\n void close();\n}", "public class Metric {\n private final boolean enabled;\n private boolean done;\n private long startNanos;\n private long lastCheckpointNanos;\n private List<Checkpoint> checkpoints;\n\n private static class Checkpoint {\n String description;\n long durationNanos;\n private final Object[] args;\n\n Checkpoint(String description, long durationNanos, Object... args) {\n this.description = description;\n this.durationNanos = durationNanos;\n this.args = args;\n }\n }\n\n /**\n * <p>Create a metric tracking object and start the nanosecond timer. Times\n * are obtained using {@code System.nanoTime()}. The canonical way to use\n * this looks something like this:\n * </p>\n *\n * <pre>\n * Metric metric = new Metric(log.isDebugEnabled);\n * ...\n * metric.checkpoint(\"received\");\n * ...\n * metric.checkpoint(\"processed\");\n * ...\n * metric.done(\"sent\");\n * ...\n * if (log.isDebugEnabled()) {\n * log.debug(\"Processed: \" + metric.getMessage());\n * }\n * </pre>\n *\n * @param enabled {@code true} if timings will be taken, {@code false} to\n * optimize out the time tracking\n */\n public Metric(boolean enabled) {\n this.enabled = enabled;\n if (enabled) {\n checkpoints = new ArrayList<>();\n startNanos = System.nanoTime();\n lastCheckpointNanos = startNanos;\n }\n }\n\n /**\n * Find out how many milliseconds have elapsed since this timer was started.\n *\n * @return the number of milliseconds elapsed, or -1 if {@code false} was\n * passed in the constructor\n */\n public long elapsedMillis() {\n if (!enabled) {\n return -1;\n }\n return (System.nanoTime() - startNanos) / 1000000;\n }\n\n /**\n * Find out how many nanoseconds have elapsed since this timer was started.\n *\n * @return the number of nanoseconds elapsed, or -1 if {@code false} was\n * passed in the constructor\n */\n public long elapsedNanos() {\n if (!enabled) {\n return -1;\n }\n return (System.nanoTime() - startNanos);\n }\n\n /**\n * Set a mark for timing. It is strongly recommended to use a short,\n * simple alphanumeric description. For example, \"sent\" or \"didThat\".\n * With this version you can provide additional arguments, such as\n * byte counts, which will be appended comma-separated within brackets.\n * For example, {@code checkpoint(\"sent\", 25, 3)} will result in a\n * description \"sent[25,3]\". The string evaluation and concatenation is\n * lazy, and won't be done if this metric is disabled.\n *\n * @param description a label for this mark; may not be null; spaces\n * and tabs will be converted to underscores\n * @param args additional information to append to the description; will\n * print \"null\" if null; evaluated with String.valueOf() lazily\n * and sanitized of most non-alphanumeric characters\n */\n public void checkpoint(String description, Object... args) {\n if (enabled) {\n long currentCheckpointNanos = System.nanoTime();\n checkpoints.add(new Checkpoint(noTabsOrSpaces(description), currentCheckpointNanos - lastCheckpointNanos, args));\n lastCheckpointNanos = currentCheckpointNanos;\n }\n }\n\n /**\n * Set a final mark for timing and stop the timer. Once you call this\n * method, subsequent calls have no effect.\n *\n * @param description a label for this mark; may not be null; spaces\n * and tabs will be converted to underscores\n * @return time in nanoseconds from the start of this metric, or -1\n * if {@code false} was passed in the constructor\n */\n public long done(String description, Object... args) {\n checkpoint(description, args);\n return done();\n }\n\n /**\n * Indicate we are done (stop the timer). Once you call this\n * method, subsequent calls have no effect.\n *\n * @return time in nanoseconds from the start of this metric, or -1\n * if {@code false} was passed in the constructor\n */\n public long done() {\n if (enabled) {\n if (!done) {\n lastCheckpointNanos = System.nanoTime();\n done = true;\n }\n return lastCheckpointNanos - startNanos;\n }\n return -1;\n }\n\n /**\n * Construct and return a message based on the timing and checkpoints. This\n * will look like \"123.456ms(checkpoint1=100.228ms,checkpoint2=23.228ms)\"\n * without the quotes. There will be no spaces or tabs in the output.\n *\n * <p>This will automatically call the done() method to stop the timer if\n * you haven't already done so.</p>\n *\n * @return a string with timing information, or {@code \"metricsDisabled\"}\n * if {@code false} was passed in the constructor.\n * @see #printMessage(StringBuilder)\n */\n public String getMessage() {\n if (enabled) {\n StringBuilder buf = new StringBuilder();\n printMessage(buf);\n return buf.toString();\n }\n return \"metricsDisabled\";\n }\n\n /**\n * Construct and print a message based on the timing and checkpoints. This\n * will look like \"123.456ms(checkpoint1=100.228ms,checkpoint2=23.228ms)\"\n * without the quotes. There will be no spaces or tabs in the output. A\n * value of {@code \"metricsDisabled\"} will be printed if {@code false} was\n * passed in the constructor.\n *\n * <p>This will automatically call the done() method to stop the timer if\n * you haven't already done so.</p>\n *\n * @param buf the message will be printed to this builder\n * @see #getMessage()\n */\n public void printMessage(StringBuilder buf) {\n if (enabled) {\n done();\n writeNanos(buf, lastCheckpointNanos - startNanos);\n if (!checkpoints.isEmpty()) {\n buf.append(\"(\");\n boolean first = true;\n for (Checkpoint checkpoint : checkpoints) {\n if (first) {\n first = false;\n } else {\n buf.append(',');\n }\n buf.append(checkpoint.description);\n if (checkpoint.args != null && checkpoint.args.length > 0) {\n buf.append('[');\n boolean firstArg = true;\n for (Object o : checkpoint.args) {\n if (firstArg) {\n firstArg = false;\n } else {\n buf.append(',');\n }\n buf.append(sanitizeArg(String.valueOf(o)));\n }\n buf.append(']');\n }\n buf.append('=');\n writeNanos(buf, checkpoint.durationNanos);\n }\n buf.append(')');\n }\n } else {\n buf.append(\"metricsDisabled\");\n }\n }\n\n private void writeNanos(StringBuilder buf, long nanos) {\n if (nanos < 0) {\n buf.append(\"-\");\n nanos = -nanos;\n }\n String nanosStr = Long.toString(nanos);\n if (nanosStr.length() > 6) {\n buf.append(nanosStr.substring(0, nanosStr.length() - 6));\n buf.append('.');\n buf.append(nanosStr.substring(nanosStr.length() - 6, nanosStr.length() - 3));\n } else {\n buf.append(\"0.0000000\".substring(0, 8 - Math.max(nanosStr.length(), 4)));\n if (nanosStr.length() > 3) {\n buf.append(nanosStr.substring(0, nanosStr.length() - 3));\n }\n }\n buf.append(\"ms\");\n }\n\n private String noTabsOrSpaces(String s) {\n return s.replace(' ', '_').replace('\\t', '_');\n }\n\n private String sanitizeArg(String s) {\n return s.replaceAll(\"[^\\\\p{Alnum}_.\\\\-\\\\+]\", \"*\");\n }\n}", "public class Schema {\n private List<Table> tables = new ArrayList<>();\n private List<Sequence> sequences = new ArrayList<>();\n private boolean indexForeignKeys = true;\n private String userTableName = \"user_principal\";\n\n public Sequence addSequence(String name) {\n Sequence sequence = new Sequence(name);\n sequences.add(sequence);\n return sequence;\n }\n\n public Schema withoutForeignKeyIndexing() {\n indexForeignKeys = false;\n return this;\n }\n\n /**\n * Set the table to which the foreign key will be created for\n * user change tracking ({@link Table#trackCreateTimeAndUser(String)}\n * and {@link Table#trackUpdateTimeAndUser(String)}).\n *\n * @param userTableName the default table name containing users\n */\n public Schema userTableName(String userTableName) {\n this.userTableName = userTableName;\n return this;\n }\n\n public enum ColumnType {\n Integer, Long, Float, Double, BigDecimal, StringVar, StringFixed, Clob, Blob, Date, LocalDate, Boolean\n }\n\n public void validate() {\n for (Table t : tables) {\n t.validate();\n }\n for (Sequence s : sequences) {\n s.validate();\n }\n }\n\n public Table addTable(String name) {\n Table table = new Table(name);\n tables.add(table);\n return table;\n }\n\n public Table addTableFromRow(String tableName, Row r) {\n Table table = addTable(tableName);\n try {\n ResultSetMetaData metadata = r.getMetadata();\n\n int columnCount = metadata.getColumnCount();\n String[] names = new String[columnCount];\n for (int i = 0; i < columnCount; i++) {\n names[i] = metadata.getColumnName(i + 1);\n }\n names = SqlArgs.tidyColumnNames(names);\n\n for (int i = 0; i < columnCount; i++) {\n int type = metadata.getColumnType(i + 1);\n\n switch (type) {\n case Types.SMALLINT:\n case Types.INTEGER:\n table.addColumn(names[i]).asInteger();\n break;\n case Types.BIGINT:\n table.addColumn(names[i]).asLong();\n break;\n case Types.REAL:\n case 100: // Oracle proprietary it seems\n table.addColumn(names[i]).asFloat();\n break;\n case Types.DOUBLE:\n case 101: // Oracle proprietary it seems\n table.addColumn(names[i]).asDouble();\n break;\n case Types.NUMERIC:\n int precision1 = metadata.getPrecision(i + 1);\n int scale = metadata.getScale(i + 1);\n if (precision1 == 10 && scale == 0) {\n // Oracle reports integer as numeric\n table.addColumn(names[i]).asInteger();\n } else if (precision1 == 19 && scale == 0) {\n // Oracle reports long as numeric\n table.addColumn(names[i]).asLong();\n } else if (precision1 == 126 && scale == -127) {\n // this clause was added to support ETL from MSSQL Server\n table.addColumn(names[i]).asFloat();\n } else if (precision1 == 0 && scale == -127) {\n // this clause was also added to support ETL from MSSQL Server\n table.addColumn(names[i]).asInteger();\n } else {\n table.addColumn(names[i]).asBigDecimal(precision1, scale);\n }\n break;\n case Types.BINARY:\n case Types.VARBINARY:\n case Types.BLOB:\n table.addColumn(names[i]).asBlob();\n break;\n case Types.CLOB:\n case Types.NCLOB:\n table.addColumn(names[i]).asClob();\n break;\n\n // The date type is used for a true date - no time info.\n // It must be checked before TimeStamp because sql dates are also\n // recognized as sql timestamp.\n case Types.DATE:\n table.addColumn(names[i]).asLocalDate();\n break;\n\n // This is the type dates and times with time and time zone associated.\n // Note that Oracle dates are always really Timestamps.\n case Types.TIMESTAMP:\n // Check if we really have a LocalDate implemented by the DB as a timestamp\n if (metadata.getScale(i + 1) == 0) {\n // If the scale is 0, this is a LocalDate (no time/timezone).\n // Anything with a time/timezone will have a non-zero scale\n table.addColumn(names[i]).asLocalDate();\n } else {\n table.addColumn(names[i]).asDate();\n }\n break;\n\n case Types.NVARCHAR:\n case Types.VARCHAR:\n int precision = metadata.getPrecision(i + 1);\n if (precision >= 2147483647) {\n // Postgres seems to report clobs are varchar(2147483647)\n table.addColumn(names[i]).asClob();\n } else {\n table.addColumn(names[i]).asString(precision);\n }\n break;\n case Types.CHAR:\n case Types.NCHAR:\n table.addColumn(names[i]).asStringFixed(metadata.getPrecision(i + 1));\n break;\n default:\n throw new DatabaseException(\"Don't know what type to use for: \" + type);\n }\n }\n } catch (SQLException e) {\n throw new DatabaseException(\"Unable to retrieve metadata from ResultSet\", e);\n }\n return table;\n }\n\n public class Sequence {\n private final String name;\n private long min = 1;\n private long max = 999999999999999999L;\n private int increment = 1;\n private long start = 1;\n private int cache = 1;\n private boolean order;\n private boolean cycle;\n\n public Sequence(String name) {\n this.name = toName(name);\n }\n\n public Sequence min(long min) {\n if (start == this.min) {\n start = min;\n }\n this.min = min;\n return this;\n }\n\n public Sequence max(long max) {\n this.max = max;\n return this;\n }\n\n public Sequence increment(int increment) {\n this.increment = increment;\n return this;\n }\n\n public Sequence start(long start) {\n this.start = start;\n return this;\n }\n\n public Sequence cache(int cache) {\n this.cache = cache < 2 ? 1 : cache;\n return this;\n }\n\n /**\n * On databases that support it, indicate you want to strictly order the values returned\n * from the sequence. This is generally NOT what you want, because it can dramatically\n * reduce performance (requires locking and synchronization). Also keep in mind it doesn't\n * guarantee there will not be gaps in the numbers handed out (nothing you can do will\n * ever prevent that).\n */\n public Sequence order() {\n order = true;\n return this;\n }\n\n public Sequence cycle() {\n cycle = true;\n return this;\n }\n\n private void validate() {\n\n }\n\n public Schema schema() {\n validate();\n return Schema.this;\n }\n }\n\n public class Table {\n private final String name;\n private String comment;\n private List<Column> columns = new ArrayList<>();\n private PrimaryKey primaryKey;\n private List<ForeignKey> foreignKeys = new ArrayList<>();\n private List<Index> indexes = new ArrayList<>();\n private List<Check> checks = new ArrayList<>();\n private List<Unique> uniques = new ArrayList<>();\n private Map<Flavor, String> customClauses = new HashMap<>();\n private boolean createTracking;\n private String createTrackingFkName;\n private String createTrackingFkTable;\n private boolean updateTracking;\n private String updateTrackingFkName;\n private String updateTrackingFkTable;\n private boolean updateSequence;\n private boolean historyTable;\n\n public Table(String name) {\n this.name = toName(name);\n if (this.name.length() > 27) {\n throw new RuntimeException(\"Table name should be 27 characters or less\");\n }\n }\n\n public void validate() {\n if (columns.size() < 1) {\n throw new RuntimeException(\"Table \" + name + \" needs at least one column\");\n }\n for (Column c : columns) {\n c.validate();\n }\n\n if (primaryKey != null) {\n primaryKey.validate();\n }\n\n for (ForeignKey fk : foreignKeys) {\n fk.validate();\n }\n\n for (Check c : checks) {\n c.validate();\n }\n\n for (Index i : indexes) {\n i.validate();\n }\n }\n\n public Schema schema() {\n if (createTracking) {\n addColumn(\"create_time\").asDate().table();\n }\n if (createTrackingFkName != null) {\n addColumn(\"create_user\").foreignKey(createTrackingFkName).references(createTrackingFkTable).table();\n }\n if (updateTracking || updateSequence) {\n addColumn(\"update_time\").asDate().table();\n }\n if (updateTrackingFkName != null) {\n addColumn(\"update_user\").foreignKey(updateTrackingFkName).references(updateTrackingFkTable).table();\n }\n if (updateSequence) {\n addColumn(\"update_sequence\").asLong().table();\n }\n // Avoid auto-indexing foreign keys if an index already exists (the first columns of the pk or explicit index)\n if (indexForeignKeys) {\n for (ForeignKey fk : foreignKeys) {\n if (primaryKey != null && 0 == Collections.indexOfSubList(primaryKey.columnNames, fk.columnNames)) {\n continue;\n }\n boolean skip = false;\n for (Index i : indexes) {\n if (0 == Collections.indexOfSubList(i.columnNames, fk.columnNames)) {\n skip = true;\n break;\n }\n }\n if (!skip) {\n addIndex(fk.name + \"_ix\", fk.columnNames.toArray(new String[fk.columnNames.size()]));\n }\n }\n }\n validate();\n if (historyTable) {\n String historyTableName = name + \"_history\";\n if (historyTableName.length() > 27 && historyTableName.length() <= 30) {\n historyTableName = name + \"_hist\";\n }\n Table hist = Schema.this.addTable(historyTableName);\n // History table needs all the same columns as the original\n hist.columns.addAll(columns);\n // Add a synthetic column to indicate when the original row has been deleted\n hist.addColumn(\"is_deleted\").asBoolean().table();\n List<String> pkColumns = new ArrayList<>();\n pkColumns.addAll(primaryKey.columnNames);\n // Index the primary key from the regular table for retrieving history\n hist.addIndex(historyTableName + \"_ix\", pkColumns.toArray(new String[pkColumns.size()]));\n // The primary key for the history table will be that of the original table, plus the update sequence\n pkColumns.add(\"update_sequence\");\n hist.addPrimaryKey(historyTableName + \"_pk\", pkColumns.toArray(new String[pkColumns.size()]));\n // To perform any validation\n hist.schema();\n }\n return Schema.this;\n }\n\n public Table withComment(String comment) {\n this.comment = comment;\n return this;\n }\n\n public Table withStandardPk() {\n return addColumn(name + \"_id\").primaryKey().table();\n }\n\n public Table trackCreateTime() {\n createTracking = true;\n return this;\n }\n\n public Table trackCreateTimeAndUser(String fkConstraintName) {\n return trackCreateTimeAndUser(fkConstraintName, userTableName);\n }\n\n public Table trackCreateTimeAndUser(String fkConstraintName, String fkReferencesTable) {\n createTracking = true;\n createTrackingFkName = fkConstraintName;\n createTrackingFkTable = fkReferencesTable;\n return this;\n }\n\n public Table trackUpdateTime() {\n updateTracking = true;\n updateSequence = true;\n return this;\n }\n\n public Table trackUpdateTimeAndUser(String fkConstraintName) {\n return trackUpdateTimeAndUser(fkConstraintName, userTableName);\n }\n\n public Table trackUpdateTimeAndUser(String fkConstraintName, String fkReferencesTable) {\n updateTracking = true;\n updateSequence = true;\n updateTrackingFkName = fkConstraintName;\n updateTrackingFkTable = fkReferencesTable;\n return this;\n }\n\n public Table withHistoryTable() {\n updateSequence = true;\n historyTable = true;\n return this;\n }\n\n public Column addColumn(String name) {\n Column column = new Column(name);\n columns.add(column);\n return column;\n }\n\n public PrimaryKey addPrimaryKey(String name, String...columnNames) {\n if (primaryKey != null) {\n throw new RuntimeException(\"Only one primary key is allowed. For composite keys use\"\n + \" addPrimaryKey(name, c1, c2, ...).\");\n }\n for (Column c: columns) {\n if (c.name.equalsIgnoreCase(name)) {\n throw new RuntimeException(\"For table: \" + this.name + \" primary key name should not be a column name: \" + name);\n }\n }\n primaryKey = new PrimaryKey(name, columnNames);\n return primaryKey;\n }\n\n public ForeignKey addForeignKey(String name, String...columnNames) {\n ForeignKey foreignKey = new ForeignKey(name, columnNames);\n foreignKeys.add(foreignKey);\n return foreignKey;\n }\n\n public Check addCheck(String name, String expression) {\n Check check = new Check(name, expression);\n checks.add(check);\n return check;\n }\n\n public Unique addUnique(String name, String...columnNames) {\n Unique unique = new Unique(name, columnNames);\n uniques.add(unique);\n return unique;\n }\n\n public Index addIndex(String name, String... columnNames) {\n Index index = new Index(name, columnNames);\n indexes.add(index);\n return index;\n }\n\n public Table customTableClause(Flavor flavor, String clause) {\n customClauses.put(flavor, clause);\n return this;\n }\n\n public class PrimaryKey {\n private final String name;\n private final List<String> columnNames = new ArrayList<>();\n\n public PrimaryKey(String name, String[] columnNames) {\n this.name = toName(name);\n for (String s : columnNames) {\n this.columnNames.add(toName(s));\n }\n }\n\n public void validate() {\n\n }\n\n public Table table() {\n validate();\n return Table.this;\n }\n }\n\n public class Unique {\n private final String name;\n private final List<String> columnNames = new ArrayList<>();\n\n public Unique(String name, String[] columnNames) {\n this.name = toName(name);\n for (String s : columnNames) {\n this.columnNames.add(toName(s));\n }\n }\n\n public void validate() {\n\n }\n\n public Table table() {\n validate();\n return Table.this;\n }\n }\n\n public class ForeignKey {\n private final String name;\n private final List<String> columnNames = new ArrayList<>();\n private boolean onDeleteCascade = false;\n public String foreignTable;\n\n public ForeignKey(String name, String[] columnNames) {\n this.name = toName(name);\n for (String s : columnNames) {\n this.columnNames.add(toName(s));\n }\n }\n\n public ForeignKey references(String tableName) {\n foreignTable = toName(tableName);\n return this;\n }\n\n public ForeignKey onDeleteCascade() {\n onDeleteCascade = true;\n return this;\n }\n\n private void validate() {\n if (foreignTable == null) {\n throw new RuntimeException(\"Foreign key \" + name + \" must reference a table\");\n }\n }\n\n public Table table() {\n validate();\n return Table.this;\n }\n }\n\n public class Check {\n private final String name;\n private final String expression;\n\n public Check(String name, String expression) {\n this.name = toName(name);\n this.expression = expression;\n }\n\n private void validate() {\n if (expression == null) {\n throw new RuntimeException(\"Expression needed for check constraint \" + name + \" on table \" + Table.this.name);\n }\n }\n\n public Table table() {\n validate();\n return Table.this;\n }\n }\n\n public class Index {\n private final String name;\n private final List<String> columnNames = new ArrayList<>();\n private boolean unique;\n\n public Index(String name, String[] columnNames) {\n this.name = toName(name);\n for (String s : columnNames) {\n this.columnNames.add(toName(s));\n }\n }\n\n public Index unique() {\n unique = true;\n return this;\n }\n\n private void validate() {\n if (columnNames.size() < 1) {\n throw new RuntimeException(\"Index \" + name + \" needs at least one column\");\n }\n }\n\n public Table table() {\n validate();\n return Table.this;\n }\n }\n\n public class Column {\n private final String name;\n private ColumnType type;\n private int scale;\n private int precision;\n private boolean notNull;\n private String comment;\n\n public Column(String name) {\n this.name = toName(name);\n }\n\n /**\n * Create a boolean column, usually char(1) to hold values 'Y' or 'N'. This\n * parameterless version does not create any check constraint at the database\n * level.\n */\n public Column asBoolean() {\n return asType(ColumnType.Boolean);\n }\n\n /**\n * Create a boolean column, usually char(1) to hold values 'Y' or 'N'. This\n * version creates a check constraint at the database level with the provided name.\n */\n public Column asBoolean(String checkConstraintName) {\n return asBoolean().check(checkConstraintName, name + \" in ('Y', 'N')\");\n }\n\n public Column asInteger() {\n return asType(ColumnType.Integer);\n }\n\n public Column asLong() {\n return asType(ColumnType.Long);\n }\n\n public Column asFloat() {\n return asType(ColumnType.Float);\n }\n\n public Column asDouble() {\n return asType(ColumnType.Double);\n }\n\n public Column asBigDecimal(int scale, int precision) {\n this.scale = scale;\n this.precision = precision;\n return asType(ColumnType.BigDecimal);\n }\n\n public Column asString(int scale) {\n this.scale = scale;\n return asType(ColumnType.StringVar);\n }\n\n public Column asStringFixed(int scale) {\n this.scale = scale;\n return asType(ColumnType.StringFixed);\n }\n\n // This type is for dates that have time associated\n public Column asDate() {\n return asType(ColumnType.Date);\n }\n\n // This type is for true dates with no time associated\n public Column asLocalDate() {\n return asType(ColumnType.LocalDate);\n }\n\n public Column asClob() {\n return asType(ColumnType.Clob);\n }\n\n public Column asBlob() {\n return asType(ColumnType.Blob);\n }\n\n private Column asType(ColumnType type) {\n this.type = type;\n return this;\n }\n\n public Column notNull() {\n this.notNull = true;\n return this;\n }\n\n private void validate() {\n if (type == null) {\n throw new RuntimeException(\"Call as*() on column \" + name + \" table \" + Table.this.name);\n }\n }\n\n public Table table() {\n validate();\n return Table.this;\n }\n\n public ForeignKey foreignKey(String constraintName) {\n if (type == null) {\n asLong();\n }\n return table().addForeignKey(constraintName, name);\n }\n\n public Column check(String checkConstraintName, String expression) {\n table().addCheck(checkConstraintName, expression).table();\n return this;\n }\n\n public Column primaryKey() {\n if (type == null) {\n asLong();\n }\n if (comment == null) {\n comment = \"Internally generated primary key\";\n }\n notNull();\n Table.this.addPrimaryKey(Table.this.name + \"_pk\", name);\n return this;\n }\n\n public Column unique(String constraintName) {\n notNull();\n Table.this.addUnique(constraintName, name);\n return this;\n }\n\n public Column withComment(String comment) {\n this.comment = comment;\n return this;\n }\n\n public Schema schema() {\n return table().schema();\n }\n }\n }\n\n public void execute(Supplier<Database> db) {\n executeOrPrint(db.get(), null);\n }\n\n public String print(Flavor flavor) {\n return executeOrPrint(null, flavor);\n }\n\n private String executeOrPrint(Database db, Flavor flavor) {\n validate();\n\n if (flavor == null) {\n flavor = db.flavor();\n }\n StringBuilder script = new StringBuilder();\n\n for (Table table : tables) {\n Sql sql = new Sql();\n sql.append(\"create table \").append(table.name).append(\" (\\n\");\n boolean first = true;\n for (Column column : table.columns) {\n if (first) {\n first = false;\n sql.append(\" \");\n } else {\n sql.append(\",\\n \");\n }\n sql.append(rpad(column.name, 30)).append(\" \");\n switch (column.type) {\n case Boolean:\n sql.append(flavor.typeBoolean());\n break;\n case Integer:\n sql.append(flavor.typeInteger());\n break;\n case Long:\n sql.append(flavor.typeLong());\n break;\n case Float:\n sql.append(flavor.typeFloat());\n break;\n case Double:\n sql.append(flavor.typeDouble());\n break;\n case BigDecimal:\n sql.append(flavor.typeBigDecimal(column.scale, column.precision));\n break;\n case StringVar:\n sql.append(flavor.typeStringVar(column.scale));\n break;\n case StringFixed:\n sql.append(flavor.typeStringFixed(column.scale));\n break;\n case Date:\n sql.append(flavor.typeDate()); // Append a date with time\n break;\n case LocalDate:\n sql.append(flavor.typeLocalDate()); // Append a true date - no time\n break;\n case Clob:\n sql.append(flavor.typeClob());\n break;\n case Blob:\n sql.append(flavor.typeBlob());\n break;\n }\n if (column.notNull) {\n sql.append(\" not null\");\n }\n }\n\n if (table.primaryKey != null) {\n sql.append(\",\\n constraint \");\n sql.append(rpad(table.primaryKey.name, 30));\n sql.listStart(\" primary key (\");\n for (String name : table.primaryKey.columnNames) {\n sql.listSeparator(\", \");\n sql.append(name);\n }\n sql.listEnd(\")\");\n }\n\n for (Unique u : table.uniques) {\n sql.append(\",\\n constraint \");\n sql.append(rpad(u.name, 30));\n sql.listStart(\" unique (\");\n for (String name : u.columnNames) {\n sql.listSeparator(\", \");\n sql.append(name);\n }\n sql.listEnd(\")\");\n }\n\n for (Check check : table.checks) {\n sql.append(\",\\n constraint \");\n sql.append(rpad(check.name, 30));\n sql.append(\" check (\");\n sql.append(check.expression);\n sql.append(\")\");\n }\n\n sql.append(\"\\n)\");\n if (table.customClauses.containsKey(flavor)) {\n sql.append(\" \").append(table.customClauses.get(flavor));\n }\n executeOrPrint(sql, db, script);\n sql = new Sql();\n\n if (flavor == Flavor.oracle || flavor == Flavor.postgresql) {\n if (table.comment != null) {\n sql.append(\"comment on table \");\n sql.append(table.name);\n sql.append(\" is \\n'\");\n sql.append(table.comment.replace(\"\\'\", \"\\'\\'\"));\n sql.append(\"'\");\n executeOrPrint(sql, db, script);\n sql = new Sql();\n }\n\n for (Column c : table.columns) {\n if (c.comment != null) {\n sql.append(\"comment on column \");\n sql.append(table.name);\n sql.append(\".\");\n sql.append(c.name);\n sql.append(\" is \\n'\");\n sql.append(c.comment.replace(\"\\'\", \"\\'\\'\"));\n sql.append(\"'\");\n executeOrPrint(sql, db, script);\n sql = new Sql();\n }\n }\n }\n }\n\n for (Table table : tables) {\n for (ForeignKey fk : table.foreignKeys) {\n Sql sql = new Sql();\n sql.append(\"alter table \");\n sql.append(table.name);\n sql.append(\" add constraint \");\n sql.append(fk.name);\n sql.listStart(\"\\n foreign key (\");\n for (String name : fk.columnNames) {\n sql.listSeparator(\", \");\n sql.append(name);\n }\n sql.listEnd(\") references \");\n sql.append(fk.foreignTable);\n if (fk.onDeleteCascade) {\n sql.append(\" on delete cascade\");\n }\n executeOrPrint(sql, db, script);\n }\n }\n\n for (Table table : tables) {\n for (Index index : table.indexes) {\n Sql sql = new Sql();\n sql.append(\"create \");\n if (index.unique) {\n sql.append(\"unique \");\n }\n sql.append(\"index \");\n sql.append(index.name);\n sql.append(\" on \");\n sql.append(table.name);\n sql.listStart(\" (\");\n for (String name : index.columnNames) {\n sql.listSeparator(\", \");\n sql.append(name);\n }\n sql.listEnd(\")\");\n executeOrPrint(sql, db, script);\n }\n }\n\n for (Sequence sequence : sequences) {\n Sql sql = new Sql();\n sql.append(\"create sequence \");\n sql.append(sequence.name);\n sql.append(flavor.sequenceOptions());\n sql.append(\" minvalue \");\n sql.append(sequence.min);\n sql.append(\" maxvalue \");\n sql.append(sequence.max);\n sql.append(\" start with \");\n sql.append(sequence.start);\n sql.append(\" increment by \");\n sql.append(sequence.increment);\n sql.append(flavor.sequenceCacheClause(sequence.cache));\n sql.append(flavor.sequenceOrderClause(sequence.order));\n sql.append(flavor.sequenceCycleClause(sequence.cycle));\n executeOrPrint(sql, db, script);\n }\n\n if (db == null) {\n return script.toString();\n }\n return null;\n }\n\n private void executeOrPrint(Sql sql, Database db, StringBuilder script) {\n if (db != null) {\n db.ddl(sql.toString()).execute();\n } else {\n script.append(sql.toString());\n script.append(\";\\n\\n\");\n }\n }\n\n private String toName(String name) {\n name = name.toLowerCase().trim();\n\n if (!name.matches(\"[a-z][a-z0-9_]{0,28}[a-z0-9]?\")) {\n throw new IllegalArgumentException(\"Identifier name should match pattern [a-z][a-z0-9_]{0,28}[a-z0-9]?\");\n }\n\n return name;\n }\n\n private String rpad(String s, int size) {\n if (s.length() < size) {\n s += \" \".substring(0, size - s.length());\n }\n return s;\n }\n}" ]
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.susom.database.Config; import com.github.susom.database.ConfigFrom; import com.github.susom.database.DatabaseProviderVertx; import com.github.susom.database.DatabaseProviderVertx.Builder; import com.github.susom.database.Metric; import com.github.susom.database.Schema; import io.vertx.core.Vertx; import io.vertx.core.json.JsonObject;
package com.github.susom.database.example; /** * Demo of using some com.github.susom.database classes with Vertx and HyperSQL. */ public class VertxServer { private static final Logger log = LoggerFactory.getLogger(VertxServer.class); private final Object lock = new Object(); public void run() throws Exception { // A JSON config you might get from Vertx. In a real scenario you would // also set database.user, database.password and database.pool.size. JsonObject jsonConfig = new JsonObject() .put("database.url", "jdbc:hsqldb:file:target/hsqldb;shutdown=true"); // Set up Vertx and database access Vertx vertx = Vertx.vertx();
Config config = ConfigFrom.firstOf().custom(jsonConfig::getString).get();
0
WSDOT/social-analytics
src/main/java/gov/wa/wsdot/apps/analytics/client/activities/twitter/view/ranking/RankingView.java
[ "public interface ClientFactory {\n EventBus getEventBus();\n PlaceController getPlaceController();\n AnalyticsView getAnalyticsView();\n}", "public class DateSubmitEvent extends GenericEvent {\n\n\n private final String dateRange;\n private final String account;\n private final Date startDate;\n private final Date endDate;\n\n public DateSubmitEvent(String dateRange, Date startDate, Date endDate, String account) {\n this.dateRange = dateRange;\n this.account = account;\n this.startDate = startDate;\n this.endDate = endDate;\n }\n\n public String getDateRange() {\n return this.dateRange;\n }\n\n public String getAccount() {\n return this.account;\n }\n\n public Date getStartDate(){ return this.startDate;}\n\n public Date getEndDate(){ return this.endDate;}\n}", "public interface Resources extends ClientBundle {\n\tpublic static final Resources INSTANCE = GWT.create(Resources.class);\n\t\n @Source(\"GlobalStyles.css\")\n public Styles css();\n\n @Source(\"WSDOTacronymWhite.png\")\n ImageResource tacronymWhiteLogoPNG();\n\n public interface Styles extends CssResource {\n // CSS classes\n\n String loader();\n\n String logo();\n\n // Graph\n String graphBlock();\n String overflowHidden();\n }\n}", "public class Mention extends JavaScriptObject {\n\tprotected Mention() {}\n\t\n\tpublic final native String getText() /*-{ return this.text }-*/;\n\tpublic final native String getProfileImageUrl() /*-{ return this.profile_image_url }-*/;\n\tpublic final native String getToUserIdStr() /*-{ return this.to_user_id_str }-*/;\n\tpublic final native String getFromUser() /*-{ return this.from_user }-*/;\n\tpublic final native int getFromUserId() /*-{ return this.from_user_id }-*/;\n\tpublic final native int getToUserId() /*-{ return this.to_user_id }-*/;\n\tpublic final native String getGeo() /*-{ return this.geo }-*/;\n\tpublic final native double getId() /*-{ return this.id }-*/;\n\tpublic final native String getIsoLanguageCode() /*-{ return this.iso_language_code }-*/;\n\tpublic final native String getFromUserIdStr() /*-{ return this.from_user_id_str }-*/;\n\tpublic final native String getSource() /*-{ return this.source }-*/;\n\tpublic final native String getIdStr() /*-{ return this.id_str }-*/;\n\tpublic final native String getCreatedAt() /*-{ return this.created_at }-*/;\n\tpublic final native String getSentiment() /*-{ return this.sentiment }-*/;\n\tpublic final native Entities getEntities() /*-{ return this.entities }-*/;\n\tpublic final native JsArray<Mention> getMentions() /*-{ return this }-*/;\n\tpublic final native User getUser() /*-{ return this.user }-*/;\n\tpublic final native int getRetweet() /*-{ return this.retweet_count }-*/;\n\tpublic final native int getFavorited() /*-{ return this.favorite_count }-*/;\n}", "public final class Consts {\n\n public static final String HOST_URL = \"http://127.0.0.1:3001\";\n\n public static final String DEFAULT_ACCOUNT = \"wsdot\";\n\n /**\n * The caller references the constants using <tt>Consts.EMPTY_STRING</tt>,\n * and so on. Thus, the caller should be prevented from constructing objects of\n * this class, by declaring this private constructor.\n */\n private Consts() {\n //this prevents even the native class from\n //calling this ctor as well :\n throw new AssertionError();\n }\n\n}" ]
import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JsArray; import com.google.gwt.dom.client.Style; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.i18n.client.DateTimeFormat; import com.google.gwt.jsonp.client.JsonpRequestBuilder; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Widget; import com.google.web.bindery.event.shared.binder.EventBinder; import com.google.web.bindery.event.shared.binder.EventHandler; import gov.wa.wsdot.apps.analytics.client.ClientFactory; import gov.wa.wsdot.apps.analytics.client.activities.events.DateSubmitEvent; import gov.wa.wsdot.apps.analytics.client.resources.Resources; import gov.wa.wsdot.apps.analytics.shared.Mention; import gov.wa.wsdot.apps.analytics.util.Consts; import gwt.material.design.client.constants.IconType; import gwt.material.design.client.ui.*; import java.util.Date;
/* * Copyright (c) 2016 Washington State Department of Transportation * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package gov.wa.wsdot.apps.analytics.client.activities.twitter.view.ranking; /** * Custom widget for displaying top 5 tweets for most/least likes and most/least retweets. * * Listens for DateSubmitEvents */ public class RankingView extends Composite{ interface MyEventBinder extends EventBinder<RankingView> {} private final MyEventBinder eventBinder = GWT.create(MyEventBinder.class); private static TweetsViewUiBinder uiBinder = GWT .create(TweetsViewUiBinder.class); interface TweetsViewUiBinder extends UiBinder<Widget, RankingView> { } @UiField static MaterialPreLoader loader; @UiField static MaterialCollection mostRetweet; @UiField static MaterialCollection mostLiked; @UiField static MaterialCollection leastRetweet; @UiField static MaterialCollection leastLiked; @UiField static MaterialLink retweetTab; @UiField static MaterialLink likeTab; final Resources res;
public RankingView(ClientFactory clientFactory) {
0
Petschko/Java-RPG-Maker-MV-Decrypter
src/main/java/org/petschko/rpgmakermv/decrypt/gui/Update.java
[ "public class Const {\n\tpublic static final String CREATOR = \"Petschko\";\n\tpublic static final String CREATOR_URL = \"https://petschko.org/\";\n\tpublic static final String CREATOR_DONATION_URL = \"https://www.paypal.me/petschko\";\n\n\t// System Constance's\n\tpublic static final String DS = System.getProperty(\"file.separator\");\n\tpublic static final String NEW_LINE = System.getProperty(\"line.separator\");\n\n\t/**\n\t * Constructor\n\t */\n\tprivate Const() {\n\t\t// VOID - This is a Static-Class\n\t}\n}", "public class JOptionPane extends javax.swing.JOptionPane {\n\t/**\n\t * Popups a yes/no question popup\n\t *\n\t * @param msg Message to display\n\t * @param title Title of the Popup Window\n\t * @param type Message type (Error, Warning etc)\n\t * @param defaultYes true/false true means that \"yes\" is preselected\n\t * @return JOptionPane dialog result\n\t */\n\tpublic static int yesNoPopupQuestion(String msg, String title, int type, boolean defaultYes) {\n\t\tString def;\n\t\tif(defaultYes)\n\t\t\tdef = \"Yes\";\n\t\telse\n\t\t\tdef = \"No\";\n\n\t\treturn JOptionPane.showOptionDialog(null, msg, title, JOptionPane.YES_NO_OPTION, type, null, new String[] {\"Yes\", \"No\"}, def);\n\t}\n}", "public class ErrorWindow extends NotificationWindow {\n\t/**\n\t * NotificationWindow Constructor\n\t *\n\t * @param message - Message for this Notification\n\t * @param errorLevel - Error-Level of this Notification\n\t * @param stopProgram - Stop Program when Displaying this\n\t */\n\tpublic ErrorWindow(String message, int errorLevel, boolean stopProgram) {\n\t\tsuper(message, null, errorLevel, stopProgram);\n\t}\n\n\t/**\n\t * NotificationWindow Constructor\n\t *\n\t * @param message - Message for this Notification\n\t * @param errorLevel - Error-Level of this Notification\n\t * @param stopProgram - Stop Program when Displaying this\n\t * @param e - Exception of this Notification\n\t */\n\tpublic ErrorWindow(String message, int errorLevel, boolean stopProgram, Exception e) {\n\t\tsuper(message, null, errorLevel, stopProgram, e);\n\t}\n\n\t/**\n\t * NotificationWindow Constructor\n\t *\n\t * @param message - Message for this Notification\n\t * @param title - Title for this Notification\n\t * @param errorLevel - Error-Level of this Notification\n\t * @param stopProgram - Stop Program when Displaying this\n\t * @param e - Exception of this Notification\n\t */\n\tpublic ErrorWindow(String message, String title, int errorLevel, boolean stopProgram, Exception e) {\n\t\tsuper(message, title, errorLevel, stopProgram, e);\n\t}\n}", "public class InfoWindow extends NotificationWindow {\n\t/**\n\t * NotificationWindow Constructor\n\t *\n\t * @param message - Message for this Notification\n\t */\n\tpublic InfoWindow(String message) {\n\t\tsuper(message, null);\n\t}\n\n\t/**\n\t * NotificationWindow Constructor\n\t *\n\t * @param message - Message for this Notification\n\t * @param title - Title for this Notification\n\t */\n\tpublic InfoWindow(String message, String title) {\n\t\tsuper(message, title);\n\t}\n}", "public class UpdateException extends Exception {\n\tprivate Version currentVersion;\n\tprivate Version newestVersion = null;\n\n\t/**\n\t * Constructs a new exception with {@code null} as its detail message.\n\t * The cause is not initialized, and may subsequently be initialized by a\n\t * call to {@link #initCause}.\n\t *\n\t * @param currentVersion - Current Version\n\t */\n\tpublic UpdateException(Version currentVersion) {\n\t\tsuper();\n\t\tthis.setCurrentVersion(currentVersion);\n\t}\n\n\t/**\n\t * Constructs a new exception with {@code null} as its detail message.\n\t * The cause is not initialized, and may subsequently be initialized by a\n\t * call to {@link #initCause}.\n\t *\n\t * @param currentVersion - Current Version\n\t * @param newestVersion - Newest Version or null for none\n\t */\n\tpublic UpdateException(Version currentVersion, Version newestVersion) {\n\t\tsuper();\n\t\tthis.setCurrentVersion(currentVersion);\n\t\tthis.setNewestVersion(newestVersion);\n\t}\n\n\t/**\n\t * Constructs a new exception with the specified detail message. The\n\t * cause is not initialized, and may subsequently be initialized by\n\t * a call to {@link #initCause}.\n\t *\n\t * @param message the detail message. The detail message is saved for\n\t * later retrieval by the {@link #getMessage()} method.\n\t * @param currentVersion - Current Version\n\t */\n\tpublic UpdateException(String message, Version currentVersion) {\n\t\tsuper(message);\n\t\tthis.setCurrentVersion(currentVersion);\n\t}\n\n\t/**\n\t * Constructs a new exception with the specified detail message. The\n\t * cause is not initialized, and may subsequently be initialized by\n\t * a call to {@link #initCause}.\n\t *\n\t * @param message the detail message. The detail message is saved for\n\t * later retrieval by the {@link #getMessage()} method.\n\t * @param currentVersion - Current Version\n\t * @param newestVersion - Newest Version or null for none\n\t */\n\tpublic UpdateException(String message, Version currentVersion, Version newestVersion) {\n\t\tsuper(message);\n\t\tthis.setCurrentVersion(currentVersion);\n\t\tthis.setNewestVersion(newestVersion);\n\t}\n\n\t/**\n\t * Constructs a new exception with the specified detail message and\n\t * cause. <p>Note that the detail message associated with\n\t * {@code cause} is <i>not</i> automatically incorporated in\n\t * this exception's detail message.\n\t *\n\t * @param message the detail message (which is saved for later retrieval\n\t * by the {@link #getMessage()} method).\n\t * @param currentVersion - Current Version\n\t * @param cause the cause (which is saved for later retrieval by the\n\t * {@link #getCause()} method). (A <tt>null</tt> value is\n\t * permitted, and indicates that the cause is nonexistent or\n\t * unknown.)\n\t */\n\tpublic UpdateException(String message, Version currentVersion, Throwable cause) {\n\t\tsuper(message, cause);\n\t\tthis.setCurrentVersion(currentVersion);\n\t}\n\n\t/**\n\t * Constructs a new exception with the specified detail message and\n\t * cause. <p>Note that the detail message associated with\n\t * {@code cause} is <i>not</i> automatically incorporated in\n\t * this exception's detail message.\n\t *\n\t * @param message the detail message (which is saved for later retrieval\n\t * by the {@link #getMessage()} method).\n\t * @param currentVersion - Current Version\n\t * @param newestVersion - Newest Version or null for none\n\t * @param cause the cause (which is saved for later retrieval by the\n\t * {@link #getCause()} method). (A <tt>null</tt> value is\n\t * permitted, and indicates that the cause is nonexistent or\n\t * unknown.)\n\t */\n\tpublic UpdateException(String message, Version currentVersion, Version newestVersion, Throwable cause) {\n\t\tsuper(message, cause);\n\t\tthis.setCurrentVersion(currentVersion);\n\t\tthis.setNewestVersion(newestVersion);\n\t}\n\n\t/**\n\t * Constructs a new exception with the specified cause and a detail\n\t * message of <tt>(cause==null ? null : cause.toString())</tt> (which\n\t * typically contains the class and detail message of <tt>cause</tt>).\n\t * This constructor is useful for exceptions that are little more than\n\t * wrappers for other throwables (for example, {@link\n\t * PrivilegedActionException}).\n\t *\n\t * @param currentVersion - Current Version\n\t * @param cause the cause (which is saved for later retrieval by the\n\t * {@link #getCause()} method). (A <tt>null</tt> value is\n\t * permitted, and indicates that the cause is nonexistent or\n\t * unknown.)\n\t */\n\tpublic UpdateException(Version currentVersion, Throwable cause) {\n\t\tsuper(cause);\n\t\tthis.setCurrentVersion(currentVersion);\n\t}\n\n\t/**\n\t * Constructs a new exception with the specified cause and a detail\n\t * message of <tt>(cause==null ? null : cause.toString())</tt> (which\n\t * typically contains the class and detail message of <tt>cause</tt>).\n\t * This constructor is useful for exceptions that are little more than\n\t * wrappers for other throwables (for example, {@link\n\t * PrivilegedActionException}).\n\t *\n\t * @param currentVersion - Current Version\n\t * @param newestVersion - Newest Version or null for none\n\t * @param cause the cause (which is saved for later retrieval by the\n\t * {@link #getCause()} method). (A <tt>null</tt> value is\n\t * permitted, and indicates that the cause is nonexistent or\n\t * unknown.)\n\t */\n\tpublic UpdateException(Version currentVersion, Version newestVersion, Throwable cause) {\n\t\tsuper(cause);\n\t\tthis.setCurrentVersion(currentVersion);\n\t\tthis.setNewestVersion(newestVersion);\n\t}\n\n\t/**\n\t * Constructs a new exception with the specified detail message,\n\t * cause, suppression enabled or disabled, and writable stack\n\t * trace enabled or disabled.\n\t *\n\t * @param message the detail message.\n\t * @param currentVersion - Current Version\n\t * @param cause the cause. (A {@code null} value is permitted,\n\t * and indicates that the cause is nonexistent or unknown.)\n\t * @param enableSuppression whether or not suppression is enabled\n\t * or disabled\n\t * @param writableStackTrace whether or not the stack trace should\n\t * be writable\n\t */\n\tprotected UpdateException(String message, Version currentVersion, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {\n\t\tsuper(message, cause, enableSuppression, writableStackTrace);\n\t\tthis.setCurrentVersion(currentVersion);\n\t}\n\n\t/**\n\t * Constructs a new exception with the specified detail message,\n\t * cause, suppression enabled or disabled, and writable stack\n\t * trace enabled or disabled.\n\t *\n\t * @param message the detail message.\n\t * @param currentVersion - Current Version\n\t * @param newestVersion - Newest Version or null for none\n\t * @param cause the cause. (A {@code null} value is permitted,\n\t * and indicates that the cause is nonexistent or unknown.)\n\t * @param enableSuppression whether or not suppression is enabled\n\t * or disabled\n\t * @param writableStackTrace whether or not the stack trace should\n\t * be writable\n\t */\n\tprotected UpdateException(String message, Version currentVersion, Version newestVersion, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {\n\t\tsuper(message, cause, enableSuppression, writableStackTrace);\n\t\tthis.setCurrentVersion(currentVersion);\n\t\tthis.setNewestVersion(newestVersion);\n\t}\n\n\t/**\n\t * Get the current Version\n\t *\n\t * @return - Current Version\n\t */\n\tpublic Version getCurrentVersion() {\n\t\treturn currentVersion;\n\t}\n\n\t/**\n\t * Get the current Version as String\n\t *\n\t * @return - Current Version as String\n\t */\n\tpublic String getCurrentVersionAsString() {\n\t\treturn currentVersion.getVersion();\n\t}\n\n\t/**\n\t * Set the current Version\n\t *\n\t * @param currentVersion - Current Version\n\t */\n\tprivate void setCurrentVersion(Version currentVersion) {\n\t\tthis.currentVersion = currentVersion;\n\t}\n\n\t/**\n\t * Get the newest Version\n\t *\n\t * @return - Newest Version or null\n\t */\n\tpublic Version getNewestVersion() {\n\t\treturn newestVersion;\n\t}\n\n\t/**\n\t * Get the newest Version as String\n\t *\n\t * @return - Newest Version as String\n\t */\n\tpublic String getNewestVersionAsString() {\n\t\tif(this.newestVersion == null)\n\t\t\treturn \"\";\n\n\t\treturn newestVersion.getVersion();\n\t}\n\n\t/**\n\t * Set the newest Version\n\t *\n\t * @param newestVersion - Newest Version or null\n\t */\n\tprivate void setNewestVersion(Version newestVersion) {\n\t\tthis.newestVersion = newestVersion;\n\t}\n}", "public class App {\n\tprivate static Boolean useGUI = true;\n\tprivate static GUI gui;\n\tprivate static CMD cmd;\n\tpublic static String outputDir;\n\tpublic static Preferences preferences;\n\n\t/**\n\t * Main-Class\n\t *\n\t * @param args - Optional Arguments from Command-Line\n\t */\n\tpublic static void main(String[] args) {\n\t\t// Ensure System output dir always exists\n\t\tif(! File.existsDir(Config.DEFAULT_OUTPUT_DIR))\n\t\t\tFile.createDirectory(Config.DEFAULT_OUTPUT_DIR);\n\n\t\t// Check whats given from CMD\n\t\tif(args.length > 0) {\n\t\t\tuseGUI = false;\n\t\t\tcmd = new CMD(args);\n\t\t}\n\n\t\tif(useGUI) {\n\t\t\t// Show something when its started via .bat or shell file\n\t\t\tSystem.out.println(Config.PROGRAM_NAME + \" - \" + Config.VERSION + \" by \" + Const.CREATOR);\n\n\t\t\t// Use GUI\n\t\t\tpreferences = new Preferences(Config.PREFERENCES_FILE);\n\t\t\toutputDir = App.preferences.getConfig(Preferences.LAST_OUTPUT_DIR, Config.DEFAULT_OUTPUT_DIR);\n\t\t\tgui = new GUI();\n\t\t} else {\n\t\t\t// Use Command-Line Version\n\t\t\tcmd.runCMD();\n\t\t}\n\t}\n\n\t/**\n\t * Shows the given message if no GUI is enabled\n\t *\n\t * @param msg - Message to display\n\t * @param messageStatus - Status of the Message\n\t */\n\tpublic static void showMessage(String msg, int messageStatus) {\n\t\tString status;\n\n\t\tswitch(messageStatus) {\n\t\t\tcase CMD.STATUS_ERROR:\n\t\t\t\tstatus = \"[ERROR]: \";\n\t\t\t\tbreak;\n\t\t\tcase CMD.STATUS_WARNING:\n\t\t\t\tstatus = \"[WARN]: \";\n\t\t\t\tbreak;\n\t\t\tcase CMD.STATUS_OK:\n\t\t\t\tstatus = \"[SUCCESS]: \";\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tstatus = \"[INFO]: \";\n\t\t}\n\n\t\tif(! App.useGUI)\n\t\t\tSystem.out.println(status + msg);\n\t}\n\n\t/**\n\t * Shows the given message if no GUI is enabled\n\t *\n\t * @param msg - Message to display\n\t */\n\tpublic static void showMessage(String msg) {\n\t\tshowMessage(msg, CMD.STATUS_INFO);\n\t}\n\n\t/**\n\t * Saves the settings, close the GUI and quit the Program\n\t */\n\tpublic static void closeGUI() {\n\t\tif(! App.preferences.save()) {\n\t\t\tErrorWindow errorWindow = new ErrorWindow(\"Can't save Settings...\", ErrorWindow.ERROR_LEVEL_ERROR, false);\n\t\t\terrorWindow.show();\n\t\t}\n\n\t\tApp.gui.dispose();\n\t\tSystem.exit(0);\n\t}\n}", "public class Config {\n\t// Program Info\n\tpublic static final String VERSION_NUMBER = \"0.4.1\";\n\tpublic static final String VERSION = \"v\" + VERSION_NUMBER + \" Alpha\";\n\tpublic static final String PROGRAM_NAME = \"RPG-Maker MV/MZ Decrypter\";\n\tpublic static final String PROJECT_PAGE_URL = \"https://github.com/Petschko/Java-RPG-Maker-MV-Decrypter\";\n\tpublic static final String PROJECT_BUG_REPORT_URL = \"https://github.com/Petschko/Java-RPG-Maker-MV-Decrypter/issues\";\n\tpublic static final String PROJECT_LICENCE_URL = \"https://github.com/Petschko/Java-RPG-Maker-MV-Decrypter/blob/master/LICENCE\";\n\tpublic static final String AUTHOR_IMAGE = \"/icons/petschko_icon.png\";\n\tpublic static final String UPDATE_URL = \"https://raw.githubusercontent.com/Petschko/Java-RPG-Maker-MV-Decrypter/master/version.txt\";\n\n\t// File-Path-Settings\n\tpublic static final String DEFAULT_OUTPUT_DIR = \"output\";\n\tpublic static final String PREFERENCES_FILE = \"config.pref\";\n\n\t// Misc Settings\n\tpublic static final long UPDATE_CHECK_EVERY_SECS = 172800;\n\tpublic static final String THIS_JAR_FILE_NAME = \"RPG Maker MV Decrypter.jar\";\n\n\t/**\n\t * Constructor\n\t */\n\tprivate Config() {\n\t\t// VOID - This is a Static-Class\n\t}\n}", "public class Preferences extends UserPref {\n\tpublic static final String IGNORE_FAKE_HEADER = \"ignoreFakeHeader\";\n\tpublic static final String LOAD_INVALID_RPG_DIRS = \"loadInvalidRPGDirs\";\n\tpublic static final String OVERWRITE_FILES = \"overwriteFiles\";\n\tpublic static final String CLEAR_OUTPUT_DIR_BEFORE_DECRYPT = \"clearOutputDirBeforeDecrypt\";\n\tpublic static final String LAST_OUTPUT_DIR = \"lastOutputDir\";\n\tpublic static final String LAST_OUTPUT_PARENT_DIR = \"lastOutputParentDir\";\n\tpublic static final String LAST_RPG_DIR = \"lastRPGParentDir\";\n\tpublic static final String DECRYPTER_VERSION = \"decrypterVersion\";\n\tpublic static final String DECRYPTER_REMAIN = \"decrypterRemain\";\n\tpublic static final String DECRYPTER_SIGNATURE = \"decrypterSignature\";\n\tpublic static final String DECRYPTER_HEADER_LEN = \"decrypterHeaderLen\";\n\tpublic static final String AUTO_CHECK_FOR_UPDATES = \"autoCheckForUpdates\";\n\n\t/**\n\t * UserPrefs Constructor\n\t *\n\t * @param filePath - File-Path to UserPref-File\n\t */\n\tpublic Preferences(String filePath) {\n\t\tsuper(filePath);\n\t}\n\n\t/**\n\t * Load the default-values for Preferences\n\t *\n\t * @return - true on success else false\n\t */\n\t@Override\n\tpublic boolean loadDefaults() {\n\t\tProperties p = new Properties();\n\n\t\tp.setProperty(Preferences.IGNORE_FAKE_HEADER, \"true\");\n\t\tp.setProperty(Preferences.OVERWRITE_FILES, \"false\");\n\t\tp.setProperty(Preferences.LOAD_INVALID_RPG_DIRS, \"false\");\n\t\tp.setProperty(Preferences.CLEAR_OUTPUT_DIR_BEFORE_DECRYPT, \"false\");\n\t\tp.setProperty(Preferences.LAST_OUTPUT_DIR, Config.DEFAULT_OUTPUT_DIR);\n\t\tp.setProperty(Preferences.LAST_OUTPUT_PARENT_DIR, \".\");\n\t\tp.setProperty(Preferences.LAST_RPG_DIR, \".\");\n\t\tp.setProperty(Preferences.DECRYPTER_VERSION, Decrypter.DEFAULT_VERSION);\n\t\tp.setProperty(Preferences.DECRYPTER_REMAIN, Decrypter.DEFAULT_REMAIN);\n\t\tp.setProperty(Preferences.DECRYPTER_SIGNATURE, Decrypter.DEFAULT_SIGNATURE);\n\t\tp.setProperty(Preferences.DECRYPTER_HEADER_LEN, Integer.toString(Decrypter.DEFAULT_HEADER_LEN));\n\t\tp.setProperty(Preferences.AUTO_CHECK_FOR_UPDATES, \"true\");\n\n\t\tthis.setProperties(p);\n\n\t\treturn true;\n\t}\n}" ]
import org.petschko.lib.Const; import org.petschko.lib.gui.JOptionPane; import org.petschko.lib.gui.notification.ErrorWindow; import org.petschko.lib.gui.notification.InfoWindow; import org.petschko.lib.update.UpdateException; import org.petschko.rpgmakermv.decrypt.App; import org.petschko.rpgmakermv.decrypt.Config; import org.petschko.rpgmakermv.decrypt.Preferences; import java.awt.*; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException;
package org.petschko.rpgmakermv.decrypt.gui; /** * @author Peter Dragicevic */ class Update { private GUI gui; private org.petschko.lib.update.Update update = null; private String[] options; private boolean autoOptionExists = false; private boolean ranAutomatically = false; /** * Update constructor * * @param gui - Main GUI-Object */ Update(GUI gui) { this.gui = gui; this.options = new String[] {"Update", "Show whats new", "Cancel"}; this.init(); } /** * Update constructor * * @param gui - Main GUI-Object * @param auto - This ran automatically */ Update(GUI gui, boolean auto) { this.gui = gui; this.options = new String[] {"Update", "Show whats new", "Disable update check", "Cancel"}; this.autoOptionExists = true; this.ranAutomatically = auto; this.init(); } /** * Inits the Object */ private void init() { try { if(this.ranAutomatically) update = new org.petschko.lib.update.Update(Config.UPDATE_URL, Config.VERSION_NUMBER, Config.UPDATE_CHECK_EVERY_SECS); else update = new org.petschko.lib.update.Update(Config.UPDATE_URL, Config.VERSION_NUMBER, true); } catch (IOException e) { if(! this.ranAutomatically) {
ErrorWindow ew = new ErrorWindow("Can't check for Updates...", ErrorWindow.ERROR_LEVEL_WARNING, false);
2
meridor/stecker
stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/DefaultDependencyChecker.java
[ "public class PluginException extends Exception {\n\n private Optional<DependencyProblem> dependencyProblem = Optional.empty();\n\n private Optional<PluginMetadata> pluginMetadata = Optional.empty();\n\n public PluginException(Exception e) {\n super(e);\n }\n\n public PluginException(String message) {\n super(message);\n }\n\n public PluginException(String message, Exception e) {\n super(message, e);\n }\n\n public PluginException withDependencyProblem(DependencyProblem dependencyProblem) {\n this.dependencyProblem = Optional.ofNullable(dependencyProblem);\n return this;\n }\n\n public PluginException withPlugin(PluginMetadata pluginMetadata) {\n this.pluginMetadata = Optional.ofNullable(pluginMetadata);\n return this;\n }\n\n /**\n * Returns dependency problem if any\n *\n * @return dependency problem\n */\n public Optional<DependencyProblem> getDependencyProblem() {\n return dependencyProblem;\n }\n\n /**\n * Returns plugin affected\n *\n * @return plugin metadata\n */\n public Optional<PluginMetadata> getPluginMetadata() {\n return pluginMetadata;\n }\n\n}", "public interface PluginMetadata {\n\n /**\n * Returns unique plugin name\n *\n * @return free-form string with name\n */\n String getName();\n\n /**\n * Returns plugin version\n *\n * @return free-form string with version\n */\n String getVersion();\n\n /**\n * Returns {@link Path} object corresponding to plugin file\n *\n * @return plugin {@link Path} object\n */\n Path getPath();\n\n /**\n * Returns {@link org.meridor.stecker.interfaces.Dependency} object corresponding to this plugin\n *\n * @return dependency object\n */\n Dependency getDependency();\n\n /**\n * Returns date when plugin was released\n *\n * @return local date or empty if not set\n */\n Optional<ZonedDateTime> getDate();\n\n /**\n * Returns detailed plugin description\n *\n * @return description or empty if not set\n */\n Optional<String> getDescription();\n\n /**\n * Returns maintainer email and name\n *\n * @return email and name in the format: <b>John Smith &lt;john.smith@example.com&gt;</b> or empty if not set\n */\n Optional<String> getMaintainer();\n\n /**\n * Returns a list of plugins required to make this plugin work\n *\n * @return possibly empty list with dependencies\n */\n List<Dependency> getRequiredDependencies();\n\n /**\n * Returns a list of plugins that should be never installed simultaneously with this plugin\n *\n * @return possibly empty list with conflicting dependencies\n */\n List<Dependency> getConflictingDependencies();\n\n /**\n * Returns a meta dependency which is provided by this plugin\n *\n * @return meta dependency or empty if not set\n */\n Optional<Dependency> getProvidedDependency();\n\n}", "public enum VersionRelation {\n\n GREATER_THAN,\n LESS_THAN,\n EQUAL,\n NOT_EQUAL,\n IN_RANGE,\n NOT_IN_RANGE\n\n}", "public interface Dependency {\n\n /**\n * Returns dependency name\n *\n * @return dependency name\n */\n String getName();\n\n /**\n * Returns dependency version if present\n *\n * @return dependency version if present and empty otherwise\n */\n Optional<String> getVersion();\n\n /**\n * Forces to override {@link Object#equals(Object)}\n *\n * @param anotherDependency dependency to compare to\n * @return true if equal and false otherwise\n */\n boolean equals(Object anotherDependency);\n\n /**\n * Forces to override {@link Object#hashCode()}\n *\n * @return instance hash code\n */\n int hashCode();\n\n /**\n * Returns dependency string representation\n *\n * @return dependency string representation\n */\n String toString();\n\n}", "public interface DependencyChecker {\n\n /**\n * Checks dependencies and throws {@link org.meridor.stecker.PluginException} with {@link DependencyProblem} in case of issues\n *\n * @param pluginRegistry plugin registry object filled with data about all plugins\n * @param pluginMetadata checked plugin metadata\n * @throws org.meridor.stecker.PluginException when dependency issues occur\n */\n void check(PluginsAware pluginRegistry, PluginMetadata pluginMetadata) throws PluginException;\n\n}", "public interface PluginsAware {\n\n /**\n * Returns information about plugin by its plugin name\n *\n * @param pluginName plugin name to process\n * @return information about plugin or empty if not present\n */\n Optional<PluginMetadata> getPlugin(String pluginName);\n\n /**\n * Returns a list of dependencies in the registry\n *\n * @return a list of dependencies\n */\n List<String> getPluginNames();\n\n}", "public interface VersionComparator {\n\n /**\n * Returns how actual version is related to required, e.g. whether it's less or greater than required or in required\n * version range. See {@link org.meridor.stecker.VersionRelation} values for details.\n *\n * @param required required version or version range or nothing\n * @param actual actual version or nothing\n * @return how actual version relates to required\n */\n VersionRelation compare(Optional<String> required, Optional<String> actual);\n\n}" ]
import org.meridor.stecker.PluginException; import org.meridor.stecker.PluginMetadata; import org.meridor.stecker.VersionRelation; import org.meridor.stecker.interfaces.Dependency; import org.meridor.stecker.interfaces.DependencyChecker; import org.meridor.stecker.interfaces.PluginsAware; import org.meridor.stecker.interfaces.VersionComparator; import java.util.ArrayList; import java.util.List; import java.util.Optional;
package org.meridor.stecker.impl; public class DefaultDependencyChecker implements DependencyChecker { @Override
public void check(PluginsAware pluginRegistry, PluginMetadata pluginMetadata) throws PluginException {
1
swookiee/com.swookiee.runtime
com.swookiee.runtime.ewok/src/main/java/com/swookiee/runtime/ewok/servlet/BundleServlet.java
[ "public class BundleRepresentation {\n\n private long id;\n private long lastModified;\n private String location;\n private int state;\n private String symbolicName;\n private String version;\n\n public BundleRepresentation() {\n }\n\n public BundleRepresentation(final long id, final long lastModified, final String location, final int state, final String symbolicName,\n final String version) {\n this.id = id;\n this.lastModified = lastModified;\n this.location = location;\n this.state = state;\n this.symbolicName = symbolicName;\n this.version = version;\n }\n\n public long getId() {\n return id;\n }\n\n public void setId(final long id) {\n this.id = id;\n }\n\n public long getLastModified() {\n return lastModified;\n }\n\n public void setLastModified(final long lastModified) {\n this.lastModified = lastModified;\n }\n\n public String getLocation() {\n return location;\n }\n\n public void setLocation(final String location) {\n this.location = location;\n }\n\n public int getState() {\n return state;\n }\n\n public void setState(final int state) {\n this.state = state;\n }\n\n public String getSymbolicName() {\n return symbolicName;\n }\n\n public void setSymbolicName(final String symbolicName) {\n this.symbolicName = symbolicName;\n }\n\n public String getVersion() {\n return version;\n }\n\n public void setVersion(final String version) {\n this.version = version;\n }\n}", "public class BundleStartlevelRepresentation {\n\n private int startLevel;\n private Boolean activationPolicyUsed;\n private Boolean persistentlyStarted;\n\n public BundleStartlevelRepresentation() {\n }\n\n public BundleStartlevelRepresentation(final int startLevel, final Boolean activationPolicyUsed, final Boolean persistentlyStarted) {\n this.startLevel = startLevel;\n this.activationPolicyUsed = activationPolicyUsed;\n this.persistentlyStarted = persistentlyStarted;\n }\n\n public int getStartLevel() {\n return startLevel;\n }\n\n public void setStartLevel(final int startLevel) {\n this.startLevel = startLevel;\n }\n\n public Boolean getActivationPolicyUsed() {\n return activationPolicyUsed;\n }\n\n public void setActivationPolicyUsed(final Boolean activationPolicyUsed) {\n this.activationPolicyUsed = activationPolicyUsed;\n }\n\n public Boolean getPersistentlyStarted() {\n return persistentlyStarted;\n }\n\n public void setPersistentlyStarted(final Boolean persistentlyStarted) {\n this.persistentlyStarted = persistentlyStarted;\n }\n\n}", "public class BundleStatusRepresentation {\n\n private int state;\n private int options;\n\n public BundleStatusRepresentation() {\n }\n\n public BundleStatusRepresentation(final int state, final int options) {\n this.state = state;\n this.options = options;\n }\n\n public int getState() {\n return state;\n }\n\n public void setState(final int state) {\n this.state = state;\n }\n\n public int getOptions() {\n return options;\n }\n\n public void setOptions(final int options) {\n this.options = options;\n }\n\n}", "public class HttpErrorException extends Exception {\n private static final long serialVersionUID = -1070141409536825661L;\n\n private final int httpErrorCode;\n private String jsonErrorMessage;\n\n public HttpErrorException(final String message, final int httpErrorCode) {\n super(message);\n this.httpErrorCode = httpErrorCode;\n }\n\n public HttpErrorException(final String message, final Throwable throwable, final int httpErrorCode) {\n super(message);\n this.httpErrorCode = httpErrorCode;\n }\n\n public HttpErrorException(final String message, final Throwable throwable, final int httpErrorCode, final String jsonErrorMessage) {\n super(message);\n this.httpErrorCode = httpErrorCode;\n this.jsonErrorMessage = jsonErrorMessage;\n }\n\n public int getHttpErrorCode() {\n return httpErrorCode;\n }\n\n public String getJsonErrorMessage() {\n return jsonErrorMessage;\n }\n\n public boolean hasJsonErrorMessage() {\n return (jsonErrorMessage != null && !jsonErrorMessage.isEmpty());\n }\n\n}", "public final class ServletUtil {\n\n public static final String APPLICATION_JSON = \"application/json\";\n private static final PathIdExtractor idExtractor = new PathIdExtractor();\n private static final ObjectMapper mapper = new ObjectMapper();\n\n private ServletUtil() {\n }\n\n public static void checkForJsonMediaType(final HttpServletRequest request) throws HttpErrorException {\n if (!APPLICATION_JSON.equals(request.getContentType())) {\n throw new HttpErrorException(\"Unsupported Media Type\", HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);\n }\n }\n\n /**\n * Since {@link HttpServletResponse#sendError(int, String)} could be overloaded from the default error pages the\n * specification suggests to use {@link HttpServletResponse#setStatus(int)} etc. instead to communicate an error\n * with an body.\n * \n * @param response\n * actual {@link HttpServletResponse}\n * @param ex\n * current HttpErrorException\n * @throws IOException\n * PrintWriter of {@link HttpServletResponse} could throw {@link IOException}\n */\n public static void errorResponse(final HttpServletResponse response, final HttpErrorException ex) throws IOException {\n response.setStatus(ex.getHttpErrorCode());\n\n if (ex.hasJsonErrorMessage()) {\n response.setContentType(APPLICATION_JSON);\n response.getWriter().println(ex.getJsonErrorMessage());\n } else {\n response.getWriter().println(ex.getMessage());\n }\n }\n\n public static <T> void jsonResponse(final HttpServletResponse response, final T toJson)\n throws IOException {\n final String jsonResponse = mapper.writeValueAsString(toJson);\n response.setContentType(APPLICATION_JSON);\n response.getWriter().println(jsonResponse);\n }\n\n public static long getId(final HttpServletRequest request) throws HttpErrorException {\n return ServletUtil.idExtractor.getId(request.getPathInfo());\n }\n\n public static Bundle checkAndGetBundle(final BundleContext bundleContext, final long bundleId) throws HttpErrorException {\n final Bundle bundle = bundleContext.getBundle(bundleId);\n\n if (bundle == null) {\n throw new HttpErrorException(String.format(\"Could not find Bundle %d\", bundleId),\n HttpServletResponse.SC_NOT_FOUND);\n }\n return bundle;\n }\n\n public static Map<String, String> transformToMapAndCleanUp(final Dictionary<String, String> source) {\n final Map<String, String> result = new HashMap<>();\n for (final Enumeration<String> keys = source.keys(); keys.hasMoreElements();) {\n final String key = keys.nextElement();\n result.put(key, source.get(key).replaceAll(\"[\\u0000-\\u001f]\", \"\"));\n }\n return result;\n }\n\n public static void addServiceProperties(final ServiceReference<?> serviceReference, final ServiceRepresenation represenation) {\n for (final String propertyKey : serviceReference.getPropertyKeys()) {\n represenation.addProperty(propertyKey, serviceReference.getProperty(propertyKey));\n }\n }\n\n public static void addUsingBundles(final ServiceReference<?> serviceReference, final ServiceRepresenation represenation) {\n final Bundle[] usingBundles = serviceReference.getUsingBundles();\n\n if (usingBundles == null) {\n return;\n }\n\n for (final Bundle usingBundle : usingBundles) {\n represenation.addUsingBundle(usingBundle.getSymbolicName());\n }\n }\n}" ]
import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Map; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; import org.osgi.framework.startlevel.BundleStartLevel; import org.osgi.framework.wiring.FrameworkWiring; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.swookiee.runtime.ewok.representation.BundleRepresentation; import com.swookiee.runtime.ewok.representation.BundleStartlevelRepresentation; import com.swookiee.runtime.ewok.representation.BundleStatusRepresentation; import com.swookiee.runtime.ewok.util.HttpErrorException; import com.swookiee.runtime.ewok.util.ServletUtil;
/******************************************************************************* * Copyright (c) 2014 Lars Pfannenschmidt and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Lars Pfannenschmidt - initial API and implementation, ongoing development and documentation *******************************************************************************/ package com.swookiee.runtime.ewok.servlet; /** * This {@link HttpServlet} implements the Bundle Resource (5.1.3), Bundle State Resource (5.1.4), Bundle Header * Resource (5.1.5) &amp; Bundle Startlevel Resource (5.1.6) of the OSGi RFC-182 draft version 8. @see <a href= * https://github.com/osgi/design/tree/master/rfcs/rfc0182> https://github.com/osgi/design/tree/master/rfcs/rfc0182</a> * */ public class BundleServlet extends HttpServlet { public static final String ALIAS = "/framework/bundle"; private static final long serialVersionUID = -8784847583201231060L; private static final Logger logger = LoggerFactory.getLogger(BundleServlet.class); private final BundleContext bundleContext; private final ObjectMapper mapper; public BundleServlet(final BundleContext bundleContext) { this.bundleContext = bundleContext; this.mapper = new ObjectMapper(); } @Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException { try { final long bundleId = ServletUtil.getId(request); final Bundle bundle = ServletUtil.checkAndGetBundle(bundleContext, bundleId); String json; if (isStartLevelRequest(request)) { json = getBundleStartlevel(bundle); } else if (isHeaderRequest(request)) { final Map<String, String> header = ServletUtil.transformToMapAndCleanUp(bundle.getHeaders()); json = mapper.writeValueAsString(header); } else if (isStateRequest(request)) {
final BundleStatusRepresentation bundleStatusRepresentation = new BundleStatusRepresentation(
2
dkzwm/SmoothRefreshLayout
app/src/main/java/me/dkzwm/widget/srl/sample/DemoApplication.java
[ "public interface IRefreshViewCreator {\n IRefreshView<IIndicator> createHeader(SmoothRefreshLayout layout);\n\n IRefreshView<IIndicator> createFooter(SmoothRefreshLayout layout);\n}", "public class SmoothRefreshLayout extends ViewGroup\n implements NestedScrollingParent3, NestedScrollingChild3 {\n // status\n public static final byte SR_STATUS_INIT = 1;\n public static final byte SR_STATUS_PREPARE = 2;\n public static final byte SR_STATUS_REFRESHING = 3;\n public static final byte SR_STATUS_LOADING_MORE = 4;\n public static final byte SR_STATUS_COMPLETE = 5;\n // fresh view status\n public static final byte SR_VIEW_STATUS_INIT = 21;\n public static final byte SR_VIEW_STATUS_HEADER_IN_PROCESSING = 22;\n public static final byte SR_VIEW_STATUS_FOOTER_IN_PROCESSING = 23;\n\n protected static final Interpolator SPRING_INTERPOLATOR =\n new Interpolator() {\n public float getInterpolation(float input) {\n --input;\n return input * input * input * input * input + 1.0F;\n }\n };\n protected static final Interpolator FLING_INTERPOLATOR = new DecelerateInterpolator(.95f);\n protected static final Interpolator SPRING_BACK_INTERPOLATOR = new DecelerateInterpolator(1.6f);\n protected static final int FLAG_AUTO_REFRESH = 0x01;\n protected static final int FLAG_ENABLE_OVER_SCROLL = 0x01 << 2;\n protected static final int FLAG_ENABLE_KEEP_REFRESH_VIEW = 0x01 << 3;\n protected static final int FLAG_ENABLE_PIN_CONTENT_VIEW = 0x01 << 4;\n protected static final int FLAG_ENABLE_PULL_TO_REFRESH = 0x01 << 5;\n protected static final int FLAG_ENABLE_PIN_REFRESH_VIEW_WHILE_LOADING = 0x01 << 6;\n protected static final int FLAG_ENABLE_HEADER_DRAWER_STYLE = 0x01 << 7;\n protected static final int FLAG_ENABLE_FOOTER_DRAWER_STYLE = 0x01 << 8;\n protected static final int FLAG_DISABLE_PERFORM_LOAD_MORE = 0x01 << 9;\n protected static final int FLAG_ENABLE_NO_MORE_DATA = 0x01 << 10;\n protected static final int FLAG_DISABLE_LOAD_MORE = 0x01 << 11;\n protected static final int FLAG_DISABLE_PERFORM_REFRESH = 0x01 << 12;\n protected static final int FLAG_DISABLE_REFRESH = 0x01 << 13;\n protected static final int FLAG_ENABLE_AUTO_PERFORM_LOAD_MORE = 0x01 << 14;\n protected static final int FLAG_ENABLE_AUTO_PERFORM_REFRESH = 0x01 << 15;\n protected static final int FLAG_ENABLE_INTERCEPT_EVENT_WHILE_LOADING = 0x01 << 16;\n protected static final int FLAG_DISABLE_WHEN_ANOTHER_DIRECTION_MOVE = 0x01 << 17;\n protected static final int FLAG_ENABLE_NO_MORE_DATA_NO_BACK = 0x01 << 18;\n protected static final int FLAG_DISABLE_LOAD_MORE_WHEN_CONTENT_NOT_FULL = 0x01 << 19;\n protected static final int FLAG_ENABLE_COMPAT_SYNC_SCROLL = 0x01 << 20;\n protected static final int FLAG_ENABLE_PERFORM_FRESH_WHEN_FLING = 0x01 << 21;\n protected static final int FLAG_ENABLE_OLD_TOUCH_HANDLING = 0x01 << 22;\n protected static final int FLAG_BEEN_SET_NO_MORE_DATA = 0x01 << 23;\n protected static final int MASK_DISABLE_PERFORM_LOAD_MORE = 0x07 << 9;\n protected static final int MASK_DISABLE_PERFORM_REFRESH = 0x03 << 12;\n public static boolean sDebug = false;\n private static int sId = 0;\n private static IRefreshViewCreator sCreator;\n protected final String TAG = \"SmoothRefreshLayout-\" + sId++;\n protected final int[] mParentScrollConsumed = new int[2];\n protected final int[] mParentOffsetInWindow = new int[2];\n private final List<View> mCachedViews = new ArrayList<>();\n protected IRefreshView<IIndicator> mHeaderView;\n protected IRefreshView<IIndicator> mFooterView;\n protected IIndicator mIndicator;\n protected IIndicatorSetter mIndicatorSetter;\n protected OnRefreshListener mRefreshListener;\n protected boolean mAutomaticActionUseSmoothScroll = false;\n protected boolean mAutomaticActionTriggered = true;\n protected boolean mIsSpringBackCanNotBeInterrupted = false;\n protected boolean mDealAnotherDirectionMove = false;\n protected boolean mPreventForAnotherDirection = false;\n protected boolean mIsInterceptTouchEventInOnceTouch = false;\n protected boolean mIsLastOverScrollCanNotAbort = false;\n protected boolean mNestedScrolling = false;\n protected boolean mNestedTouchScrolling = false;\n protected byte mStatus = SR_STATUS_INIT;\n protected byte mViewStatus = SR_VIEW_STATUS_INIT;\n protected long mLoadingStartTime = 0;\n protected int mAutomaticAction = Constants.ACTION_NOTIFY;\n protected int mLastNestedType = ViewCompat.TYPE_NON_TOUCH;\n protected int mDurationToCloseHeader = 350;\n protected int mDurationToCloseFooter = 350;\n protected int mDurationOfBackToHeaderHeight = 200;\n protected int mDurationOfBackToFooterHeight = 200;\n protected int mDurationOfFlingBack = 550;\n protected int mContentResId = View.NO_ID;\n protected int mStickyHeaderResId = View.NO_ID;\n protected int mStickyFooterResId = View.NO_ID;\n protected int mTouchSlop;\n protected int mTouchPointerId;\n protected int mMinimumFlingVelocity;\n protected int mMaximumFlingVelocity;\n protected View mTargetView;\n protected View mScrollTargetView;\n protected View mAutoFoundScrollTargetView;\n protected View mStickyHeaderView;\n protected View mStickyFooterView;\n protected LayoutManager mLayoutManager;\n protected ScrollChecker mScrollChecker;\n protected VelocityTracker mVelocityTracker;\n protected MotionEvent mLastMoveEvent;\n protected OnHeaderEdgeDetectCallBack mInEdgeCanMoveHeaderCallBack;\n protected OnFooterEdgeDetectCallBack mInEdgeCanMoveFooterCallBack;\n protected OnSyncScrollCallback mSyncScrollCallback;\n protected OnPerformAutoLoadMoreCallBack mAutoLoadMoreCallBack;\n protected OnPerformAutoRefreshCallBack mAutoRefreshCallBack;\n protected OnCalculateBounceCallback mCalculateBounceCallback;\n protected int mFlag =\n FLAG_DISABLE_LOAD_MORE\n | FLAG_ENABLE_KEEP_REFRESH_VIEW\n | FLAG_ENABLE_COMPAT_SYNC_SCROLL\n | FLAG_ENABLE_OLD_TOUCH_HANDLING\n | FLAG_ENABLE_PERFORM_FRESH_WHEN_FLING;\n private NestedScrollingParentHelper mNestedScrollingParentHelper =\n new NestedScrollingParentHelper(this);\n private NestedScrollingChildHelper mNestedScrollingChildHelper;\n private Interpolator mSpringInterpolator;\n private Interpolator mSpringBackInterpolator;\n private ArrayList<OnUIPositionChangedListener> mUIPositionChangedListeners;\n private ArrayList<OnStatusChangedListener> mStatusChangedListeners;\n private ArrayList<ILifecycleObserver> mLifecycleObservers;\n private DelayToDispatchNestedFling mDelayToDispatchNestedFling;\n private DelayToRefreshComplete mDelayToRefreshComplete;\n private DelayToPerformAutoRefresh mDelayToPerformAutoRefresh;\n private RefreshCompleteHook mHeaderRefreshCompleteHook;\n private RefreshCompleteHook mFooterRefreshCompleteHook;\n private AppBarLayoutUtil mAppBarLayoutUtil;\n private Matrix mCachedMatrix = new Matrix();\n private boolean mIsLastRefreshSuccessful = true;\n private boolean mViewsZAxisNeedReset = true;\n private boolean mNeedFilterScrollEvent = false;\n private boolean mHasSendCancelEvent = false;\n private boolean mHasSendDownEvent = false;\n private boolean mLastEventIsActionDown = false;\n private float[] mCachedFloatPoint = new float[2];\n private int[] mCachedIntPoint = new int[2];\n private float mOffsetConsumed = 0f;\n private float mOffsetTotal = 0f;\n private int mMaxOverScrollDuration = 350;\n private int mMinOverScrollDuration = 100;\n private int mOffsetRemaining = 0;\n\n public SmoothRefreshLayout(Context context) {\n super(context);\n init(context, null, 0, 0);\n }\n\n public SmoothRefreshLayout(Context context, AttributeSet attrs) {\n super(context, attrs);\n init(context, attrs, 0, 0);\n }\n\n public SmoothRefreshLayout(Context context, AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n init(context, attrs, defStyleAttr, 0);\n }\n\n /**\n * Set the static refresh view creator, if the refresh view is null and the frame be needed the\n * refresh view,frame will use this creator to create refresh view.\n *\n * <p>设置默认的刷新视图构造器,当刷新视图为null且需要使用刷新视图时,Frame会使用该构造器构造刷新视图\n *\n * @param creator The static refresh view creator\n */\n public static void setDefaultCreator(IRefreshViewCreator creator) {\n sCreator = creator;\n }\n\n @CallSuper\n protected void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {\n sId++;\n createIndicator();\n if (mIndicator == null || mIndicatorSetter == null) {\n throw new IllegalArgumentException(\n \"You must create a IIndicator, current indicator is null\");\n }\n ViewConfiguration viewConfiguration = ViewConfiguration.get(getContext());\n mTouchSlop = viewConfiguration.getScaledTouchSlop();\n mMaximumFlingVelocity = viewConfiguration.getScaledMaximumFlingVelocity();\n mMinimumFlingVelocity = viewConfiguration.getScaledMinimumFlingVelocity();\n createScrollerChecker();\n mSpringInterpolator = SPRING_INTERPOLATOR;\n mSpringBackInterpolator = SPRING_BACK_INTERPOLATOR;\n mDelayToPerformAutoRefresh = new DelayToPerformAutoRefresh();\n TypedArray arr =\n context.obtainStyledAttributes(\n attrs, R.styleable.SmoothRefreshLayout, defStyleAttr, defStyleRes);\n int mode = Constants.MODE_DEFAULT;\n if (arr != null) {\n try {\n mContentResId =\n arr.getResourceId(\n R.styleable.SmoothRefreshLayout_sr_content, mContentResId);\n float resistance =\n arr.getFloat(\n R.styleable.SmoothRefreshLayout_sr_resistance,\n IIndicator.DEFAULT_RESISTANCE);\n mIndicatorSetter.setResistance(resistance);\n mIndicatorSetter.setResistanceOfHeader(\n arr.getFloat(\n R.styleable.SmoothRefreshLayout_sr_resistanceOfHeader, resistance));\n mIndicatorSetter.setResistanceOfFooter(\n arr.getFloat(\n R.styleable.SmoothRefreshLayout_sr_resistanceOfFooter, resistance));\n mDurationOfBackToHeaderHeight =\n arr.getInt(\n R.styleable.SmoothRefreshLayout_sr_backToKeepDuration,\n mDurationOfBackToHeaderHeight);\n mDurationOfBackToFooterHeight =\n arr.getInt(\n R.styleable.SmoothRefreshLayout_sr_backToKeepDuration,\n mDurationOfBackToFooterHeight);\n mDurationOfBackToHeaderHeight =\n arr.getInt(\n R.styleable.SmoothRefreshLayout_sr_backToKeepHeaderDuration,\n mDurationOfBackToHeaderHeight);\n mDurationOfBackToFooterHeight =\n arr.getInt(\n R.styleable.SmoothRefreshLayout_sr_backToKeepFooterDuration,\n mDurationOfBackToFooterHeight);\n mDurationToCloseHeader =\n arr.getInt(\n R.styleable.SmoothRefreshLayout_sr_closeDuration,\n mDurationToCloseHeader);\n mDurationToCloseFooter =\n arr.getInt(\n R.styleable.SmoothRefreshLayout_sr_closeDuration,\n mDurationToCloseFooter);\n mDurationToCloseHeader =\n arr.getInt(\n R.styleable.SmoothRefreshLayout_sr_closeHeaderDuration,\n mDurationToCloseHeader);\n mDurationToCloseFooter =\n arr.getInt(\n R.styleable.SmoothRefreshLayout_sr_closeFooterDuration,\n mDurationToCloseFooter);\n float ratio =\n arr.getFloat(\n R.styleable.SmoothRefreshLayout_sr_ratioToRefresh,\n IIndicator.DEFAULT_RATIO_TO_REFRESH);\n mIndicatorSetter.setRatioToRefresh(ratio);\n mIndicatorSetter.setRatioOfHeaderToRefresh(\n arr.getFloat(\n R.styleable.SmoothRefreshLayout_sr_ratioOfHeaderToRefresh, ratio));\n mIndicatorSetter.setRatioOfFooterToRefresh(\n arr.getFloat(\n R.styleable.SmoothRefreshLayout_sr_ratioOfFooterToRefresh, ratio));\n ratio =\n arr.getFloat(\n R.styleable.SmoothRefreshLayout_sr_ratioToKeep,\n IIndicator.DEFAULT_RATIO_TO_REFRESH);\n mIndicatorSetter.setRatioToKeepHeader(ratio);\n mIndicatorSetter.setRatioToKeepFooter(ratio);\n mIndicatorSetter.setRatioToKeepHeader(\n arr.getFloat(R.styleable.SmoothRefreshLayout_sr_ratioToKeepHeader, ratio));\n mIndicatorSetter.setRatioToKeepFooter(\n arr.getFloat(R.styleable.SmoothRefreshLayout_sr_ratioToKeepFooter, ratio));\n ratio =\n arr.getFloat(\n R.styleable.SmoothRefreshLayout_sr_maxMoveRatio,\n IIndicator.DEFAULT_MAX_MOVE_RATIO);\n mIndicatorSetter.setMaxMoveRatio(ratio);\n mIndicatorSetter.setMaxMoveRatioOfHeader(\n arr.getFloat(\n R.styleable.SmoothRefreshLayout_sr_maxMoveRatioOfHeader, ratio));\n mIndicatorSetter.setMaxMoveRatioOfFooter(\n arr.getFloat(\n R.styleable.SmoothRefreshLayout_sr_maxMoveRatioOfFooter, ratio));\n mStickyHeaderResId =\n arr.getResourceId(R.styleable.SmoothRefreshLayout_sr_stickyHeader, NO_ID);\n mStickyFooterResId =\n arr.getResourceId(R.styleable.SmoothRefreshLayout_sr_stickyFooter, NO_ID);\n setEnableKeepRefreshView(\n arr.getBoolean(R.styleable.SmoothRefreshLayout_sr_enableKeep, true));\n setEnablePinContentView(\n arr.getBoolean(R.styleable.SmoothRefreshLayout_sr_enablePinContent, false));\n setEnableOverScroll(\n arr.getBoolean(R.styleable.SmoothRefreshLayout_sr_enableOverScroll, true));\n setEnablePullToRefresh(\n arr.getBoolean(\n R.styleable.SmoothRefreshLayout_sr_enablePullToRefresh, false));\n setDisableRefresh(\n !arr.getBoolean(R.styleable.SmoothRefreshLayout_sr_enableRefresh, true));\n setDisableLoadMore(\n !arr.getBoolean(R.styleable.SmoothRefreshLayout_sr_enableLoadMore, false));\n mode = arr.getInt(R.styleable.SmoothRefreshLayout_sr_mode, 0);\n setEnabled(arr.getBoolean(R.styleable.SmoothRefreshLayout_android_enabled, true));\n } finally {\n arr.recycle();\n }\n }\n setMode(mode);\n if (mNestedScrollingChildHelper == null) {\n setNestedScrollingEnabled(true);\n }\n }\n\n protected void createIndicator() {\n DefaultIndicator indicator = new DefaultIndicator();\n mIndicator = indicator;\n mIndicatorSetter = indicator;\n }\n\n protected void createScrollerChecker() {\n mScrollChecker = new ScrollChecker();\n }\n\n public final IIndicator getIndicator() {\n return mIndicator;\n }\n\n @Override\n @SuppressWarnings(\"unchecked\")\n @CallSuper\n public void addView(View child, int index, ViewGroup.LayoutParams params) {\n if (params == null) {\n params = generateDefaultLayoutParams();\n } else {\n params = generateLayoutParams(params);\n }\n if (child instanceof IRefreshView) {\n IRefreshView<IIndicator> view = (IRefreshView<IIndicator>) child;\n switch (view.getType()) {\n case IRefreshView.TYPE_HEADER:\n if (mHeaderView != null)\n throw new IllegalArgumentException(\n \"Unsupported operation, HeaderView only can be add once !!\");\n mHeaderView = view;\n break;\n case IRefreshView.TYPE_FOOTER:\n if (mFooterView != null)\n throw new IllegalArgumentException(\n \"Unsupported operation, FooterView only can be add once !!\");\n mFooterView = view;\n break;\n }\n }\n super.addView(child, index, params);\n }\n\n @Override\n public void setEnabled(boolean enabled) {\n super.setEnabled(enabled);\n if (!enabled) {\n reset();\n }\n }\n\n @Override\n protected void onFinishInflate() {\n super.onFinishInflate();\n checkViewsZAxisNeedReset();\n }\n\n @Override\n protected void onDetachedFromWindow() {\n final List<ILifecycleObserver> observers = mLifecycleObservers;\n if (observers != null) {\n for (ILifecycleObserver observer : observers) {\n observer.onDetached(this);\n }\n }\n if (mAppBarLayoutUtil != null) {\n if (mInEdgeCanMoveHeaderCallBack == mAppBarLayoutUtil) {\n mInEdgeCanMoveHeaderCallBack = null;\n }\n if (mInEdgeCanMoveFooterCallBack == mAppBarLayoutUtil) {\n mInEdgeCanMoveFooterCallBack = null;\n }\n mAppBarLayoutUtil.detach();\n }\n mAppBarLayoutUtil = null;\n reset();\n if (mHeaderRefreshCompleteHook != null) {\n mHeaderRefreshCompleteHook.mLayout = null;\n }\n if (mFooterRefreshCompleteHook != null) {\n mFooterRefreshCompleteHook.mLayout = null;\n }\n if (mDelayToDispatchNestedFling != null) {\n mDelayToDispatchNestedFling.mLayout = null;\n }\n if (mDelayToRefreshComplete != null) {\n mDelayToRefreshComplete.mLayout = null;\n }\n mDelayToPerformAutoRefresh.mLayout = null;\n if (mVelocityTracker != null) {\n mVelocityTracker.recycle();\n }\n mVelocityTracker = null;\n if (sDebug) {\n Log.d(TAG, \"onDetachedFromWindow()\");\n }\n super.onDetachedFromWindow();\n }\n\n @Override\n protected void onAttachedToWindow() {\n super.onAttachedToWindow();\n if (sDebug) {\n Log.d(TAG, \"onAttachedToWindow()\");\n }\n final List<ILifecycleObserver> observers = mLifecycleObservers;\n if (observers != null) {\n for (ILifecycleObserver observer : observers) {\n observer.onAttached(this);\n }\n }\n if (isVerticalOrientation()) {\n View view = ViewCatcherUtil.catchAppBarLayout(this);\n if (view != null) {\n mAppBarLayoutUtil = new AppBarLayoutUtil(view);\n if (mInEdgeCanMoveHeaderCallBack == null) {\n mInEdgeCanMoveHeaderCallBack = mAppBarLayoutUtil;\n }\n if (mInEdgeCanMoveFooterCallBack == null) {\n mInEdgeCanMoveFooterCallBack = mAppBarLayoutUtil;\n }\n }\n }\n mDelayToPerformAutoRefresh.mLayout = this;\n }\n\n @Override\n public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {\n int count = getChildCount();\n if (count == 0) {\n return;\n }\n ensureTargetView();\n int maxHeight = 0;\n int maxWidth = 0;\n int childState = 0;\n mCachedViews.clear();\n final boolean measureMatchParentChildren =\n MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY\n || MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY;\n mLayoutManager.mMeasureMatchParentChildren = measureMatchParentChildren;\n mLayoutManager.mOldWidthMeasureSpec = widthMeasureSpec;\n mLayoutManager.mOldHeightMeasureSpec = heightMeasureSpec;\n for (int i = 0; i < count; i++) {\n final View child = getChildAt(i);\n if (child.getVisibility() == GONE) {\n continue;\n }\n final LayoutParams lp = (LayoutParams) child.getLayoutParams();\n if (mHeaderView != null && child == mHeaderView.getView()) {\n mLayoutManager.measureHeader(mHeaderView, widthMeasureSpec, heightMeasureSpec);\n } else if (mFooterView != null && child == mFooterView.getView()) {\n mLayoutManager.measureFooter(mFooterView, widthMeasureSpec, heightMeasureSpec);\n } else {\n measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);\n if (measureMatchParentChildren\n && (lp.width == LayoutParams.MATCH_PARENT\n || lp.height == LayoutParams.MATCH_PARENT)) {\n mCachedViews.add(child);\n }\n }\n maxWidth =\n Math.max(maxWidth, child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);\n maxHeight =\n Math.max(maxHeight, child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);\n childState = combineMeasuredStates(childState, child.getMeasuredState());\n }\n maxWidth += getPaddingLeft() + getPaddingRight();\n maxHeight += getPaddingTop() + getPaddingBottom();\n maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());\n maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());\n setMeasuredDimension(\n resolveSizeAndState(maxWidth, widthMeasureSpec, childState),\n resolveSizeAndState(\n maxHeight, heightMeasureSpec, childState << MEASURED_HEIGHT_STATE_SHIFT));\n count = mCachedViews.size();\n if (count > 1) {\n for (int i = 0; i < count; i++) {\n final View child = mCachedViews.get(i);\n final LayoutParams lp = (LayoutParams) child.getLayoutParams();\n final int[] spec = measureChildAgain(lp, widthMeasureSpec, heightMeasureSpec);\n child.measure(spec[0], spec[1]);\n }\n }\n mCachedViews.clear();\n if (MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY\n || MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY) {\n if (mHeaderView != null && mHeaderView.getView().getVisibility() != GONE) {\n final View child = mHeaderView.getView();\n final LayoutParams lp = (LayoutParams) child.getLayoutParams();\n final int[] spec = measureChildAgain(lp, widthMeasureSpec, heightMeasureSpec);\n mLayoutManager.measureHeader(mHeaderView, spec[0], spec[1]);\n }\n if (mFooterView != null && mFooterView.getView().getVisibility() != GONE) {\n final View child = mFooterView.getView();\n final LayoutParams lp = (LayoutParams) child.getLayoutParams();\n final int[] spec = measureChildAgain(lp, widthMeasureSpec, heightMeasureSpec);\n mLayoutManager.measureFooter(mFooterView, spec[0], spec[1]);\n }\n }\n }\n\n private int[] measureChildAgain(LayoutParams lp, int widthMeasureSpec, int heightMeasureSpec) {\n if (lp.width == LayoutParams.MATCH_PARENT) {\n final int width =\n Math.max(\n 0,\n getMeasuredWidth()\n - getPaddingLeft()\n - getPaddingRight()\n - lp.leftMargin\n - lp.rightMargin);\n mCachedIntPoint[0] = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);\n } else {\n mCachedIntPoint[0] =\n getChildMeasureSpec(\n widthMeasureSpec,\n getPaddingLeft() + getPaddingRight() + lp.leftMargin + lp.rightMargin,\n lp.width);\n }\n if (lp.height == LayoutParams.MATCH_PARENT) {\n final int height =\n Math.max(\n 0,\n getMeasuredHeight()\n - getPaddingTop()\n - getPaddingBottom()\n - lp.topMargin\n - lp.bottomMargin);\n mCachedIntPoint[1] = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);\n } else {\n mCachedIntPoint[1] =\n getChildMeasureSpec(\n heightMeasureSpec,\n getPaddingTop() + getPaddingBottom() + lp.topMargin + lp.bottomMargin,\n lp.height);\n }\n return mCachedIntPoint;\n }\n\n @Override\n protected void onLayout(boolean changed, int l, int t, int r, int b) {\n final int count = getChildCount();\n if (count == 0) {\n return;\n }\n mIndicator.checkConfig();\n final int parentRight = r - l - getPaddingRight();\n final int parentBottom = b - t - getPaddingBottom();\n for (int i = 0; i < count; i++) {\n final View child = getChildAt(i);\n if (child.getVisibility() == GONE) {\n continue;\n }\n if (mHeaderView != null && child == mHeaderView.getView()) {\n mLayoutManager.layoutHeaderView(mHeaderView);\n } else if (mTargetView != null && child == mTargetView) {\n mLayoutManager.layoutContentView(child);\n } else if (mStickyHeaderView != null && child == mStickyHeaderView) {\n mLayoutManager.layoutStickyHeaderView(child);\n } else if ((mFooterView == null || mFooterView.getView() != child)\n && (mStickyFooterView == null || mStickyFooterView != child)) {\n layoutOtherView(child, parentRight, parentBottom);\n }\n }\n if (mFooterView != null && mFooterView.getView().getVisibility() != GONE) {\n mLayoutManager.layoutFooterView(mFooterView);\n }\n if (mStickyFooterView != null && mStickyFooterView.getVisibility() != GONE) {\n mLayoutManager.layoutStickyFooterView(mStickyFooterView);\n }\n if (!mAutomaticActionTriggered) {\n removeCallbacks(mDelayToPerformAutoRefresh);\n postDelayed(mDelayToPerformAutoRefresh, 90);\n }\n }\n\n protected void layoutOtherView(View child, int parentRight, int parentBottom) {\n final int width = child.getMeasuredWidth();\n final int height = child.getMeasuredHeight();\n int childLeft, childTop;\n final LayoutParams lp = (LayoutParams) child.getLayoutParams();\n final int gravity = lp.gravity;\n final int layoutDirection = ViewCompat.getLayoutDirection(this);\n final int absoluteGravity = GravityCompat.getAbsoluteGravity(gravity, layoutDirection);\n final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;\n switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {\n case Gravity.CENTER_HORIZONTAL:\n childLeft =\n (int)\n (getPaddingLeft()\n + (parentRight - getPaddingLeft() - width) / 2f\n + lp.leftMargin\n - lp.rightMargin);\n break;\n case Gravity.RIGHT:\n childLeft = parentRight - width - lp.rightMargin;\n break;\n default:\n childLeft = getPaddingLeft() + lp.leftMargin;\n }\n switch (verticalGravity) {\n case Gravity.CENTER_VERTICAL:\n childTop =\n (int)\n (getPaddingTop()\n + (parentBottom - getPaddingTop() - height) / 2f\n + lp.topMargin\n - lp.bottomMargin);\n break;\n case Gravity.BOTTOM:\n childTop = parentBottom - height - lp.bottomMargin;\n break;\n default:\n childTop = getPaddingTop() + lp.topMargin;\n }\n child.layout(childLeft, childTop, childLeft + width, childTop + height);\n if (sDebug) {\n Log.d(\n TAG,\n String.format(\n \"onLayout(): child: %d %d %d %d\",\n childLeft, childTop, childLeft + width, childTop + height));\n }\n }\n\n @Override\n protected void onDraw(Canvas canvas) {\n super.onDraw(canvas);\n mLayoutManager.onLayoutDraw(canvas);\n }\n\n @Override\n public boolean dispatchTouchEvent(MotionEvent ev) {\n mLastEventIsActionDown = ev.getActionMasked() == MotionEvent.ACTION_DOWN;\n if (!isEnabled()\n || mTargetView == null\n || ((isDisabledLoadMore() && isDisabledRefresh()))\n || (isEnabledPinRefreshViewWhileLoading()\n && ((isRefreshing() && isMovingHeader())\n || (isLoadingMore() && isMovingFooter())))\n || mNestedTouchScrolling) {\n return super.dispatchTouchEvent(ev);\n }\n return processDispatchTouchEvent(ev);\n }\n\n protected final boolean dispatchTouchEventSuper(MotionEvent ev) {\n if (!isEnabledOldTouchHandling()) {\n final int index = ev.findPointerIndex(mTouchPointerId);\n if (index < 0) {\n return super.dispatchTouchEvent(ev);\n }\n if (ev.getActionMasked() == MotionEvent.ACTION_DOWN) {\n mOffsetConsumed = 0;\n mOffsetTotal = 0;\n mOffsetRemaining = mTouchSlop * 3;\n } else {\n if (!mIndicator.isAlreadyHere(IIndicator.START_POS)\n && mIndicator.getRawOffset() != 0) {\n if (mOffsetRemaining > 0) {\n mOffsetRemaining -= mTouchSlop;\n if (isMovingHeader()) {\n mOffsetTotal -= mOffsetRemaining;\n } else if (isMovingFooter()) {\n mOffsetTotal += mOffsetRemaining;\n }\n }\n mOffsetConsumed +=\n mIndicator.getRawOffset() < 0\n ? mIndicator.getLastPos() - mIndicator.getCurrentPos()\n : mIndicator.getCurrentPos() - mIndicator.getLastPos();\n mOffsetTotal += mIndicator.getRawOffset();\n }\n if (isVerticalOrientation()) {\n ev.offsetLocation(0, mOffsetConsumed - mOffsetTotal);\n } else {\n ev.offsetLocation(mOffsetConsumed - mOffsetTotal, 0);\n }\n }\n }\n return super.dispatchTouchEvent(ev);\n }\n\n public void addLifecycleObserver(@NonNull ILifecycleObserver observer) {\n if (mLifecycleObservers == null) {\n mLifecycleObservers = new ArrayList<>();\n mLifecycleObservers.add(observer);\n } else if (!mLifecycleObservers.contains(observer)) {\n mLifecycleObservers.add(observer);\n }\n }\n\n public void removeLifecycleObserver(@NonNull ILifecycleObserver observer) {\n if (mLifecycleObservers != null) {\n mLifecycleObservers.remove(observer);\n }\n }\n\n @Nullable\n public View getScrollTargetView() {\n if (mScrollTargetView != null) {\n return mScrollTargetView;\n } else if (mAutoFoundScrollTargetView != null) {\n return mAutoFoundScrollTargetView;\n } else {\n return mTargetView;\n }\n }\n\n /**\n * Set loadMore scroll target view,For example the content view is a FrameLayout,with a listView\n * in it.You can call this method,set the listView as load more scroll target view. Load more\n * compat will try to make it smooth scrolling.\n *\n * <p>设置加载更多时需要做滑动处理的视图。 例如在SmoothRefreshLayout中有一个CoordinatorLayout,\n * CoordinatorLayout中有AppbarLayout、RecyclerView等,加载更多时希望被移动的视图为RecyclerVieW\n * 而不是CoordinatorLayout,那么设置RecyclerView为TargetView即可\n *\n * @param view Target view\n */\n public void setScrollTargetView(View view) {\n mScrollTargetView = view;\n }\n\n public LayoutManager getLayoutManager() {\n return mLayoutManager;\n }\n\n /**\n * Set custom LayoutManager\n *\n * <p>设置自定义布局管理器\n *\n * @param layoutManager The custom LayoutManager\n */\n public void setLayoutManager(@NonNull LayoutManager layoutManager) {\n if (mLayoutManager != layoutManager) {\n if (mLayoutManager != null) {\n if (mLayoutManager.getOrientation() != layoutManager.getOrientation()) {\n reset();\n requestLayout();\n }\n mLayoutManager.setLayout(null);\n }\n mLayoutManager = layoutManager;\n mLayoutManager.setLayout(this);\n }\n }\n\n /**\n * Set the layout mode\n *\n * <p>设置模式,默认为刷新模式,可配置为拉伸模式\n *\n * @param mode The layout mode. {@link Constants#MODE_DEFAULT}, {@link Constants#MODE_SCALE}\n */\n public void setMode(@Mode int mode) {\n if (mode == Constants.MODE_DEFAULT) {\n if (mLayoutManager instanceof VRefreshLayoutManager) {\n return;\n }\n setLayoutManager(new VRefreshLayoutManager());\n } else {\n if (mLayoutManager instanceof VScaleLayoutManager) {\n return;\n }\n setLayoutManager(new VScaleLayoutManager());\n }\n }\n\n /**\n * Whether to enable the synchronous scroll when load more completed.\n *\n * <p>当加载更多完成时是否启用同步滚动。\n *\n * @param enable enable\n */\n public void setEnableCompatSyncScroll(boolean enable) {\n if (enable) {\n mFlag = mFlag | FLAG_ENABLE_COMPAT_SYNC_SCROLL;\n } else {\n mFlag = mFlag & ~FLAG_ENABLE_COMPAT_SYNC_SCROLL;\n }\n }\n\n /**\n * Set the custom offset calculator.\n *\n * <p>设置自定义偏移计算器\n *\n * @param calculator Offset calculator\n */\n public void setIndicatorOffsetCalculator(IIndicator.IOffsetCalculator calculator) {\n mIndicatorSetter.setOffsetCalculator(calculator);\n }\n\n /**\n * Set the listener to be notified when a refresh is triggered.\n *\n * <p>设置刷新监听回调\n *\n * @param listener Listener\n */\n public <T extends OnRefreshListener> void setOnRefreshListener(T listener) {\n mRefreshListener = listener;\n }\n\n /**\n * Add a listener to listen the views position change event.\n *\n * <p>设置UI位置变化回调\n *\n * @param listener Listener\n */\n public void addOnUIPositionChangedListener(@NonNull OnUIPositionChangedListener listener) {\n if (mUIPositionChangedListeners == null) {\n mUIPositionChangedListeners = new ArrayList<>();\n mUIPositionChangedListeners.add(listener);\n } else if (!mUIPositionChangedListeners.contains(listener)) {\n mUIPositionChangedListeners.add(listener);\n }\n }\n\n /**\n * remove the listener.\n *\n * <p>移除UI位置变化监听器\n *\n * @param listener Listener\n */\n public void removeOnUIPositionChangedListener(@NonNull OnUIPositionChangedListener listener) {\n if (mUIPositionChangedListeners != null) {\n mUIPositionChangedListeners.remove(listener);\n }\n }\n\n /**\n * Add a listener when status changed.\n *\n * <p>添加个状态改变监听\n *\n * @param listener Listener that should be called when status changed.\n */\n public void addOnStatusChangedListener(@NonNull OnStatusChangedListener listener) {\n if (mStatusChangedListeners == null) {\n mStatusChangedListeners = new ArrayList<>();\n mStatusChangedListeners.add(listener);\n } else if (!mStatusChangedListeners.contains(listener)) {\n mStatusChangedListeners.add(listener);\n }\n }\n\n /**\n * remove the listener.\n *\n * <p>移除状态改变监听器\n *\n * @param listener Listener\n */\n public void removeOnStatusChangedListener(@NonNull OnStatusChangedListener listener) {\n if (mStatusChangedListeners != null) {\n mStatusChangedListeners.remove(listener);\n }\n }\n\n /**\n * Set a sync scrolling callback when refresh competed.\n *\n * <p>设置同步滚动回调,可使用该属性对内容视图做滑动处理。例如内容视图是ListView,完成加载更多时,\n * 需要将加载出的数据显示出来,那么设置该回调,每次Footer回滚时拿到滚动的数值对ListView做向上滚动处理,将数据展示处理\n *\n * @param callback a sync scrolling callback when refresh competed.\n */\n public void setOnSyncScrollCallback(OnSyncScrollCallback callback) {\n mSyncScrollCallback = callback;\n }\n\n /**\n * Set a callback to override {@link SmoothRefreshLayout#isNotYetInEdgeCannotMoveHeader()}\n * method. Non-null callback will return the value provided by the callback and ignore all\n * internal logic.\n *\n * <p>设置{@link SmoothRefreshLayout#isNotYetInEdgeCannotMoveHeader()}的重载回调,用来检测内容视图是否在顶部\n *\n * @param callback Callback that should be called when isChildNotYetInEdgeCannotMoveHeader() is\n * called.\n */\n public void setOnHeaderEdgeDetectCallBack(OnHeaderEdgeDetectCallBack callback) {\n mInEdgeCanMoveHeaderCallBack = callback;\n }\n\n /**\n * Set a callback to override {@link SmoothRefreshLayout#isNotYetInEdgeCannotMoveFooter()}\n * method. Non-null callback will return the value provided by the callback and ignore all\n * internal logic.\n *\n * <p>设置{@link SmoothRefreshLayout#isNotYetInEdgeCannotMoveFooter()}的重载回调,用来检测内容视图是否在底部\n *\n * @param callback Callback that should be called when isChildNotYetInEdgeCannotMoveFooter() is\n * called.\n */\n public void setOnFooterEdgeDetectCallBack(OnFooterEdgeDetectCallBack callback) {\n mInEdgeCanMoveFooterCallBack = callback;\n }\n\n /**\n * Set a callback to make sure you need to customize the specified trigger the auto load more\n * rule.\n *\n * <p>设置自动加载更多的触发条件回调,可自定义具体的触发自动加载更多的条件\n *\n * @param callBack Customize the specified triggered rule\n */\n public void setOnPerformAutoLoadMoreCallBack(OnPerformAutoLoadMoreCallBack callBack) {\n mAutoLoadMoreCallBack = callBack;\n }\n\n /**\n * Set a callback to make sure you need to customize the specified trigger the auto refresh\n * rule.\n *\n * <p>设置滚到到顶自动刷新的触发条件回调,可自定义具体的触发自动刷新的条件\n *\n * @param callBack Customize the specified triggered rule\n */\n public void setOnPerformAutoRefreshCallBack(OnPerformAutoRefreshCallBack callBack) {\n mAutoRefreshCallBack = callBack;\n }\n\n public void setOnCalculateBounceCallback(OnCalculateBounceCallback callBack) {\n mCalculateBounceCallback = callBack;\n }\n\n /**\n * Set a hook callback when the refresh complete event be triggered. Only can be called on\n * refreshing.\n *\n * <p>设置一个头部视图刷新完成前的Hook回调\n *\n * @param callback Callback that should be called when refreshComplete() is called.\n */\n public void setOnHookHeaderRefreshCompleteCallback(OnHookUIRefreshCompleteCallBack callback) {\n if (mHeaderRefreshCompleteHook == null)\n mHeaderRefreshCompleteHook = new RefreshCompleteHook();\n mHeaderRefreshCompleteHook.mCallBack = callback;\n }\n\n /**\n * Set a hook callback when the refresh complete event be triggered. Only can be called on\n * loading more.\n *\n * <p>设置一个尾部视图刷新完成前的Hook回调\n *\n * @param callback Callback that should be called when refreshComplete() is called.\n */\n public void setOnHookFooterRefreshCompleteCallback(OnHookUIRefreshCompleteCallBack callback) {\n if (mFooterRefreshCompleteHook == null)\n mFooterRefreshCompleteHook = new RefreshCompleteHook();\n mFooterRefreshCompleteHook.mCallBack = callback;\n }\n\n /**\n * Whether it is refreshing state.\n *\n * <p>是否在刷新中\n *\n * @return Refreshing\n */\n public boolean isRefreshing() {\n return mStatus == SR_STATUS_REFRESHING;\n }\n\n /**\n * Whether it is loading more state.\n *\n * <p>是否在加载更多种\n *\n * @return Loading\n */\n public boolean isLoadingMore() {\n return mStatus == SR_STATUS_LOADING_MORE;\n }\n\n /**\n * Whether it is refresh successful.\n *\n * <p>是否刷新成功\n *\n * @return Is\n */\n public boolean isRefreshSuccessful() {\n return mIsLastRefreshSuccessful;\n }\n\n /**\n * Perform refresh complete, to reset the state to {@link SmoothRefreshLayout#SR_STATUS_INIT}\n * and set the last refresh operation successfully.\n *\n * <p>完成刷新,刷新状态为成功\n */\n public final void refreshComplete() {\n refreshComplete(true);\n }\n\n /**\n * Perform refresh complete, to reset the state to {@link SmoothRefreshLayout#SR_STATUS_INIT}.\n *\n * <p>完成刷新,刷新状态`isSuccessful`\n *\n * @param isSuccessful Set the last refresh operation status\n */\n public final void refreshComplete(boolean isSuccessful) {\n refreshComplete(isSuccessful, 0);\n }\n\n /**\n * Perform refresh complete, delay to reset the state to {@link\n * SmoothRefreshLayout#SR_STATUS_INIT} and set the last refresh operation successfully.\n *\n * <p>完成刷新,延迟`delayDurationToChangeState`时间\n *\n * @param delayDurationToChangeState Delay to change the state to {@link\n * SmoothRefreshLayout#SR_STATUS_COMPLETE}\n */\n public final void refreshComplete(long delayDurationToChangeState) {\n refreshComplete(true, delayDurationToChangeState);\n }\n\n /**\n * Perform refresh complete, delay to reset the state to {@link\n * SmoothRefreshLayout#SR_STATUS_INIT} and set the last refresh operation.\n *\n * <p>完成刷新,刷新状态`isSuccessful`,延迟`delayDurationToChangeState`时间\n *\n * @param delayDurationToChangeState Delay to change the state to {@link\n * SmoothRefreshLayout#SR_STATUS_INIT}\n * @param isSuccessful Set the last refresh operation\n */\n public final void refreshComplete(boolean isSuccessful, long delayDurationToChangeState) {\n if (sDebug) {\n Log.d(\n TAG,\n String.format(\n \"refreshComplete(): isSuccessful: %b, \"\n + \"delayDurationToChangeState: %d\",\n isSuccessful, delayDurationToChangeState));\n }\n mIsLastRefreshSuccessful = isSuccessful;\n if (!isRefreshing() && !isLoadingMore()) {\n return;\n }\n if (delayDurationToChangeState <= 0) {\n performRefreshComplete(true, false, true);\n } else {\n if (isRefreshing() && mHeaderView != null) {\n mHeaderView.onRefreshComplete(this, isSuccessful);\n } else if (isLoadingMore() && mFooterView != null) {\n mFooterView.onRefreshComplete(this, isSuccessful);\n }\n if (mDelayToRefreshComplete == null) {\n mDelayToRefreshComplete = new DelayToRefreshComplete();\n }\n mDelayToRefreshComplete.mLayout = this;\n mDelayToRefreshComplete.mNotifyViews = false;\n postDelayed(mDelayToRefreshComplete, delayDurationToChangeState);\n }\n }\n\n /**\n * Get the Header height, after the measurement is completed, the height will have value.\n *\n * <p>获取Header的高度,在布局计算完成前无法得到准确的值\n *\n * @return Height default is -1\n */\n public int getHeaderHeight() {\n return mIndicator.getHeaderHeight();\n }\n\n /**\n * Get the Footer height, after the measurement is completed, the height will have value.\n *\n * <p>获取Footer的高度,在布局计算完成前无法得到准确的值\n *\n * @return Height default is -1\n */\n public int getFooterHeight() {\n return mIndicator.getFooterHeight();\n }\n\n /**\n * Perform auto refresh at once.\n *\n * <p>自动刷新并立即触发刷新回调\n */\n public boolean autoRefresh() {\n return autoRefresh(Constants.ACTION_NOTIFY, true);\n }\n\n /**\n * If @param atOnce has been set to true. Auto perform refresh at once.\n *\n * <p>自动刷新,`atOnce`立即触发刷新回调\n *\n * @param atOnce Auto refresh at once\n */\n public boolean autoRefresh(boolean atOnce) {\n return autoRefresh(atOnce ? Constants.ACTION_AT_ONCE : Constants.ACTION_NOTIFY, true);\n }\n\n /**\n * If @param atOnce has been set to true. Auto perform refresh at once. If @param smooth has\n * been set to true. Auto perform refresh will using smooth scrolling.\n *\n * <p>自动刷新,`atOnce`立即触发刷新回调,`smoothScroll`滚动到触发位置\n *\n * @param atOnce Auto refresh at once\n * @param smoothScroll Auto refresh use smooth scrolling\n */\n public boolean autoRefresh(boolean atOnce, boolean smoothScroll) {\n return autoRefresh(\n atOnce ? Constants.ACTION_AT_ONCE : Constants.ACTION_NOTIFY, smoothScroll);\n }\n\n /**\n * The @param action can be used to specify the action to trigger refresh. If the `action` been\n * set to `SR_ACTION_NOTHING`, we will not notify the refresh listener when in refreshing. If\n * the `action` been set to `SR_ACTION_AT_ONCE`, we will notify the refresh listener at once. If\n * the `action` been set to `SR_ACTION_NOTIFY`, we will notify the refresh listener when in\n * refreshing be later If @param smooth has been set to true. Auto perform refresh will using\n * smooth scrolling.\n *\n * <p>自动刷新,`action`触发刷新的动作,`smoothScroll`滚动到触发位置\n *\n * @param action Auto refresh use action .{@link Constants#ACTION_NOTIFY}, {@link\n * Constants#ACTION_AT_ONCE}, {@link Constants#ACTION_NOTHING}\n * @param smoothScroll Auto refresh use smooth scrolling\n */\n public boolean autoRefresh(@Action int action, boolean smoothScroll) {\n if (mStatus != SR_STATUS_INIT || isDisabledPerformRefresh()) {\n return false;\n }\n if (sDebug) {\n Log.d(\n TAG,\n String.format(\n \"autoRefresh(): action: %d, smoothScroll: %b\", action, smoothScroll));\n }\n final byte old = mStatus;\n mStatus = SR_STATUS_PREPARE;\n notifyStatusChanged(old, mStatus);\n if (mHeaderView != null) {\n mHeaderView.onRefreshPrepare(this);\n }\n mIndicatorSetter.setMovingStatus(Constants.MOVING_HEADER);\n mViewStatus = SR_VIEW_STATUS_HEADER_IN_PROCESSING;\n mAutomaticActionUseSmoothScroll = smoothScroll;\n mAutomaticAction = action;\n if (mIndicator.getHeaderHeight() <= 0) {\n mAutomaticActionTriggered = false;\n } else {\n scrollToTriggeredAutomatic(true);\n }\n return true;\n }\n\n /**\n * Trigger refresh action directly\n *\n * <p>强制直接触发刷新\n */\n public boolean forceRefresh() {\n if (mIndicator.getHeaderHeight() <= 0 || isDisabledPerformRefresh()) {\n return false;\n }\n removeCallbacks(mDelayToRefreshComplete);\n triggeredRefresh(true);\n return true;\n }\n\n /**\n * Perform auto load more at once.\n *\n * <p>自动加载更多,并立即触发刷新回调\n */\n public boolean autoLoadMore() {\n return autoLoadMore(Constants.ACTION_NOTIFY, true);\n }\n\n /**\n * If @param atOnce has been set to true. Auto perform load more at once.\n *\n * <p>自动加载更多,`atOnce`立即触发刷新回调\n *\n * @param atOnce Auto load more at once\n */\n public boolean autoLoadMore(boolean atOnce) {\n return autoLoadMore(atOnce ? Constants.ACTION_AT_ONCE : Constants.ACTION_NOTIFY, true);\n }\n\n /**\n * If @param atOnce has been set to true. Auto perform load more at once. If @param smooth has\n * been set to true. Auto perform load more will using smooth scrolling.\n *\n * <p>自动加载更多,`atOnce`立即触发刷新回调,`smoothScroll`滚动到触发位置\n *\n * @param atOnce Auto load more at once\n * @param smoothScroll Auto load more use smooth scrolling\n */\n public boolean autoLoadMore(boolean atOnce, boolean smoothScroll) {\n return autoLoadMore(\n atOnce ? Constants.ACTION_AT_ONCE : Constants.ACTION_NOTIFY, smoothScroll);\n }\n\n /**\n * The @param action can be used to specify the action to trigger refresh. If the `action` been\n * set to `SR_ACTION_NOTHING`, we will not notify the refresh listener when in refreshing. If\n * the `action` been set to `SR_ACTION_AT_ONCE`, we will notify the refresh listener at once. If\n * the `action` been set to `SR_ACTION_NOTIFY`, we will notify the refresh listener when in\n * refreshing be later If @param smooth has been set to true. Auto perform load more will using\n * smooth scrolling.\n *\n * <p>自动加载更多,`action`触发加载更多的动作,`smoothScroll`滚动到触发位置\n *\n * @param action Auto load more use action.{@link Constants#ACTION_NOTIFY}, {@link\n * Constants#ACTION_AT_ONCE}, {@link Constants#ACTION_NOTHING}\n * @param smoothScroll Auto load more use smooth scrolling\n */\n public boolean autoLoadMore(@Action int action, boolean smoothScroll) {\n if (mStatus != SR_STATUS_INIT || isDisabledPerformLoadMore()) {\n return false;\n }\n if (sDebug) {\n Log.d(\n TAG,\n String.format(\n \"autoLoadMore(): action: %d, smoothScroll: %b\", action, smoothScroll));\n }\n final byte old = mStatus;\n mStatus = SR_STATUS_PREPARE;\n notifyStatusChanged(old, mStatus);\n if (mFooterView != null) {\n mFooterView.onRefreshPrepare(this);\n }\n mIndicatorSetter.setMovingStatus(Constants.MOVING_FOOTER);\n mViewStatus = SR_VIEW_STATUS_FOOTER_IN_PROCESSING;\n mAutomaticActionUseSmoothScroll = smoothScroll;\n if (mIndicator.getFooterHeight() <= 0) {\n mAutomaticActionTriggered = false;\n } else {\n scrollToTriggeredAutomatic(false);\n }\n return true;\n }\n\n /**\n * Trigger load more action directly\n *\n * <p>强制直接触发加载更多\n */\n public boolean forceLoadMore() {\n if (mIndicator.getFooterHeight() <= 0 || isDisabledPerformLoadMore()) {\n return false;\n }\n removeCallbacks(mDelayToRefreshComplete);\n triggeredLoadMore(true);\n return true;\n }\n\n /**\n * Set the resistance while you are moving.\n *\n * <p>移动刷新视图时候的移动阻尼\n *\n * @param resistance Resistance\n */\n public void setResistance(float resistance) {\n mIndicatorSetter.setResistance(resistance);\n }\n\n /**\n * Set the resistance while you are moving Footer.\n *\n * <p>移动Footer视图时候的移动阻尼\n *\n * @param resistance Resistance\n */\n public void setResistanceOfFooter(float resistance) {\n mIndicatorSetter.setResistanceOfFooter(resistance);\n }\n\n /**\n * Set the resistance while you are moving Header.\n *\n * <p>移动Header视图时候的移动阻尼\n *\n * @param resistance Resistance\n */\n public void setResistanceOfHeader(float resistance) {\n mIndicatorSetter.setResistanceOfHeader(resistance);\n }\n\n /**\n * Set the height ratio of the trigger refresh.\n *\n * <p>设置触发刷新时的位置占刷新视图的高度比\n *\n * @param ratio Height ratio\n */\n public void setRatioToRefresh(float ratio) {\n mIndicatorSetter.setRatioToRefresh(ratio);\n }\n\n /**\n * Set the Header height ratio of the trigger refresh.\n *\n * <p>设置触发下拉刷新时的位置占Header视图的高度比\n *\n * @param ratio Height ratio\n */\n public void setRatioOfHeaderToRefresh(float ratio) {\n mIndicatorSetter.setRatioOfHeaderToRefresh(ratio);\n }\n\n /**\n * Set the Footer height ratio of the trigger refresh.\n *\n * <p>设置触发加载更多时的位置占Footer视图的高度比\n *\n * @param ratio Height ratio\n */\n public void setRatioOfFooterToRefresh(float ratio) {\n mIndicatorSetter.setRatioOfFooterToRefresh(ratio);\n }\n\n /**\n * Set the offset of keep view in refreshing occupies the height ratio of the refresh view.\n *\n * <p>刷新中保持视图位置占刷新视图的高度比(默认:`1f`),该属性的值必须小于等于触发刷新高度比才会有效果, 当开启了{@link\n * SmoothRefreshLayout#isEnabledKeepRefreshView}后,该属性会生效\n *\n * @param ratio Height ratio\n */\n public void setRatioToKeep(float ratio) {\n mIndicatorSetter.setRatioToKeepHeader(ratio);\n mIndicatorSetter.setRatioToKeepFooter(ratio);\n }\n\n /**\n * Set the offset of keep Header in refreshing occupies the height ratio of the Header.\n *\n * <p>刷新中保持视图位置占Header视图的高度比(默认:`1f`),该属性的值必须小于等于触发刷新高度比才会有效果\n *\n * @param ratio Height ratio\n */\n public void setRatioToKeepHeader(float ratio) {\n mIndicatorSetter.setRatioToKeepHeader(ratio);\n }\n\n /**\n * Set the offset of keep Footer in refreshing occupies the height ratio of the Footer.\n *\n * <p>刷新中保持视图位置占Header视图的高度比(默认:`1f`),该属性的值必须小于等于触发刷新高度比才会有效果\n *\n * @param ratio Height ratio\n */\n public void setRatioToKeepFooter(float ratio) {\n mIndicatorSetter.setRatioToKeepFooter(ratio);\n }\n\n /**\n * Set the max duration for Cross-Boundary-Rebound(OverScroll).\n *\n * <p>设置越界回弹效果弹出时的最大持续时长(默认:`350`)\n *\n * @param duration Duration\n */\n public void setMaxOverScrollDuration(int duration) {\n mMaxOverScrollDuration = duration;\n }\n\n /**\n * Set the min duration for Cross-Boundary-Rebound(OverScroll).\n *\n * <p>设置越界回弹效果弹出时的最小持续时长(默认:`100`)\n *\n * @param duration Duration\n */\n public void setMinOverScrollDuration(int duration) {\n mMinOverScrollDuration = duration;\n }\n\n /**\n * Set the duration for Fling back.\n *\n * <p>设置越界回弹效果回弹时的持续时长(默认:`550`)\n *\n * @param duration Duration\n */\n public void setFlingBackDuration(int duration) {\n mDurationOfFlingBack = duration;\n }\n\n /**\n * Set the duration of return back to the start position.\n *\n * <p>设置刷新完成回滚到起始位置的时间\n *\n * @param duration Millis\n */\n public void setDurationToClose(int duration) {\n mDurationToCloseHeader = duration;\n mDurationToCloseFooter = duration;\n }\n\n /**\n * Set the duration of Header return to the start position.\n *\n * <p>设置Header刷新完成回滚到起始位置的时间\n *\n * @param duration Millis\n */\n public void setDurationToCloseHeader(int duration) {\n mDurationToCloseHeader = duration;\n }\n\n /**\n * Set the duration of Footer return to the start position.\n *\n * <p>设置Footer刷新完成回滚到起始位置的时间\n *\n * @param duration Millis\n */\n public void setDurationToCloseFooter(int duration) {\n mDurationToCloseFooter = duration;\n }\n\n /**\n * Set the duration of return to the keep refresh view position.\n *\n * <p>设置回滚到保持刷新视图位置的时间\n *\n * @param duration Millis\n */\n public void setDurationOfBackToKeep(int duration) {\n mDurationOfBackToHeaderHeight = duration;\n mDurationOfBackToFooterHeight = duration;\n }\n\n /**\n * Set the duration of return to the keep refresh view position when Header moves.\n *\n * <p>设置回滚到保持Header视图位置的时间\n *\n * @param duration Millis\n */\n public void setDurationOfBackToKeepHeader(int duration) {\n this.mDurationOfBackToHeaderHeight = duration;\n }\n\n /**\n * Set the duration of return to the keep refresh view position when Footer moves.\n *\n * <p>设置回顾到保持Footer视图位置的时间\n *\n * @param duration Millis\n */\n public void setDurationOfBackToKeepFooter(int duration) {\n this.mDurationOfBackToFooterHeight = duration;\n }\n\n /**\n * Set the max can move offset occupies the height ratio of the refresh view.\n *\n * <p>设置最大移动距离占刷新视图的高度比\n *\n * @param ratio The max ratio of refresh view\n */\n public void setMaxMoveRatio(float ratio) {\n mIndicatorSetter.setMaxMoveRatio(ratio);\n }\n\n /**\n * Set the max can move offset occupies the height ratio of the Header.\n *\n * <p>设置最大移动距离占Header视图的高度比\n *\n * @param ratio The max ratio of Header view\n */\n public void setMaxMoveRatioOfHeader(float ratio) {\n mIndicatorSetter.setMaxMoveRatioOfHeader(ratio);\n }\n\n /**\n * Set the max can move offset occupies the height ratio of the Footer.\n *\n * <p>设置最大移动距离占Footer视图的高度比\n *\n * @param ratio The max ratio of Footer view\n */\n public void setMaxMoveRatioOfFooter(float ratio) {\n mIndicatorSetter.setMaxMoveRatioOfFooter(ratio);\n }\n\n /**\n * The flag has set to autoRefresh.\n *\n * <p>是否处于自动刷新刷新\n *\n * @return Enabled\n */\n public boolean isAutoRefresh() {\n return (mFlag & FLAG_AUTO_REFRESH) > 0;\n }\n\n /**\n * The flag has set enabled overScroll.\n *\n * <p>是否已经开启越界回弹\n *\n * @return Enabled\n */\n public boolean isEnabledOverScroll() {\n return (mFlag & FLAG_ENABLE_OVER_SCROLL) > 0;\n }\n\n /**\n * If @param enable has been set to true. Will supports over scroll.\n *\n * <p>设置开始越界回弹\n *\n * @param enable Enable\n */\n public void setEnableOverScroll(boolean enable) {\n if (enable) {\n mFlag = mFlag | FLAG_ENABLE_OVER_SCROLL;\n } else {\n mFlag = mFlag & ~FLAG_ENABLE_OVER_SCROLL;\n }\n }\n\n /**\n * The flag has set enabled to intercept the touch event while loading.\n *\n * <p>是否已经开启刷新中拦截消耗触摸事件\n *\n * @return Enabled\n */\n public boolean isEnabledInterceptEventWhileLoading() {\n return (mFlag & FLAG_ENABLE_INTERCEPT_EVENT_WHILE_LOADING) > 0;\n }\n\n /**\n * If @param enable has been set to true. Will intercept the touch event while loading.\n *\n * <p>开启刷新中拦截消耗触摸事件\n *\n * @param enable Enable\n */\n public void setEnableInterceptEventWhileLoading(boolean enable) {\n if (enable) {\n mFlag = mFlag | FLAG_ENABLE_INTERCEPT_EVENT_WHILE_LOADING;\n } else {\n mFlag = mFlag & ~FLAG_ENABLE_INTERCEPT_EVENT_WHILE_LOADING;\n }\n }\n\n /**\n * The flag has been set to pull to refresh.\n *\n * <p>是否已经开启拉动刷新,下拉或者上拉到触发刷新位置即立即触发刷新\n *\n * @return Enabled\n */\n public boolean isEnabledPullToRefresh() {\n return (mFlag & FLAG_ENABLE_PULL_TO_REFRESH) > 0;\n }\n\n /**\n * If @param enable has been set to true. When the current pos >= refresh offsets perform\n * refresh.\n *\n * <p>设置开启拉动刷新,下拉或者上拉到触发刷新位置即立即触发刷新\n *\n * @param enable Pull to refresh\n */\n public void setEnablePullToRefresh(boolean enable) {\n if (enable) {\n mFlag = mFlag | FLAG_ENABLE_PULL_TO_REFRESH;\n } else {\n mFlag = mFlag & ~FLAG_ENABLE_PULL_TO_REFRESH;\n }\n }\n\n /**\n * The flag has been set to enabled Header drawerStyle.\n *\n * <p>是否已经开启Header的抽屉效果,即Header在Content下面\n *\n * @return Enabled\n */\n public boolean isEnabledHeaderDrawerStyle() {\n return (mFlag & FLAG_ENABLE_HEADER_DRAWER_STYLE) > 0;\n }\n\n /**\n * If @param enable has been set to true.Enable Header drawerStyle.\n *\n * <p>设置开启Header的抽屉效果,即Header在Content下面,由于该效果需要改变层级关系,所以需要重新布局\n *\n * @param enable enable Header drawerStyle\n */\n public void setEnableHeaderDrawerStyle(boolean enable) {\n if (enable) {\n mFlag = mFlag | FLAG_ENABLE_HEADER_DRAWER_STYLE;\n } else {\n mFlag = mFlag & ~FLAG_ENABLE_HEADER_DRAWER_STYLE;\n }\n mViewsZAxisNeedReset = true;\n checkViewsZAxisNeedReset();\n }\n\n /**\n * The flag has been set to enabled Footer drawerStyle.\n *\n * <p>是否已经开启Footer的抽屉效果,即Footer在Content下面\n *\n * @return Enabled\n */\n public boolean isEnabledFooterDrawerStyle() {\n return (mFlag & FLAG_ENABLE_FOOTER_DRAWER_STYLE) > 0;\n }\n\n /**\n * If @param enable has been set to true.Enable Footer drawerStyle.\n *\n * <p>设置开启Footer的抽屉效果,即Footer在Content下面,由于该效果需要改变层级关系,所以需要重新布局\n *\n * @param enable enable Footer drawerStyle\n */\n public void setEnableFooterDrawerStyle(boolean enable) {\n if (enable) {\n mFlag = mFlag | FLAG_ENABLE_FOOTER_DRAWER_STYLE;\n } else {\n mFlag = mFlag & ~FLAG_ENABLE_FOOTER_DRAWER_STYLE;\n }\n mViewsZAxisNeedReset = true;\n checkViewsZAxisNeedReset();\n }\n\n /**\n * The flag has been set to disabled perform refresh.\n *\n * <p>是否已经关闭触发下拉刷新\n *\n * @return Disabled\n */\n public boolean isDisabledPerformRefresh() {\n return (mFlag & MASK_DISABLE_PERFORM_REFRESH) > 0;\n }\n\n /**\n * If @param disable has been set to true. Will never perform refresh.\n *\n * <p>设置是否关闭触发下拉刷新\n *\n * @param disable Disable perform refresh\n */\n public void setDisablePerformRefresh(boolean disable) {\n if (disable) {\n mFlag = mFlag | FLAG_DISABLE_PERFORM_REFRESH;\n reset();\n } else {\n mFlag = mFlag & ~FLAG_DISABLE_PERFORM_REFRESH;\n }\n }\n\n /**\n * The flag has been set to disabled refresh.\n *\n * <p>是否已经关闭刷新\n *\n * @return Disabled\n */\n public boolean isDisabledRefresh() {\n return (mFlag & FLAG_DISABLE_REFRESH) > 0;\n }\n\n /**\n * If @param disable has been set to true.Will disable refresh.\n *\n * <p>设置是否关闭刷新\n *\n * @param disable Disable refresh\n */\n public void setDisableRefresh(boolean disable) {\n if (disable) {\n mFlag = mFlag | FLAG_DISABLE_REFRESH;\n reset();\n } else {\n mFlag = mFlag & ~FLAG_DISABLE_REFRESH;\n }\n }\n\n /**\n * The flag has been set to disabled perform load more.\n *\n * <p>是否已经关闭触发加载更多\n *\n * @return Disabled\n */\n public boolean isDisabledPerformLoadMore() {\n return (mFlag & MASK_DISABLE_PERFORM_LOAD_MORE) > 0;\n }\n\n /**\n * If @param disable has been set to true.Will never perform load more.\n *\n * <p>设置是否关闭触发加载更多\n *\n * @param disable Disable perform load more\n */\n public void setDisablePerformLoadMore(boolean disable) {\n if (disable) {\n mFlag = mFlag | FLAG_DISABLE_PERFORM_LOAD_MORE;\n reset();\n } else {\n mFlag = mFlag & ~FLAG_DISABLE_PERFORM_LOAD_MORE;\n }\n }\n\n /**\n * The flag has been set to disabled load more.\n *\n * <p>是否已经关闭加载更多\n *\n * @return Disabled\n */\n public boolean isDisabledLoadMore() {\n return (mFlag & FLAG_DISABLE_LOAD_MORE) > 0;\n }\n\n /**\n * If @param disable has been set to true. Will disable load more.\n *\n * <p>设置关闭加载更多\n *\n * @param disable Disable load more\n */\n public void setDisableLoadMore(boolean disable) {\n if (disable) {\n mFlag = mFlag | FLAG_DISABLE_LOAD_MORE;\n reset();\n } else {\n mFlag = mFlag & ~FLAG_DISABLE_LOAD_MORE;\n }\n }\n\n /**\n * The flag has been set to enabled the old touch handling logic.\n *\n * <p>是否已经启用老版本的事件处理逻辑\n *\n * @return Enabled\n */\n public boolean isEnabledOldTouchHandling() {\n return (mFlag & FLAG_ENABLE_OLD_TOUCH_HANDLING) > 0;\n }\n\n /**\n * If @param enable has been set to true. Frame will use the old version of the touch event\n * handling logic.\n *\n * <p>设置开启老版本的事件处理逻辑,老版本的逻辑会导致部分场景下体验下降,例如拉出刷新视图再收回视图,\n * 当刷新视图回到顶部后缓慢滑动会导致内容视图触发按下效果,视觉上产生割裂,整体性较差但兼容性最好。\n * 新版本的逻辑将一直向下传递触摸事件,不会产生割裂效果,但同时由于需要避免触发长按事件,取巧性的利用了偏移进行规避,\n * 可能导致极个别情况下兼容没有老版本的逻辑好,可按需切换。切莫在处理事件处理过程中切换!\n *\n * @param enable Enable old touch handling\n */\n public void setEnableOldTouchHandling(boolean enable) {\n if (mIndicator.hasTouched()) {\n Log.e(TAG, \"This method cannot be called during touch event handling\");\n return;\n }\n if (enable) {\n mFlag = mFlag | FLAG_ENABLE_OLD_TOUCH_HANDLING;\n } else {\n mFlag = mFlag & ~FLAG_ENABLE_OLD_TOUCH_HANDLING;\n }\n }\n\n /**\n * The flag has been set to disabled when horizontal move.\n *\n * <p>是否已经设置响应其它方向滑动\n *\n * @return Disabled\n */\n public boolean isDisabledWhenAnotherDirectionMove() {\n return (mFlag & FLAG_DISABLE_WHEN_ANOTHER_DIRECTION_MOVE) > 0;\n }\n\n /**\n * Set whether to filter the horizontal moves.\n *\n * <p>设置响应其它方向滑动,当内容视图含有需要响应其它方向滑动的子视图时,需要设置该属性,否则子视图无法响应其它方向的滑动\n *\n * @param disable Enable\n */\n public void setDisableWhenAnotherDirectionMove(boolean disable) {\n if (disable) {\n mFlag = mFlag | FLAG_DISABLE_WHEN_ANOTHER_DIRECTION_MOVE;\n } else {\n mFlag = mFlag & ~FLAG_DISABLE_WHEN_ANOTHER_DIRECTION_MOVE;\n }\n }\n\n /**\n * The flag has been set to enabled load more has no more data.\n *\n * <p>是否已经开启加载更多完成已无更多数据,自定义Footer可根据该属性判断是否显示无更多数据的提示\n *\n * @return Enabled\n */\n public boolean isEnabledNoMoreData() {\n return (mFlag & FLAG_ENABLE_NO_MORE_DATA) > 0;\n }\n\n /**\n * If @param enable has been set to true. The Footer will show no more data and will never\n * trigger load more.\n *\n * <p>设置开启加载更多完成已无更多数据,当该属性设置为`true`时,将不再触发加载更多\n *\n * @param enable Enable no more data\n */\n public void setEnableNoMoreData(boolean enable) {\n mFlag = mFlag | FLAG_BEEN_SET_NO_MORE_DATA;\n if (enable) {\n mFlag = mFlag | FLAG_ENABLE_NO_MORE_DATA;\n } else {\n mFlag = mFlag & ~(FLAG_ENABLE_NO_MORE_DATA | FLAG_ENABLE_NO_MORE_DATA_NO_BACK);\n }\n }\n\n /**\n * The flag has been set to enabled. Load more will be disabled when the content is not full.\n *\n * <p>是否已经设置了内容视图未满屏时关闭加载更多\n *\n * @return Disabled\n */\n public boolean isDisabledLoadMoreWhenContentNotFull() {\n return (mFlag & FLAG_DISABLE_LOAD_MORE_WHEN_CONTENT_NOT_FULL) > 0;\n }\n\n /**\n * If @param disable has been set to true.Load more will be disabled when the content is not\n * full.\n *\n * <p>设置当内容视图未满屏时关闭加载更多\n *\n * @param disable Disable load more when the content is not full\n */\n public void setDisableLoadMoreWhenContentNotFull(boolean disable) {\n if (disable) {\n mFlag = mFlag | FLAG_DISABLE_LOAD_MORE_WHEN_CONTENT_NOT_FULL;\n } else {\n mFlag = mFlag & ~FLAG_DISABLE_LOAD_MORE_WHEN_CONTENT_NOT_FULL;\n }\n }\n\n /**\n * The flag has been set to enabled when Footer has no more data and no spring back.\n *\n * <p>是否已经开启加载更多完成已无更多数据且不需要回滚动作\n *\n * @return Enabled\n */\n public boolean isEnabledNoMoreDataAndNoSpringBack() {\n return (mFlag & FLAG_ENABLE_NO_MORE_DATA_NO_BACK) > 0;\n }\n\n /**\n * If @param enable has been set to true. When there is no more data and no spring back.\n *\n * <p>设置开启加载更多完成已无更多数据且不需要回滚动作,当该属性设置为`true`时,将不再触发加载更多\n *\n * @param enable Enable no more data\n */\n public void setEnableNoMoreDataAndNoSpringBack(boolean enable) {\n mFlag = mFlag | FLAG_BEEN_SET_NO_MORE_DATA;\n if (enable) {\n mFlag = mFlag | FLAG_ENABLE_NO_MORE_DATA | FLAG_ENABLE_NO_MORE_DATA_NO_BACK;\n } else {\n mFlag = mFlag & ~(FLAG_ENABLE_NO_MORE_DATA | FLAG_ENABLE_NO_MORE_DATA_NO_BACK);\n }\n }\n\n /**\n * The flag has been set to keep refresh view while loading.\n *\n * <p>是否已经开启保持刷新视图\n *\n * @return Enabled\n */\n public boolean isEnabledKeepRefreshView() {\n return (mFlag & FLAG_ENABLE_KEEP_REFRESH_VIEW) > 0;\n }\n\n /**\n * If @param enable has been set to true.When the current pos> = keep refresh view pos, it rolls\n * back to the keep refresh view pos to perform refresh and remains until the refresh completed.\n *\n * <p>开启刷新中保持刷新视图位置\n *\n * @param enable Keep refresh view\n */\n public void setEnableKeepRefreshView(boolean enable) {\n\n if (enable) {\n mFlag = mFlag | FLAG_ENABLE_KEEP_REFRESH_VIEW;\n } else {\n mFlag =\n mFlag\n & ~(FLAG_ENABLE_KEEP_REFRESH_VIEW\n | FLAG_ENABLE_PIN_REFRESH_VIEW_WHILE_LOADING);\n }\n }\n\n /**\n * The flag has been set to perform load more when the content view scrolling to bottom.\n *\n * <p>是否已经开启到底部自动加载更多\n *\n * @return Enabled\n */\n public boolean isEnabledAutoLoadMore() {\n return (mFlag & FLAG_ENABLE_AUTO_PERFORM_LOAD_MORE) > 0;\n }\n\n /**\n * If @param enable has been set to true.When the content view scrolling to bottom, it will be\n * perform load more.\n *\n * <p>开启到底自动加载更多\n *\n * @param enable Enable\n */\n public void setEnableAutoLoadMore(boolean enable) {\n if (enable) {\n mFlag = mFlag | FLAG_ENABLE_AUTO_PERFORM_LOAD_MORE;\n } else {\n mFlag = mFlag & ~FLAG_ENABLE_AUTO_PERFORM_LOAD_MORE;\n }\n }\n\n /**\n * The flag has been set to perform refresh when the content view scrolling to top.\n *\n * <p>是否已经开启到顶自动刷新\n *\n * @return Enabled\n */\n public boolean isEnabledAutoRefresh() {\n return (mFlag & FLAG_ENABLE_AUTO_PERFORM_REFRESH) > 0;\n }\n\n /**\n * If @param enable has been set to true.When the content view scrolling to top, it will be\n * perform refresh.\n *\n * <p>开启到顶自动刷新\n *\n * @param enable Enable\n */\n public void setEnableAutoRefresh(boolean enable) {\n if (enable) {\n mFlag = mFlag | FLAG_ENABLE_AUTO_PERFORM_REFRESH;\n } else {\n mFlag = mFlag & ~FLAG_ENABLE_AUTO_PERFORM_REFRESH;\n }\n }\n\n /**\n * The flag has been set to pinned refresh view while loading.\n *\n * <p>是否已经开启刷新过程中固定刷新视图且不响应触摸移动\n *\n * @return Enabled\n */\n public boolean isEnabledPinRefreshViewWhileLoading() {\n return (mFlag & FLAG_ENABLE_PIN_REFRESH_VIEW_WHILE_LOADING) > 0;\n }\n\n /**\n * If @param enable has been set to true.The refresh view will pinned at the keep refresh\n * position.\n *\n * @param enable Pin content view\n */\n public void setEnablePinRefreshViewWhileLoading(boolean enable) {\n if (enable) {\n mFlag =\n mFlag\n | FLAG_ENABLE_PIN_CONTENT_VIEW\n | FLAG_ENABLE_PIN_REFRESH_VIEW_WHILE_LOADING\n | FLAG_ENABLE_KEEP_REFRESH_VIEW;\n } else {\n mFlag = mFlag & ~FLAG_ENABLE_PIN_REFRESH_VIEW_WHILE_LOADING;\n }\n }\n\n /**\n * The flag has been set to pinned content view while loading.\n *\n * <p>是否已经开启了固定内容视图\n *\n * @return Enabled\n */\n public boolean isEnabledPinContentView() {\n return (mFlag & FLAG_ENABLE_PIN_CONTENT_VIEW) > 0;\n }\n\n /**\n * If @param enable has been set to true. The content view will be pinned in the start pos.\n *\n * <p>设置开启固定内容视图\n *\n * @param enable Pin content view\n */\n public void setEnablePinContentView(boolean enable) {\n if (enable) {\n mFlag = mFlag | FLAG_ENABLE_PIN_CONTENT_VIEW;\n } else {\n mFlag =\n mFlag\n & ~(FLAG_ENABLE_PIN_CONTENT_VIEW\n | FLAG_ENABLE_PIN_REFRESH_VIEW_WHILE_LOADING);\n }\n }\n\n /**\n * The flag has been set to perform refresh when Fling.\n *\n * <p>是否已经开启了当收回刷新视图的手势被触发且当前位置大于触发刷新的位置时,将可以触发刷新同时将不存在Fling效果的功能,\n *\n * @return Enabled\n */\n public boolean isEnabledPerformFreshWhenFling() {\n return (mFlag & FLAG_ENABLE_PERFORM_FRESH_WHEN_FLING) > 0;\n }\n\n /**\n * If @param enable has been set to true. When the gesture of retracting the refresh view is\n * triggered and the current offset is greater than the trigger refresh offset, the fresh can be\n * performed without the Fling effect.\n *\n * <p>当收回刷新视图的手势被触发且当前位置大于触发刷新的位置时,将可以触发刷新同时将不存在Fling效果\n *\n * @param enable enable perform refresh when fling\n */\n public void setEnablePerformFreshWhenFling(boolean enable) {\n if (enable) {\n mFlag = mFlag | FLAG_ENABLE_PERFORM_FRESH_WHEN_FLING;\n } else {\n mFlag = mFlag & ~FLAG_ENABLE_PERFORM_FRESH_WHEN_FLING;\n }\n }\n\n @Nullable\n public IRefreshView<IIndicator> getFooterView() {\n // Use the static default creator to create the Footer view\n if (!isDisabledLoadMore() && mFooterView == null && sCreator != null) {\n final IRefreshView<IIndicator> footer = sCreator.createFooter(this);\n if (footer != null) {\n setFooterView(footer);\n }\n }\n return mFooterView;\n }\n\n /**\n * Set the Footer view.\n *\n * <p>设置Footer视图\n *\n * @param footer Footer view\n */\n public void setFooterView(@NonNull IRefreshView footer) {\n if (footer.getType() != IRefreshView.TYPE_FOOTER) {\n throw new IllegalArgumentException(\"Wrong type, FooterView type must be TYPE_FOOTER\");\n }\n if (footer == mFooterView) {\n return;\n }\n if (mFooterView != null) {\n removeView(mFooterView.getView());\n mFooterView = null;\n }\n final View view = footer.getView();\n mViewsZAxisNeedReset = true;\n addView(view, -1, view.getLayoutParams());\n }\n\n @Nullable\n public IRefreshView<IIndicator> getHeaderView() {\n // Use the static default creator to create the Header view\n if (!isDisabledRefresh() && mHeaderView == null && sCreator != null) {\n final IRefreshView<IIndicator> header = sCreator.createHeader(this);\n if (header != null) {\n setHeaderView(header);\n }\n }\n return mHeaderView;\n }\n\n /**\n * Set the Header view.\n *\n * <p>设置Header视图\n *\n * @param header Header view\n */\n public void setHeaderView(@NonNull IRefreshView header) {\n if (header.getType() != IRefreshView.TYPE_HEADER) {\n throw new IllegalArgumentException(\"Wrong type, HeaderView type must be TYPE_HEADER\");\n }\n if (header == mHeaderView) {\n return;\n }\n if (mHeaderView != null) {\n removeView(mHeaderView.getView());\n mHeaderView = null;\n }\n final View view = header.getView();\n mViewsZAxisNeedReset = true;\n addView(view, -1, view.getLayoutParams());\n }\n\n /**\n * Set the content view.\n *\n * <p>设置内容视图\n *\n * @param content Content view\n */\n public void setContentView(View content) {\n if (mTargetView == content) {\n return;\n }\n mContentResId = View.NO_ID;\n final int count = getChildCount();\n for (int i = 0; i < count; i++) {\n final View child = getChildAt(i);\n if (child == content) {\n mTargetView = content;\n return;\n }\n }\n if (mTargetView != null) {\n removeView(mTargetView);\n }\n ViewGroup.LayoutParams lp = content.getLayoutParams();\n if (lp == null) {\n lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);\n }\n mTargetView = content;\n mViewsZAxisNeedReset = true;\n addView(content, lp);\n }\n\n /**\n * Set the content view resource id.\n *\n * <p>设置内容视图\n *\n * @param id Content view resource id\n */\n public void setContentResId(@IdRes int id) {\n if (id != mContentResId) {\n mContentResId = id;\n mTargetView = null;\n ensureTargetView();\n }\n }\n\n /**\n * Reset scroller interpolator.\n *\n * <p>重置Scroller的插值器\n */\n public void resetScrollerInterpolator() {\n if (mSpringInterpolator != SPRING_INTERPOLATOR) {\n setSpringInterpolator(SPRING_INTERPOLATOR);\n }\n if (mSpringBackInterpolator != SPRING_BACK_INTERPOLATOR) {\n setSpringBackInterpolator(SPRING_BACK_INTERPOLATOR);\n }\n }\n\n /**\n * Set the scroller default interpolator.\n *\n * <p>设置Scroller的默认插值器\n *\n * @param interpolator Scroller interpolator\n */\n public void setSpringInterpolator(@NonNull Interpolator interpolator) {\n if (mSpringInterpolator != interpolator) {\n mSpringInterpolator = interpolator;\n if (mScrollChecker.isSpring()) {\n mScrollChecker.setInterpolator(interpolator);\n }\n }\n }\n\n /**\n * Set the scroller spring back interpolator.\n *\n * @param interpolator Scroller interpolator\n */\n public void setSpringBackInterpolator(@NonNull Interpolator interpolator) {\n if (mSpringBackInterpolator != interpolator) {\n mSpringBackInterpolator = interpolator;\n if (mScrollChecker.isSpringBack() || mScrollChecker.isFlingBack()) {\n mScrollChecker.setInterpolator(interpolator);\n }\n }\n }\n\n /**\n * Get the ScrollChecker current mode.\n *\n * @return the mode {@link Constants#SCROLLER_MODE_NONE}, {@link\n * Constants#SCROLLER_MODE_PRE_FLING}, {@link Constants#SCROLLER_MODE_FLING}, {@link\n * Constants#SCROLLER_MODE_CALC_FLING}, {@link Constants#SCROLLER_MODE_FLING_BACK}, {@link\n * Constants#SCROLLER_MODE_SPRING}, {@link Constants#SCROLLER_MODE_SPRING_BACK}.\n */\n public byte getScrollMode() {\n return mScrollChecker.mMode;\n }\n\n @Override\n protected ViewGroup.LayoutParams generateDefaultLayoutParams() {\n return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);\n }\n\n @Override\n protected boolean checkLayoutParams(ViewGroup.LayoutParams lp) {\n return lp instanceof LayoutParams;\n }\n\n @Override\n protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) {\n if (lp instanceof LayoutParams) {\n return lp;\n } else if (lp instanceof MarginLayoutParams) {\n return new LayoutParams((MarginLayoutParams) lp);\n } else {\n return new LayoutParams(lp);\n }\n }\n\n @Override\n public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {\n return new LayoutParams(getContext(), attrs);\n }\n\n /**\n * Set the pinned header view resource id\n *\n * @param resId Resource id\n */\n public void setStickyHeaderResId(@IdRes int resId) {\n if (mStickyHeaderResId != resId) {\n mStickyHeaderResId = resId;\n mStickyHeaderView = null;\n ensureTargetView();\n }\n }\n\n /**\n * Set the pinned footer view resource id\n *\n * @param resId Resource id\n */\n public void setStickyFooterResId(@IdRes int resId) {\n if (mStickyFooterResId != resId) {\n mStickyFooterResId = resId;\n mStickyFooterView = null;\n ensureTargetView();\n }\n }\n\n public boolean onFling(float vx, final float vy, boolean nested) {\n if (sDebug) {\n Log.d(\n TAG,\n String.format(\n \"onFling() velocityX: %f, velocityY: %f, nested: %b\", vx, vy, nested));\n }\n if ((isNeedInterceptTouchEvent() || isCanNotAbortOverScrolling())) {\n return true;\n }\n if (mPreventForAnotherDirection) {\n return nested && dispatchNestedPreFling(-vx, -vy);\n }\n float realVelocity = isVerticalOrientation() ? vy : vx;\n if (!mIndicator.isAlreadyHere(IIndicator.START_POS)) {\n if (!isEnabledPinContentView()) {\n if (Math.abs(realVelocity) > 2000) {\n if ((realVelocity > 0 && isMovingHeader())\n || (realVelocity < 0 && isMovingFooter())) {\n if (isEnabledOverScroll()) {\n if (isDisabledLoadMoreWhenContentNotFull()\n && !isNotYetInEdgeCannotMoveFooter()\n && !isNotYetInEdgeCannotMoveHeader()) {\n return true;\n }\n boolean invert = realVelocity < 0;\n realVelocity = (float) Math.pow(Math.abs(realVelocity), .5f);\n mScrollChecker.startPreFling(invert ? -realVelocity : realVelocity);\n }\n } else {\n if (mScrollChecker.getFinalY(realVelocity) > mIndicator.getCurrentPos()) {\n if (!isEnabledPerformFreshWhenFling()) {\n mScrollChecker.startPreFling(realVelocity);\n } else if (isMovingHeader()\n && (isDisabledPerformRefresh()\n || mIndicator.getCurrentPos()\n < mIndicator.getOffsetToRefresh())) {\n mScrollChecker.startPreFling(realVelocity);\n } else if (isMovingFooter()\n && (isDisabledPerformLoadMore()\n || mIndicator.getCurrentPos()\n < mIndicator.getOffsetToLoadMore())) {\n mScrollChecker.startPreFling(realVelocity);\n }\n }\n }\n }\n return true;\n }\n if (nested) {\n return dispatchNestedPreFling(-vx, -vy);\n } else {\n return false;\n }\n } else {\n tryToResetMovingStatus();\n if (isEnabledOverScroll()\n && (!isEnabledPinContentView()\n || ((realVelocity >= 0 || !isDisabledLoadMore())\n && (realVelocity <= 0 || !isDisabledRefresh())))) {\n if (isDisabledLoadMoreWhenContentNotFull()\n && realVelocity < 0\n && !isNotYetInEdgeCannotMoveHeader()\n && !isNotYetInEdgeCannotMoveFooter()) {\n return nested && dispatchNestedPreFling(-vx, -vy);\n }\n mScrollChecker.startFling(realVelocity);\n if (!nested && isEnabledOldTouchHandling()) {\n if (mDelayToDispatchNestedFling == null)\n mDelayToDispatchNestedFling = new DelayToDispatchNestedFling();\n mDelayToDispatchNestedFling.mLayout = this;\n mDelayToDispatchNestedFling.mVelocity = (int) realVelocity;\n ViewCompat.postOnAnimation(this, mDelayToDispatchNestedFling);\n invalidate();\n return true;\n }\n }\n invalidate();\n }\n return nested && dispatchNestedPreFling(-vx, -vy);\n }\n\n @Override\n public boolean onStartNestedScroll(\n @NonNull View child, @NonNull View target, int nestedScrollAxes) {\n return onStartNestedScroll(child, target, nestedScrollAxes, ViewCompat.TYPE_TOUCH);\n }\n\n @Override\n public boolean onStartNestedScroll(\n @NonNull View child, @NonNull View target, int axes, int type) {\n if (sDebug) {\n Log.d(TAG, String.format(\"onStartNestedScroll(): axes: %d, type: %d\", axes, type));\n }\n return isEnabled()\n && isNestedScrollingEnabled()\n && mTargetView != null\n && (axes & getNestedScrollAxes()) != 0\n && !(type == ViewCompat.TYPE_NON_TOUCH && !isEnabledOverScroll());\n }\n\n @Override\n public void onNestedScrollAccepted(@NonNull View child, @NonNull View target, int axes) {\n onNestedScrollAccepted(child, target, axes, ViewCompat.TYPE_TOUCH);\n }\n\n @Override\n public void onNestedScrollAccepted(\n @NonNull View child, @NonNull View target, int axes, int type) {\n if (sDebug) {\n Log.d(TAG, String.format(\"onNestedScrollAccepted(): axes: %d, type: %d\", axes, type));\n }\n // Reset the counter of how much leftover scroll needs to be consumed.\n mNestedScrollingParentHelper.onNestedScrollAccepted(child, target, axes, type);\n // Dispatch up to the nested parent\n startNestedScroll(axes & getNestedScrollAxes(), type);\n mNestedTouchScrolling = type == ViewCompat.TYPE_TOUCH;\n mLastNestedType = type;\n mNestedScrolling = true;\n }\n\n @Override\n public int getNestedScrollAxes() {\n return mLayoutManager == null\n ? ViewCompat.SCROLL_AXIS_NONE\n : mLayoutManager.getOrientation() == LayoutManager.VERTICAL\n ? ViewCompat.SCROLL_AXIS_VERTICAL\n : ViewCompat.SCROLL_AXIS_HORIZONTAL;\n }\n\n @Override\n public void onNestedPreScroll(@NonNull View target, int dx, int dy, @NonNull int[] consumed) {\n onNestedPreScroll(target, dx, dy, consumed, ViewCompat.TYPE_TOUCH);\n }\n\n @Override\n public void onNestedPreScroll(\n @NonNull View target, int dx, int dy, @NonNull int[] consumed, int type) {\n final boolean isVerticalOrientation = isVerticalOrientation();\n if (type == ViewCompat.TYPE_TOUCH) {\n if (tryToFilterTouchEvent(null)) {\n if (isVerticalOrientation) {\n consumed[1] = dy;\n } else {\n consumed[0] = dx;\n }\n } else {\n mScrollChecker.stop();\n final int distance = isVerticalOrientation ? dy : dx;\n if (distance > 0\n && !isDisabledRefresh()\n && !(isEnabledPinRefreshViewWhileLoading() && isRefreshing())\n && !isNotYetInEdgeCannotMoveHeader()) {\n if (!mIndicator.isAlreadyHere(IIndicator.START_POS) && isMovingHeader()) {\n mIndicatorSetter.onFingerMove(\n mIndicator.getLastMovePoint()[0] - dx,\n mIndicator.getLastMovePoint()[1] - dy);\n moveHeaderPos(mIndicator.getOffset());\n if (isVerticalOrientation) {\n consumed[1] = dy;\n } else {\n consumed[0] = dx;\n }\n } else {\n if (isVerticalOrientation) {\n mIndicatorSetter.onFingerMove(\n mIndicator.getLastMovePoint()[0] - dx,\n mIndicator.getLastMovePoint()[1]);\n } else {\n mIndicatorSetter.onFingerMove(\n mIndicator.getLastMovePoint()[0],\n mIndicator.getLastMovePoint()[1] - dy);\n }\n }\n } else if (distance < 0\n && !isDisabledLoadMore()\n && !(isEnabledPinRefreshViewWhileLoading() && isLoadingMore())\n && !isNotYetInEdgeCannotMoveFooter()) {\n if (!mIndicator.isAlreadyHere(IIndicator.START_POS) && isMovingFooter()) {\n mIndicatorSetter.onFingerMove(\n mIndicator.getLastMovePoint()[0] - dx,\n mIndicator.getLastMovePoint()[1] - dy);\n moveFooterPos(mIndicator.getOffset());\n if (isVerticalOrientation) {\n consumed[1] = dy;\n } else {\n consumed[0] = dx;\n }\n } else {\n if (isVerticalOrientation) {\n mIndicatorSetter.onFingerMove(\n mIndicator.getLastMovePoint()[0] - dx,\n mIndicator.getLastMovePoint()[1]);\n } else {\n mIndicatorSetter.onFingerMove(\n mIndicator.getLastMovePoint()[0],\n mIndicator.getLastMovePoint()[1] - dy);\n }\n }\n }\n }\n tryToResetMovingStatus();\n }\n // Now let our nested parent consume the leftovers\n final int[] parentConsumed = mParentScrollConsumed;\n parentConsumed[0] = 0;\n parentConsumed[1] = 0;\n if (dispatchNestedPreScroll(\n dx - consumed[0], dy - consumed[1], parentConsumed, null, type)) {\n consumed[0] += parentConsumed[0];\n consumed[1] += parentConsumed[1];\n } else if (type == ViewCompat.TYPE_NON_TOUCH) {\n if (!isMovingContent() && !isEnabledPinContentView()) {\n if (isVerticalOrientation) {\n parentConsumed[1] = dy;\n } else {\n parentConsumed[0] = dx;\n }\n consumed[0] += parentConsumed[0];\n consumed[1] += parentConsumed[1];\n }\n }\n if (sDebug) {\n Log.d(\n TAG,\n String.format(\n \"onNestedPreScroll(): dx: %d, dy: %d, consumed: %s, type: %d\",\n dx, dy, Arrays.toString(consumed), type));\n }\n }\n\n @Override\n public void onNestedScroll(\n @NonNull View target,\n int dxConsumed,\n int dyConsumed,\n int dxUnconsumed,\n int dyUnconsumed) {\n onNestedScroll(\n target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, ViewCompat.TYPE_TOUCH);\n }\n\n @Override\n public void onNestedScroll(\n @NonNull View target,\n int dxConsumed,\n int dyConsumed,\n int dxUnconsumed,\n int dyUnconsumed,\n int type) {\n mCachedIntPoint[0] = 0;\n mCachedIntPoint[1] = 0;\n onNestedScroll(\n target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type, mCachedIntPoint);\n }\n\n @Override\n public void onNestedScroll(\n @NonNull View target,\n int dxConsumed,\n int dyConsumed,\n int dxUnconsumed,\n int dyUnconsumed,\n int type,\n @NonNull int[] consumed) {\n // Dispatch up to the nested parent first\n dispatchNestedScroll(\n dxConsumed,\n dyConsumed,\n dxUnconsumed,\n dyUnconsumed,\n mParentOffsetInWindow,\n type,\n consumed);\n if (sDebug) {\n Log.d(\n TAG,\n String.format(\n \"onNestedScroll(): dxConsumed: %d, dyConsumed: %d, dxUnconsumed: %d\"\n + \" dyUnconsumed: %d, type: %d, consumed: %s\",\n dxConsumed,\n dyConsumed,\n dxUnconsumed,\n dyUnconsumed,\n type,\n Arrays.toString(consumed)));\n }\n final boolean isVerticalOrientation = isVerticalOrientation();\n if (isVerticalOrientation) {\n if (dyUnconsumed == 0 || consumed[1] == dyUnconsumed) {\n onNestedScrollChanged(true);\n return;\n }\n } else {\n if (dxUnconsumed == 0 || consumed[0] == dxUnconsumed) {\n onNestedScrollChanged(true);\n return;\n }\n }\n if (type == ViewCompat.TYPE_TOUCH) {\n if (tryToFilterTouchEvent(null)) {\n return;\n }\n final int dx = dxUnconsumed + mParentOffsetInWindow[0] - consumed[0];\n final int dy = dyUnconsumed + mParentOffsetInWindow[1] - consumed[1];\n final int distance = isVerticalOrientation ? dy : dx;\n if (distance < 0\n && !isDisabledRefresh()\n && !isNotYetInEdgeCannotMoveHeader()\n && !(isEnabledPinRefreshViewWhileLoading() && isRefreshing())) {\n mIndicatorSetter.onFingerMove(\n mIndicator.getLastMovePoint()[0] - dx,\n mIndicator.getLastMovePoint()[1] - dy);\n moveHeaderPos(mIndicator.getOffset());\n if (isVerticalOrientation) {\n consumed[1] += dy;\n } else {\n consumed[0] += dx;\n }\n } else if (distance > 0\n && !isDisabledLoadMore()\n && !isNotYetInEdgeCannotMoveFooter()\n && !(isDisabledLoadMoreWhenContentNotFull()\n && !isNotYetInEdgeCannotMoveHeader()\n && mIndicator.isAlreadyHere(IIndicator.START_POS))\n && !(isEnabledPinRefreshViewWhileLoading() && isLoadingMore())) {\n mIndicatorSetter.onFingerMove(\n mIndicator.getLastMovePoint()[0] - dx,\n mIndicator.getLastMovePoint()[1] - dy);\n moveFooterPos(mIndicator.getOffset());\n if (isVerticalOrientation) {\n consumed[1] += dy;\n } else {\n consumed[0] += dx;\n }\n }\n tryToResetMovingStatus();\n }\n if (dxConsumed != 0 || dyConsumed != 0 || consumed[0] != 0 || consumed[1] != 0) {\n onNestedScrollChanged(true);\n }\n }\n\n @Override\n public void onStopNestedScroll(@NonNull View target) {\n onStopNestedScroll(target, ViewCompat.TYPE_TOUCH);\n }\n\n @Override\n public void onStopNestedScroll(@NonNull View target, int type) {\n if (sDebug) {\n Log.d(TAG, String.format(\"onStopNestedScroll() type: %d\", type));\n }\n mNestedScrollingParentHelper.onStopNestedScroll(target, type);\n if (mLastNestedType == type) {\n mNestedScrolling = false;\n }\n mNestedTouchScrolling = false;\n mIsInterceptTouchEventInOnceTouch = isNeedInterceptTouchEvent();\n mIsLastOverScrollCanNotAbort = isCanNotAbortOverScrolling();\n // Dispatch up our nested parent\n getScrollingChildHelper().stopNestedScroll(type);\n if (!isAutoRefresh() && type == ViewCompat.TYPE_TOUCH && !mLastEventIsActionDown) {\n mIndicatorSetter.onFingerUp();\n onFingerUp();\n }\n onNestedScrollChanged(true);\n }\n\n @Override\n public boolean isNestedScrollingEnabled() {\n return getScrollingChildHelper().isNestedScrollingEnabled();\n }\n\n @Override\n public void setNestedScrollingEnabled(boolean enabled) {\n getScrollingChildHelper().setNestedScrollingEnabled(enabled);\n }\n\n @Override\n public boolean startNestedScroll(int axes) {\n return getScrollingChildHelper().startNestedScroll(axes);\n }\n\n @Override\n public boolean startNestedScroll(int axes, int type) {\n return getScrollingChildHelper().startNestedScroll(axes, type);\n }\n\n @Override\n public void stopNestedScroll() {\n stopNestedScroll(ViewCompat.TYPE_TOUCH);\n }\n\n @Override\n public void stopNestedScroll(int type) {\n if (sDebug) {\n Log.d(TAG, String.format(\"stopNestedScroll() type: %d\", type));\n }\n final View targetView = getScrollTargetView();\n if (targetView != null) {\n ViewCompat.stopNestedScroll(targetView, type);\n }\n getScrollingChildHelper().stopNestedScroll(type);\n }\n\n @Override\n public boolean hasNestedScrollingParent() {\n return getScrollingChildHelper().hasNestedScrollingParent();\n }\n\n @Override\n public boolean hasNestedScrollingParent(int type) {\n return getScrollingChildHelper().hasNestedScrollingParent(type);\n }\n\n @Override\n public boolean dispatchNestedScroll(\n int dxConsumed,\n int dyConsumed,\n int dxUnconsumed,\n int dyUnconsumed,\n int[] offsetInWindow) {\n return getScrollingChildHelper()\n .dispatchNestedScroll(\n dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, offsetInWindow);\n }\n\n @Override\n public boolean dispatchNestedScroll(\n int dxConsumed,\n int dyConsumed,\n int dxUnconsumed,\n int dyUnconsumed,\n @Nullable int[] offsetInWindow,\n int type) {\n return getScrollingChildHelper()\n .dispatchNestedScroll(\n dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, offsetInWindow, type);\n }\n\n @Override\n public void dispatchNestedScroll(\n int dxConsumed,\n int dyConsumed,\n int dxUnconsumed,\n int dyUnconsumed,\n @Nullable int[] offsetInWindow,\n int type,\n @NonNull int[] consumed) {\n getScrollingChildHelper()\n .dispatchNestedScroll(\n dxConsumed,\n dyConsumed,\n dxUnconsumed,\n dyUnconsumed,\n offsetInWindow,\n type,\n consumed);\n }\n\n @Override\n public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) {\n return getScrollingChildHelper().dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow);\n }\n\n @Override\n public boolean dispatchNestedPreScroll(\n int dx, int dy, @Nullable int[] consumed, @Nullable int[] offsetInWindow, int type) {\n return getScrollingChildHelper()\n .dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow, type);\n }\n\n @Override\n public boolean onNestedPreFling(@NonNull View target, float velocityX, float velocityY) {\n return onFling(-velocityX, -velocityY, true);\n }\n\n @Override\n public boolean onNestedFling(\n @NonNull View target, float velocityX, float velocityY, boolean consumed) {\n return dispatchNestedFling(velocityX, velocityY, consumed);\n }\n\n @Override\n public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {\n return getScrollingChildHelper().dispatchNestedFling(velocityX, velocityY, consumed);\n }\n\n @Override\n public boolean dispatchNestedPreFling(float velocityX, float velocityY) {\n return getScrollingChildHelper().dispatchNestedPreFling(velocityX, velocityY);\n }\n\n @Override\n public void computeScroll() {\n if (mNestedScrolling || !isMovingContent()) {\n return;\n }\n onNestedScrollChanged(true);\n }\n\n @Override\n public boolean canScrollVertically(int direction) {\n if (isVerticalOrientation()) {\n if (mAppBarLayoutUtil == null || mAppBarLayoutUtil != mInEdgeCanMoveHeaderCallBack) {\n if (direction < 0) {\n return super.canScrollVertically(direction) || isNotYetInEdgeCannotMoveHeader();\n } else {\n return super.canScrollVertically(direction) || isNotYetInEdgeCannotMoveFooter();\n }\n }\n }\n return super.canScrollVertically(direction);\n }\n\n @Override\n public boolean canScrollHorizontally(int direction) {\n if (!isVerticalOrientation()) {\n if (direction < 0) {\n return super.canScrollHorizontally(direction) || isNotYetInEdgeCannotMoveHeader();\n } else {\n return super.canScrollHorizontally(direction) || isNotYetInEdgeCannotMoveFooter();\n }\n }\n return super.canScrollHorizontally(direction);\n }\n\n public void onNestedScrollChanged(boolean compute) {\n if (mNeedFilterScrollEvent) {\n return;\n }\n tryScrollToPerformAutoRefresh();\n if (compute) {\n mScrollChecker.computeScrollOffset();\n }\n }\n\n public boolean isVerticalOrientation() {\n return mLayoutManager == null || mLayoutManager.getOrientation() == LayoutManager.VERTICAL;\n }\n\n /** Check the Z-Axis relationships of the views need to be rearranged */\n protected void checkViewsZAxisNeedReset() {\n final int count = getChildCount();\n if (mViewsZAxisNeedReset && count > 0 && (mHeaderView != null || mFooterView != null)) {\n mCachedViews.clear();\n if (mHeaderView != null && !isEnabledHeaderDrawerStyle()) {\n mCachedViews.add(mHeaderView.getView());\n }\n if (mFooterView != null && !isEnabledFooterDrawerStyle()) {\n mCachedViews.add(mFooterView.getView());\n }\n for (int i = count - 1; i >= 0; i--) {\n View view = getChildAt(i);\n if (!(view instanceof IRefreshView)) {\n mCachedViews.add(view);\n }\n }\n final int viewCount = mCachedViews.size();\n if (viewCount > 0) {\n for (int i = viewCount - 1; i >= 0; i--) {\n bringChildToFront(mCachedViews.get(i));\n }\n }\n mCachedViews.clear();\n }\n mViewsZAxisNeedReset = false;\n }\n\n protected void reset() {\n if (mStatus != SR_STATUS_INIT) {\n if (isRefreshing() || isLoadingMore()) {\n notifyUIRefreshComplete(false, false, true);\n }\n if (mHeaderView != null) {\n mHeaderView.onReset(this);\n }\n if (mFooterView != null) {\n mFooterView.onReset(this);\n }\n if (!mIndicator.isAlreadyHere(IIndicator.START_POS)) {\n mScrollChecker.scrollTo(IIndicator.START_POS, 0);\n }\n mScrollChecker.stop();\n mScrollChecker.setInterpolator(mSpringInterpolator);\n final byte old = mStatus;\n mStatus = SR_STATUS_INIT;\n notifyStatusChanged(old, mStatus);\n mAutomaticActionTriggered = true;\n mLayoutManager.resetLayout(\n mHeaderView, mFooterView, mStickyHeaderView, mStickyFooterView, mTargetView);\n removeCallbacks(mDelayToRefreshComplete);\n removeCallbacks(mDelayToDispatchNestedFling);\n removeCallbacks(mDelayToPerformAutoRefresh);\n if (sDebug) {\n Log.d(TAG, \"reset()\");\n }\n }\n }\n\n protected void tryToPerformAutoRefresh() {\n if (!mAutomaticActionTriggered) {\n if (sDebug) Log.d(TAG, \"tryToPerformAutoRefresh()\");\n if (isHeaderInProcessing() && isMovingHeader()) {\n if (mHeaderView == null || mIndicator.getHeaderHeight() <= 0) {\n return;\n }\n scrollToTriggeredAutomatic(true);\n } else if (isFooterInProcessing() && isMovingFooter()) {\n if (mFooterView == null || mIndicator.getFooterHeight() <= 0) {\n return;\n }\n scrollToTriggeredAutomatic(false);\n }\n }\n }\n\n private void ensureTargetView() {\n boolean ensureStickyHeader = mStickyHeaderView == null && mStickyHeaderResId != NO_ID;\n boolean ensureStickyFooter = mStickyFooterView == null && mStickyFooterResId != NO_ID;\n boolean ensureTarget = mTargetView == null && mContentResId != NO_ID;\n final int count = getChildCount();\n if (ensureStickyHeader || ensureStickyFooter || ensureTarget) {\n for (int i = count - 1; i >= 0; i--) {\n View child = getChildAt(i);\n if (ensureStickyHeader && child.getId() == mStickyHeaderResId) {\n mStickyHeaderView = child;\n ensureStickyHeader = false;\n } else if (ensureStickyFooter && child.getId() == mStickyFooterResId) {\n mStickyFooterView = child;\n ensureStickyFooter = false;\n } else if (ensureTarget) {\n if (mContentResId == child.getId()) {\n mTargetView = child;\n View view = ensureScrollTargetView(child, true, 0, 0);\n if (view != null && view != child) {\n mAutoFoundScrollTargetView = view;\n }\n ensureTarget = false;\n } else if (child instanceof ViewGroup) {\n final View view =\n foundViewInViewGroupById((ViewGroup) child, mContentResId);\n if (view != null) {\n mTargetView = child;\n mScrollTargetView = view;\n ensureTarget = false;\n }\n }\n } else if (!ensureStickyHeader && !ensureStickyFooter) {\n break;\n }\n }\n }\n if (mTargetView == null) {\n for (int i = count - 1; i >= 0; i--) {\n View child = getChildAt(i);\n if (child.getVisibility() == VISIBLE\n && !(child instanceof IRefreshView)\n && child != mStickyHeaderView\n && child != mStickyFooterView) {\n View view = ensureScrollTargetView(child, true, 0, 0);\n if (view != null) {\n mTargetView = child;\n if (view != child) {\n mAutoFoundScrollTargetView = view;\n }\n break;\n } else {\n mTargetView = child;\n break;\n }\n }\n }\n } else if (mTargetView.getParent() == null) {\n mTargetView = null;\n ensureTargetView();\n mLayoutManager.offsetChild(\n mHeaderView, mFooterView, mStickyHeaderView, mStickyFooterView, mTargetView, 0);\n return;\n }\n mHeaderView = getHeaderView();\n mFooterView = getFooterView();\n }\n\n /**\n * Returns true if a child view contains the specified point when transformed into its\n * coordinate space.\n *\n * @see ViewGroup source code\n */\n protected boolean isTransformedTouchPointInView(float x, float y, ViewGroup group, View child) {\n if (child.getVisibility() != VISIBLE\n || child.getAnimation() != null\n || child instanceof IRefreshView) {\n return false;\n }\n mCachedFloatPoint[0] = x;\n mCachedFloatPoint[1] = y;\n transformPointToViewLocal(group, mCachedFloatPoint, child);\n final boolean isInView =\n mCachedFloatPoint[0] >= 0\n && mCachedFloatPoint[1] >= 0\n && mCachedFloatPoint[0] < child.getWidth()\n && mCachedFloatPoint[1] < child.getHeight();\n if (isInView) {\n mCachedFloatPoint[0] = mCachedFloatPoint[0] - x;\n mCachedFloatPoint[1] = mCachedFloatPoint[1] - y;\n }\n return isInView;\n }\n\n public void transformPointToViewLocal(ViewGroup group, float[] point, View child) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1\n && Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) {\n group.transformPointToViewLocal(point, child);\n } else {\n // When the system version is lower than LOLLIPOP_MR1, the system source code has no\n // transformPointToViewLocal method. We need to be compatible with it.\n // When the system version is larger than R, the transformPointToViewLocal method has\n // been unavailable. We need to be compatible with it.\n point[0] += group.getScrollX() - child.getLeft();\n point[1] += group.getScrollY() - child.getTop();\n Matrix matrix = child.getMatrix();\n if (!matrix.isIdentity()) {\n mCachedMatrix.reset();\n if (matrix.invert(mCachedMatrix)) {\n mCachedMatrix.mapPoints(point);\n }\n }\n }\n }\n\n protected View ensureScrollTargetView(View target, boolean noTransform, float x, float y) {\n if (target instanceof IRefreshView\n || target.getVisibility() != VISIBLE\n || target.getAnimation() != null) {\n return null;\n }\n if (isScrollingView(target)) {\n return target;\n }\n if (target instanceof ViewGroup) {\n ViewGroup group = (ViewGroup) target;\n final int count = group.getChildCount();\n for (int i = count - 1; i >= 0; i--) {\n View child = group.getChildAt(i);\n if (noTransform || isTransformedTouchPointInView(x, y, group, child)) {\n View view =\n ensureScrollTargetView(\n child,\n noTransform,\n x + mCachedFloatPoint[0],\n y + mCachedFloatPoint[1]);\n if (view != null) {\n return view;\n }\n }\n }\n }\n return null;\n }\n\n protected boolean isWrappedByScrollingView(ViewParent parent) {\n if (parent instanceof View) {\n if (isScrollingView((View) parent)) {\n return true;\n }\n return isWrappedByScrollingView(parent.getParent());\n }\n return false;\n }\n\n protected boolean isScrollingView(View view) {\n return ScrollCompat.isScrollingView(view);\n }\n\n protected boolean processDispatchTouchEvent(MotionEvent ev) {\n final int action = ev.getAction() & MotionEvent.ACTION_MASK;\n if (sDebug) {\n Log.d(TAG, String.format(\"processDispatchTouchEvent(): action: %d\", action));\n }\n if (mVelocityTracker == null) {\n mVelocityTracker = VelocityTracker.obtain();\n }\n mVelocityTracker.addMovement(ev);\n final boolean oldTouchHanding = isEnabledOldTouchHandling();\n switch (action) {\n case MotionEvent.ACTION_UP:\n final int pointerId = ev.getPointerId(0);\n mVelocityTracker.computeCurrentVelocity(1000, mMaximumFlingVelocity);\n float vy = mVelocityTracker.getYVelocity(pointerId);\n float vx = mVelocityTracker.getXVelocity(pointerId);\n if (Math.abs(vx) >= mMinimumFlingVelocity\n || Math.abs(vy) >= mMinimumFlingVelocity) {\n final boolean handler = onFling(vx, vy, false);\n final View targetView = getScrollTargetView();\n if (handler\n && !ViewCatcherUtil.isCoordinatorLayout(mTargetView)\n && targetView != null\n && !ViewCatcherUtil.isViewPager(targetView)\n && !(targetView.getParent() instanceof View\n && ViewCatcherUtil.isViewPager(\n (View) targetView.getParent()))) {\n ev.setAction(MotionEvent.ACTION_CANCEL);\n }\n }\n case MotionEvent.ACTION_CANCEL:\n mIndicatorSetter.onFingerUp();\n mPreventForAnotherDirection = false;\n mDealAnotherDirectionMove = false;\n if (isNeedFilterTouchEvent()) {\n mIsInterceptTouchEventInOnceTouch = false;\n if (mIsLastOverScrollCanNotAbort\n && mIndicator.isAlreadyHere(IIndicator.START_POS)) {\n mScrollChecker.stop();\n }\n mIsLastOverScrollCanNotAbort = false;\n } else {\n mIsInterceptTouchEventInOnceTouch = false;\n mIsLastOverScrollCanNotAbort = false;\n if (mIndicator.hasLeftStartPosition()) {\n onFingerUp();\n } else {\n notifyFingerUp();\n }\n }\n mHasSendCancelEvent = false;\n mVelocityTracker.clear();\n break;\n case MotionEvent.ACTION_POINTER_UP:\n final int pointerIndex =\n (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK)\n >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;\n if (ev.getPointerId(pointerIndex) == mTouchPointerId) {\n // Pick a new pointer to pick up the slack.\n final int newIndex = pointerIndex == 0 ? 1 : 0;\n mTouchPointerId = ev.getPointerId(newIndex);\n mIndicatorSetter.onFingerMove(ev.getX(newIndex), ev.getY(newIndex));\n }\n final int count = ev.getPointerCount();\n mVelocityTracker.computeCurrentVelocity(1000, mMaximumFlingVelocity);\n final int upIndex = ev.getActionIndex();\n final int id1 = ev.getPointerId(upIndex);\n final float x1 = mVelocityTracker.getXVelocity(id1);\n final float y1 = mVelocityTracker.getYVelocity(id1);\n for (int i = 0; i < count; i++) {\n if (i == upIndex) continue;\n final int id2 = ev.getPointerId(i);\n final float x = x1 * mVelocityTracker.getXVelocity(id2);\n final float y = y1 * mVelocityTracker.getYVelocity(id2);\n final float dot = x + y;\n if (dot < 0) {\n mVelocityTracker.clear();\n break;\n }\n }\n break;\n case MotionEvent.ACTION_POINTER_DOWN:\n mTouchPointerId = ev.getPointerId(ev.getActionIndex());\n mIndicatorSetter.onFingerMove(\n ev.getX(ev.getActionIndex()), ev.getY(ev.getActionIndex()));\n break;\n case MotionEvent.ACTION_DOWN:\n mIndicatorSetter.onFingerUp();\n mTouchPointerId = ev.getPointerId(0);\n mIndicatorSetter.onFingerDown(ev.getX(), ev.getY());\n mIsInterceptTouchEventInOnceTouch = isNeedInterceptTouchEvent();\n mIsLastOverScrollCanNotAbort = isCanNotAbortOverScrolling();\n if (!isNeedFilterTouchEvent()) {\n mScrollChecker.stop();\n }\n mHasSendDownEvent = false;\n mPreventForAnotherDirection = false;\n if (mScrollTargetView == null) {\n View view = ensureScrollTargetView(this, false, ev.getX(), ev.getY());\n if (view != null && mTargetView != view && mAutoFoundScrollTargetView != view) {\n mAutoFoundScrollTargetView = view;\n }\n } else {\n mAutoFoundScrollTargetView = null;\n }\n removeCallbacks(mDelayToDispatchNestedFling);\n dispatchTouchEventSuper(ev);\n return true;\n case MotionEvent.ACTION_MOVE:\n final int index = ev.findPointerIndex(mTouchPointerId);\n if (index < 0) {\n Log.e(\n TAG,\n String.format(\n \"Error processing scroll; pointer index for id %d not found. Did any MotionEvents get skipped?\",\n mTouchPointerId));\n return super.dispatchTouchEvent(ev);\n }\n if (!mIndicator.hasTouched()) {\n mIndicatorSetter.onFingerDown(ev.getX(index), ev.getY(index));\n }\n mLastMoveEvent = ev;\n if (tryToFilterTouchEvent(ev)) {\n return true;\n }\n tryToResetMovingStatus();\n if (!mDealAnotherDirectionMove) {\n final float[] pressDownPoint = mIndicator.getFingerDownPoint();\n final float offsetX = ev.getX(index) - pressDownPoint[0];\n final float offsetY = ev.getY(index) - pressDownPoint[1];\n tryToDealAnotherDirectionMove(offsetX, offsetY);\n if (mDealAnotherDirectionMove && oldTouchHanding) {\n mIndicatorSetter.onFingerDown(\n ev.getX(index) - offsetX / 10, ev.getY(index) - offsetY / 10);\n }\n final ViewParent parent = getParent();\n if (!isWrappedByScrollingView(parent)) {\n parent.requestDisallowInterceptTouchEvent(true);\n }\n }\n final boolean canNotChildScrollDown = !isNotYetInEdgeCannotMoveFooter();\n final boolean canNotChildScrollUp = !isNotYetInEdgeCannotMoveHeader();\n if (mPreventForAnotherDirection) {\n if (mDealAnotherDirectionMove && isMovingHeader() && !canNotChildScrollUp) {\n mPreventForAnotherDirection = false;\n } else if (mDealAnotherDirectionMove\n && isMovingFooter()\n && !canNotChildScrollDown) {\n mPreventForAnotherDirection = false;\n } else {\n return super.dispatchTouchEvent(ev);\n }\n }\n mIndicatorSetter.onFingerMove(ev.getX(index), ev.getY(index));\n final float offset = mIndicator.getOffset();\n boolean movingDown = offset > 0;\n if (!movingDown\n && isDisabledLoadMoreWhenContentNotFull()\n && mIndicator.isAlreadyHere(IIndicator.START_POS)\n && canNotChildScrollDown\n && canNotChildScrollUp) {\n return dispatchTouchEventSuper(ev);\n }\n boolean canMoveUp = isMovingHeader() && mIndicator.hasLeftStartPosition();\n boolean canMoveDown = isMovingFooter() && mIndicator.hasLeftStartPosition();\n boolean canHeaderMoveDown = canNotChildScrollUp && !isDisabledRefresh();\n boolean canFooterMoveUp = canNotChildScrollDown && !isDisabledLoadMore();\n if (!canMoveUp && !canMoveDown) {\n if ((movingDown && !canHeaderMoveDown) || (!movingDown && !canFooterMoveUp)) {\n if (isLoadingMore() && mIndicator.hasLeftStartPosition()) {\n moveFooterPos(offset);\n if (oldTouchHanding) {\n return true;\n }\n } else if (isRefreshing() && mIndicator.hasLeftStartPosition()) {\n moveHeaderPos(offset);\n if (oldTouchHanding) {\n return true;\n }\n }\n } else if (movingDown) {\n if (!isDisabledRefresh()) {\n moveHeaderPos(offset);\n if (oldTouchHanding) {\n return true;\n }\n }\n } else if (!isDisabledLoadMore()) {\n moveFooterPos(offset);\n if (oldTouchHanding) {\n return true;\n }\n }\n } else if (canMoveUp) {\n if (isDisabledRefresh()) {\n return dispatchTouchEventSuper(ev);\n }\n if ((!canHeaderMoveDown && movingDown)) {\n if (oldTouchHanding) {\n sendDownEvent(ev);\n return true;\n }\n return dispatchTouchEventSuper(ev);\n }\n moveHeaderPos(offset);\n if (oldTouchHanding) {\n return true;\n }\n } else {\n if (isDisabledLoadMore()) {\n return dispatchTouchEventSuper(ev);\n }\n if ((!canFooterMoveUp && !movingDown)) {\n if (oldTouchHanding) {\n sendDownEvent(ev);\n return true;\n }\n return dispatchTouchEventSuper(ev);\n }\n moveFooterPos(offset);\n if (oldTouchHanding) {\n return true;\n }\n }\n }\n return dispatchTouchEventSuper(ev);\n }\n\n protected void tryToDealAnotherDirectionMove(float offsetX, float offsetY) {\n if (isDisabledWhenAnotherDirectionMove()) {\n if ((Math.abs(offsetX) >= mTouchSlop && Math.abs(offsetX) > Math.abs(offsetY))) {\n mPreventForAnotherDirection = true;\n mDealAnotherDirectionMove = true;\n } else if (Math.abs(offsetX) < mTouchSlop && Math.abs(offsetY) < mTouchSlop) {\n mDealAnotherDirectionMove = false;\n mPreventForAnotherDirection = true;\n } else {\n mDealAnotherDirectionMove = true;\n mPreventForAnotherDirection = false;\n }\n } else {\n mPreventForAnotherDirection =\n Math.abs(offsetX) < mTouchSlop && Math.abs(offsetY) < mTouchSlop;\n if (!mPreventForAnotherDirection) {\n mDealAnotherDirectionMove = true;\n }\n }\n }\n\n protected boolean tryToFilterTouchEvent(MotionEvent ev) {\n if (mIsInterceptTouchEventInOnceTouch) {\n if ((!isAutoRefresh()\n && mIndicator.isAlreadyHere(IIndicator.START_POS)\n && !mScrollChecker.mIsScrolling)\n || (isAutoRefresh() && (isRefreshing() || isLoadingMore()))) {\n mScrollChecker.stop();\n if (ev != null) {\n makeNewTouchDownEvent(ev);\n }\n mIsInterceptTouchEventInOnceTouch = false;\n }\n return true;\n }\n if (mIsLastOverScrollCanNotAbort) {\n if (mIndicator.isAlreadyHere(IIndicator.START_POS) && !mScrollChecker.mIsScrolling) {\n if (ev != null) {\n makeNewTouchDownEvent(ev);\n }\n mIsLastOverScrollCanNotAbort = false;\n }\n return true;\n }\n if (mIsSpringBackCanNotBeInterrupted) {\n if (isEnabledNoMoreDataAndNoSpringBack()) {\n mIsSpringBackCanNotBeInterrupted = false;\n return false;\n }\n if (mIndicator.isAlreadyHere(IIndicator.START_POS) && !mScrollChecker.mIsScrolling) {\n if (ev != null) {\n makeNewTouchDownEvent(ev);\n }\n mIsSpringBackCanNotBeInterrupted = false;\n }\n return true;\n }\n return false;\n }\n\n private NestedScrollingChildHelper getScrollingChildHelper() {\n if (mNestedScrollingChildHelper == null) {\n mNestedScrollingChildHelper = new NestedScrollingChildHelper(this);\n }\n return mNestedScrollingChildHelper;\n }\n\n private void scrollToTriggeredAutomatic(boolean isRefresh) {\n if (sDebug) {\n Log.d(TAG, \"scrollToTriggeredAutomatic()\");\n }\n switch (mAutomaticAction) {\n case Constants.ACTION_NOTHING:\n if (isRefresh) {\n triggeredRefresh(false);\n } else {\n triggeredLoadMore(false);\n }\n break;\n case Constants.ACTION_NOTIFY:\n mFlag |= FLAG_AUTO_REFRESH;\n break;\n case Constants.ACTION_AT_ONCE:\n if (isRefresh) {\n triggeredRefresh(true);\n } else {\n triggeredLoadMore(true);\n }\n break;\n }\n int offset;\n if (isRefresh) {\n if (isEnabledKeepRefreshView()) {\n final int offsetToKeepHeaderWhileLoading =\n mIndicator.getOffsetToKeepHeaderWhileLoading();\n final int offsetToRefresh = mIndicator.getOffsetToRefresh();\n offset = Math.max(offsetToKeepHeaderWhileLoading, offsetToRefresh);\n } else {\n offset = mIndicator.getOffsetToRefresh();\n }\n } else {\n if (isEnabledKeepRefreshView()) {\n final int offsetToKeepFooterWhileLoading =\n mIndicator.getOffsetToKeepFooterWhileLoading();\n final int offsetToLoadMore = mIndicator.getOffsetToLoadMore();\n offset = Math.max(offsetToKeepFooterWhileLoading, offsetToLoadMore);\n } else {\n offset = mIndicator.getOffsetToLoadMore();\n }\n }\n mAutomaticActionTriggered = true;\n mScrollChecker.scrollTo(\n offset,\n mAutomaticActionUseSmoothScroll\n ? isRefresh ? mDurationToCloseHeader : mDurationToCloseFooter\n : 0);\n }\n\n protected boolean isNeedInterceptTouchEvent() {\n return (isEnabledInterceptEventWhileLoading() && (isRefreshing() || isLoadingMore()))\n || mAutomaticActionUseSmoothScroll;\n }\n\n protected boolean isNeedFilterTouchEvent() {\n return mIsLastOverScrollCanNotAbort\n || mIsSpringBackCanNotBeInterrupted\n || mIsInterceptTouchEventInOnceTouch;\n }\n\n protected boolean isCanNotAbortOverScrolling() {\n return ((mScrollChecker.isFling()\n || mScrollChecker.isFlingBack()\n || mScrollChecker.isPreFling())\n && (((isMovingHeader() && isDisabledRefresh()))\n || (isMovingFooter() && isDisabledLoadMore())));\n }\n\n public boolean isNotYetInEdgeCannotMoveHeader() {\n final View targetView = getScrollTargetView();\n if (mInEdgeCanMoveHeaderCallBack != null) {\n return mInEdgeCanMoveHeaderCallBack.isNotYetInEdgeCannotMoveHeader(\n this, targetView, mHeaderView);\n }\n return targetView != null && targetView.canScrollVertically(-1);\n }\n\n public boolean isNotYetInEdgeCannotMoveFooter() {\n final View targetView = getScrollTargetView();\n if (mInEdgeCanMoveFooterCallBack != null) {\n return mInEdgeCanMoveFooterCallBack.isNotYetInEdgeCannotMoveFooter(\n this, targetView, mFooterView);\n }\n return targetView != null && targetView.canScrollVertically(1);\n }\n\n protected void makeNewTouchDownEvent(MotionEvent ev) {\n if (sDebug) {\n Log.d(TAG, \"makeNewTouchDownEvent()\");\n }\n sendCancelEvent(ev);\n sendDownEvent(ev);\n mOffsetConsumed = 0;\n mOffsetTotal = 0;\n mOffsetRemaining = mTouchSlop * 3;\n mIndicatorSetter.onFingerUp();\n mIndicatorSetter.onFingerDown(ev.getX(), ev.getY());\n }\n\n protected void sendCancelEvent(MotionEvent event) {\n if (mHasSendCancelEvent || (event == null && mLastMoveEvent == null)) {\n return;\n }\n if (sDebug) {\n Log.d(TAG, \"sendCancelEvent()\");\n }\n final MotionEvent last = event == null ? mLastMoveEvent : event;\n final long now = SystemClock.uptimeMillis();\n final MotionEvent ev =\n MotionEvent.obtain(\n now, now, MotionEvent.ACTION_CANCEL, last.getX(), last.getY(), 0);\n ev.setSource(InputDevice.SOURCE_TOUCHSCREEN);\n mHasSendCancelEvent = true;\n mHasSendDownEvent = false;\n super.dispatchTouchEvent(ev);\n ev.recycle();\n }\n\n protected void sendDownEvent(MotionEvent event) {\n if (mHasSendDownEvent || (event == null && mLastMoveEvent == null)) {\n return;\n }\n if (sDebug) {\n Log.d(TAG, \"sendDownEvent()\");\n }\n final MotionEvent last = event == null ? mLastMoveEvent : event;\n final long now = SystemClock.uptimeMillis();\n final float[] rawOffsets = mIndicator.getRawOffsets();\n final MotionEvent downEv =\n MotionEvent.obtain(\n now,\n now,\n MotionEvent.ACTION_DOWN,\n last.getX() - rawOffsets[0],\n last.getY() - rawOffsets[1],\n 0);\n downEv.setSource(InputDevice.SOURCE_TOUCHSCREEN);\n super.dispatchTouchEvent(downEv);\n downEv.recycle();\n final MotionEvent moveEv =\n MotionEvent.obtain(now, now, MotionEvent.ACTION_MOVE, last.getX(), last.getY(), 0);\n moveEv.setSource(InputDevice.SOURCE_TOUCHSCREEN);\n mHasSendCancelEvent = false;\n mHasSendDownEvent = true;\n super.dispatchTouchEvent(moveEv);\n moveEv.recycle();\n }\n\n protected void notifyFingerUp() {\n if (isHeaderInProcessing() && mHeaderView != null && !isDisabledRefresh()) {\n mHeaderView.onFingerUp(this, mIndicator);\n } else if (isFooterInProcessing() && mFooterView != null && !isDisabledLoadMore()) {\n mFooterView.onFingerUp(this, mIndicator);\n }\n }\n\n protected void onFingerUp() {\n if (sDebug) {\n Log.d(TAG, \"onFingerUp()\");\n }\n notifyFingerUp();\n if (!mScrollChecker.isPreFling()) {\n if (isEnabledKeepRefreshView() && mStatus != SR_STATUS_COMPLETE) {\n if (isHeaderInProcessing()\n && mHeaderView != null\n && !isDisabledPerformRefresh()\n && isMovingHeader()\n && mIndicator.isOverOffsetToRefresh()) {\n if (!mIndicator.isAlreadyHere(mIndicator.getOffsetToKeepHeaderWhileLoading())) {\n mScrollChecker.scrollTo(\n mIndicator.getOffsetToKeepHeaderWhileLoading(),\n mDurationOfBackToHeaderHeight);\n return;\n }\n } else if (isFooterInProcessing()\n && mFooterView != null\n && !isDisabledPerformLoadMore()\n && isMovingFooter()\n && mIndicator.isOverOffsetToLoadMore()) {\n if (!mIndicator.isAlreadyHere(mIndicator.getOffsetToKeepFooterWhileLoading())) {\n mScrollChecker.scrollTo(\n mIndicator.getOffsetToKeepFooterWhileLoading(),\n mDurationOfBackToFooterHeight);\n return;\n }\n }\n }\n onRelease();\n }\n }\n\n protected void onRelease() {\n if (sDebug) {\n Log.d(TAG, \"onRelease()\");\n }\n if ((isMovingFooter() && isEnabledNoMoreDataAndNoSpringBack())) {\n mScrollChecker.stop();\n return;\n }\n tryToPerformRefresh();\n if (mStatus == SR_STATUS_COMPLETE) {\n notifyUIRefreshComplete(true, false, false);\n return;\n } else if (isEnabledKeepRefreshView()) {\n if (isHeaderInProcessing() && mHeaderView != null && !isDisabledPerformRefresh()) {\n if (isRefreshing()\n && isMovingHeader()\n && mIndicator.isAlreadyHere(\n mIndicator.getOffsetToKeepHeaderWhileLoading())) {\n return;\n } else if (isMovingHeader() && mIndicator.isOverOffsetToKeepHeaderWhileLoading()) {\n mScrollChecker.scrollTo(\n mIndicator.getOffsetToKeepHeaderWhileLoading(),\n mDurationOfBackToHeaderHeight);\n return;\n } else if (isRefreshing() && !isMovingFooter()) {\n return;\n }\n } else if (isFooterInProcessing()\n && mFooterView != null\n && !isDisabledPerformLoadMore()) {\n if (isLoadingMore()\n && isMovingFooter()\n && mIndicator.isAlreadyHere(\n mIndicator.getOffsetToKeepFooterWhileLoading())) {\n return;\n } else if (isMovingFooter() && mIndicator.isOverOffsetToKeepFooterWhileLoading()) {\n mScrollChecker.scrollTo(\n mIndicator.getOffsetToKeepFooterWhileLoading(),\n mDurationOfBackToFooterHeight);\n return;\n } else if (isLoadingMore() && !isMovingHeader()) {\n return;\n }\n }\n }\n tryScrollBackToTop();\n }\n\n protected void tryScrollBackToTop() {\n // Use the current percentage duration of the current position to scroll back to the top\n if (mScrollChecker.isFlingBack()) {\n tryScrollBackToTop(mDurationOfFlingBack);\n } else if (isMovingHeader()) {\n tryScrollBackToTop(mDurationToCloseHeader);\n } else if (isMovingFooter()) {\n tryScrollBackToTop(mDurationToCloseFooter);\n } else {\n tryToNotifyReset();\n }\n }\n\n protected void tryScrollBackToTop(int duration) {\n if (sDebug) {\n Log.d(TAG, String.format(\"tryScrollBackToTop(): duration: %d\", duration));\n }\n if (mIndicator.hasLeftStartPosition()\n && (!mIndicator.hasTouched() || !mIndicator.hasMoved())) {\n mScrollChecker.scrollTo(IIndicator.START_POS, duration);\n return;\n }\n if (isNeedFilterTouchEvent() && mIndicator.hasLeftStartPosition()) {\n mScrollChecker.scrollTo(IIndicator.START_POS, duration);\n return;\n }\n tryToNotifyReset();\n }\n\n protected void moveHeaderPos(float delta) {\n if (sDebug) {\n Log.d(TAG, String.format(\"moveHeaderPos(): delta: %f\", delta));\n }\n mNeedFilterScrollEvent = false;\n if (!mNestedScrolling\n && !mHasSendCancelEvent\n && isEnabledOldTouchHandling()\n && mIndicator.hasTouched()\n && !mIndicator.isAlreadyHere(IIndicator.START_POS)) sendCancelEvent(null);\n mIndicatorSetter.setMovingStatus(Constants.MOVING_HEADER);\n if (mHeaderView != null) {\n if (delta > 0) {\n final float maxHeaderDistance = mIndicator.getCanMoveTheMaxDistanceOfHeader();\n final int current = mIndicator.getCurrentPos();\n final boolean isFling = mScrollChecker.isFling() || mScrollChecker.isPreFling();\n if (maxHeaderDistance > 0) {\n if (current >= maxHeaderDistance) {\n if (!mScrollChecker.mIsScrolling || isFling) {\n updateAnotherDirectionPos();\n return;\n }\n } else if (current + delta > maxHeaderDistance) {\n if (!mScrollChecker.mIsScrolling || isFling) {\n delta = maxHeaderDistance - current;\n if (isFling) {\n mScrollChecker.mScroller.forceFinished(true);\n }\n }\n }\n }\n } else {\n // check if it is needed to compatible scroll\n if ((mFlag & FLAG_ENABLE_COMPAT_SYNC_SCROLL) > 0\n && !isEnabledPinContentView()\n && mIsLastRefreshSuccessful\n && mStatus == SR_STATUS_COMPLETE\n && isNotYetInEdgeCannotMoveHeader()) {\n if (sDebug) {\n Log.d(\n TAG,\n String.format(\n \"moveHeaderPos(): compatible scroll delta: %f\", delta));\n }\n mNeedFilterScrollEvent = true;\n tryToCompatSyncScroll(getScrollTargetView(), delta);\n }\n }\n }\n movePos(delta);\n }\n\n protected void moveFooterPos(float delta) {\n if (sDebug) {\n Log.d(TAG, String.format(\"moveFooterPos(): delta: %f\", delta));\n }\n mNeedFilterScrollEvent = false;\n if (!mNestedScrolling\n && !mHasSendCancelEvent\n && isEnabledOldTouchHandling()\n && mIndicator.hasTouched()\n && !mIndicator.isAlreadyHere(IIndicator.START_POS)) sendCancelEvent(null);\n mIndicatorSetter.setMovingStatus(Constants.MOVING_FOOTER);\n if (mFooterView != null) {\n if (delta < 0) {\n final float maxFooterDistance = mIndicator.getCanMoveTheMaxDistanceOfFooter();\n final int current = mIndicator.getCurrentPos();\n final boolean isFling = mScrollChecker.isFling() || mScrollChecker.isPreFling();\n if (maxFooterDistance > 0) {\n if (current >= maxFooterDistance) {\n if (!mScrollChecker.mIsScrolling || isFling) {\n updateAnotherDirectionPos();\n return;\n }\n } else if (current - delta > maxFooterDistance) {\n if (!mScrollChecker.mIsScrolling || isFling) {\n delta = current - maxFooterDistance;\n if (isFling) {\n mScrollChecker.mScroller.forceFinished(true);\n }\n }\n }\n }\n } else {\n // check if it is needed to compatible scroll\n if ((mFlag & FLAG_ENABLE_COMPAT_SYNC_SCROLL) > 0\n && !isEnabledPinContentView()\n && mIsLastRefreshSuccessful\n && mStatus == SR_STATUS_COMPLETE\n && isNotYetInEdgeCannotMoveFooter()) {\n if (sDebug) {\n Log.d(\n TAG,\n String.format(\n \"moveFooterPos(): compatible scroll delta: %f\", delta));\n }\n mNeedFilterScrollEvent = true;\n tryToCompatSyncScroll(getScrollTargetView(), delta);\n }\n }\n }\n movePos(-delta);\n }\n\n protected void tryToCompatSyncScroll(View view, float delta) {\n if (mSyncScrollCallback != null) {\n mSyncScrollCallback.onScroll(view, delta);\n } else {\n if (!ScrollCompat.scrollCompat(view, delta)) {\n Log.w(TAG, \"tryToCompatSyncScroll(): scrollCompat failed!\");\n }\n }\n }\n\n protected void movePos(float delta) {\n if (delta == 0f) {\n if (sDebug) {\n Log.d(TAG, \"movePos(): delta is zero\");\n }\n return;\n }\n int to = (int) (mIndicator.getCurrentPos() + delta);\n // over top\n if (to < IIndicator.START_POS && mLayoutManager.isNeedFilterOverTop(delta)) {\n to = IIndicator.START_POS;\n if (sDebug) {\n Log.d(TAG, \"movePos(): over top\");\n }\n }\n mIndicatorSetter.setCurrentPos(to);\n int change = to - mIndicator.getLastPos();\n updatePos(isMovingFooter() ? -change : change);\n }\n\n /**\n * Update view's Y position\n *\n * @param change The changed value\n */\n protected void updatePos(int change) {\n if (sDebug) {\n Log.d(\n TAG,\n String.format(\n \"updatePos(): change: %d, current: %d last: %d\",\n change, mIndicator.getCurrentPos(), mIndicator.getLastPos()));\n }\n // leave initiated position or just refresh complete\n if ((mIndicator.hasJustLeftStartPosition() || mViewStatus == SR_VIEW_STATUS_INIT)\n && mStatus == SR_STATUS_INIT) {\n final byte old = mStatus;\n mStatus = SR_STATUS_PREPARE;\n notifyStatusChanged(old, mStatus);\n if (isMovingHeader()) {\n mViewStatus = SR_VIEW_STATUS_HEADER_IN_PROCESSING;\n if (mHeaderView != null) {\n mHeaderView.onRefreshPrepare(this);\n }\n } else if (isMovingFooter()) {\n mViewStatus = SR_VIEW_STATUS_FOOTER_IN_PROCESSING;\n if (mFooterView != null) {\n mFooterView.onRefreshPrepare(this);\n }\n }\n }\n tryToPerformRefreshWhenMoved();\n notifyUIPositionChanged();\n boolean needRequestLayout =\n mLayoutManager.offsetChild(\n mHeaderView,\n mFooterView,\n mStickyHeaderView,\n mStickyFooterView,\n mTargetView,\n change);\n // back to initiated position\n if (!(isAutoRefresh() && mStatus != SR_STATUS_COMPLETE)\n && mIndicator.hasJustBackToStartPosition()) {\n tryToNotifyReset();\n if (isEnabledOldTouchHandling()) {\n if (mIndicator.hasTouched() && !mNestedScrolling && !mHasSendDownEvent) {\n sendDownEvent(null);\n }\n }\n }\n if (needRequestLayout) {\n requestLayout();\n } else if (mIndicator.isAlreadyHere(IIndicator.START_POS)) {\n invalidate();\n }\n }\n\n protected void tryToPerformRefreshWhenMoved() {\n // try to perform refresh\n if (mStatus == SR_STATUS_PREPARE && !isAutoRefresh()) {\n // reach fresh height while moving from top to bottom or reach load more height while\n // moving from bottom to top\n if (isHeaderInProcessing() && isMovingHeader() && !isDisabledPerformRefresh()) {\n if (isEnabledPullToRefresh() && mIndicator.isOverOffsetToRefresh()) {\n triggeredRefresh(true);\n } else if (isEnabledPerformFreshWhenFling()\n && !mIndicator.hasTouched()\n && !(mScrollChecker.isPreFling() || mScrollChecker.isFling())\n && mIndicator.isJustReturnedOffsetToRefresh()) {\n mScrollChecker.stop();\n triggeredRefresh(true);\n }\n } else if (isFooterInProcessing() && isMovingFooter() && !isDisabledPerformLoadMore()) {\n if (isEnabledPullToRefresh() && mIndicator.isOverOffsetToLoadMore()) {\n triggeredLoadMore(true);\n } else if (isEnabledPerformFreshWhenFling()\n && !mIndicator.hasTouched()\n && !(mScrollChecker.isPreFling() || mScrollChecker.isFling())\n && mIndicator.isJustReturnedOffsetToLoadMore()) {\n mScrollChecker.stop();\n triggeredLoadMore(true);\n }\n }\n }\n }\n\n /** We need to notify the X pos changed */\n protected void updateAnotherDirectionPos() {\n if (mHeaderView != null\n && !isDisabledRefresh()\n && isMovingHeader()\n && mHeaderView.getView().getVisibility() == VISIBLE) {\n if (isHeaderInProcessing()) {\n mHeaderView.onRefreshPositionChanged(this, mStatus, mIndicator);\n } else {\n mHeaderView.onPureScrollPositionChanged(this, mStatus, mIndicator);\n }\n } else if (mFooterView != null\n && !isDisabledLoadMore()\n && isMovingFooter()\n && mFooterView.getView().getVisibility() == VISIBLE) {\n if (isFooterInProcessing()) {\n mFooterView.onRefreshPositionChanged(this, mStatus, mIndicator);\n } else {\n mFooterView.onPureScrollPositionChanged(this, mStatus, mIndicator);\n }\n }\n }\n\n public boolean isMovingHeader() {\n return mIndicator.getMovingStatus() == Constants.MOVING_HEADER;\n }\n\n public boolean isMovingContent() {\n return mIndicator.getMovingStatus() == Constants.MOVING_CONTENT;\n }\n\n public boolean isMovingFooter() {\n return mIndicator.getMovingStatus() == Constants.MOVING_FOOTER;\n }\n\n public boolean isHeaderInProcessing() {\n return mViewStatus == SR_VIEW_STATUS_HEADER_IN_PROCESSING;\n }\n\n public boolean isFooterInProcessing() {\n return mViewStatus == SR_VIEW_STATUS_FOOTER_IN_PROCESSING;\n }\n\n protected void tryToDispatchNestedFling() {\n if (mScrollChecker.isPreFling() && mIndicator.isAlreadyHere(IIndicator.START_POS)) {\n if (sDebug) {\n Log.d(TAG, \"tryToDispatchNestedFling()\");\n }\n final int velocity = (int) (mScrollChecker.getCurrVelocity() + 0.5f);\n mIndicatorSetter.setMovingStatus(Constants.MOVING_CONTENT);\n if (isEnabledOverScroll()\n && !(isDisabledLoadMoreWhenContentNotFull()\n && !isNotYetInEdgeCannotMoveHeader()\n && !isNotYetInEdgeCannotMoveFooter())) {\n mScrollChecker.startFling(velocity);\n } else {\n mScrollChecker.stop();\n }\n dispatchNestedFling(velocity);\n postInvalidateDelayed(30);\n }\n }\n\n protected boolean tryToNotifyReset() {\n if ((mStatus == SR_STATUS_COMPLETE || mStatus == SR_STATUS_PREPARE)\n && mIndicator.isAlreadyHere(IIndicator.START_POS)) {\n if (sDebug) {\n Log.d(TAG, \"tryToNotifyReset()\");\n }\n if (mHeaderView != null) {\n mHeaderView.onReset(this);\n }\n if (mFooterView != null) {\n mFooterView.onReset(this);\n }\n final byte old = mStatus;\n mStatus = SR_STATUS_INIT;\n notifyStatusChanged(old, mStatus);\n mViewStatus = SR_VIEW_STATUS_INIT;\n mAutomaticActionTriggered = true;\n mNeedFilterScrollEvent = false;\n tryToResetMovingStatus();\n if (!mIndicator.hasTouched()) {\n mIsSpringBackCanNotBeInterrupted = false;\n }\n if (mScrollChecker.isSpringBack()\n || mScrollChecker.isSpring()\n || mScrollChecker.isFlingBack()) {\n mScrollChecker.stop();\n }\n mLayoutManager.resetLayout(\n mHeaderView, mFooterView, mStickyHeaderView, mStickyFooterView, mTargetView);\n if (getParent() != null) {\n getParent().requestDisallowInterceptTouchEvent(false);\n }\n return true;\n }\n return false;\n }\n\n protected void performRefreshComplete(\n boolean hook, boolean immediatelyNoScrolling, boolean notifyViews) {\n if (sDebug) {\n Log.d(\n TAG,\n String.format(\n \"performRefreshComplete(): hook: %b, immediatelyNoScrolling: %b, notifyViews: %b\",\n hook, immediatelyNoScrolling, notifyViews));\n }\n if (isRefreshing()\n && hook\n && mHeaderRefreshCompleteHook != null\n && mHeaderRefreshCompleteHook.mCallBack != null) {\n mHeaderRefreshCompleteHook.mLayout = this;\n mHeaderRefreshCompleteHook.mNotifyViews = notifyViews;\n mHeaderRefreshCompleteHook.doHook();\n return;\n }\n if (isLoadingMore()\n && hook\n && mFooterRefreshCompleteHook != null\n && mFooterRefreshCompleteHook.mCallBack != null) {\n mFooterRefreshCompleteHook.mLayout = this;\n mFooterRefreshCompleteHook.mNotifyViews = notifyViews;\n mFooterRefreshCompleteHook.doHook();\n return;\n }\n if ((mFlag & FLAG_BEEN_SET_NO_MORE_DATA) <= 0) {\n if (mIsLastRefreshSuccessful) {\n mFlag = mFlag & ~(FLAG_ENABLE_NO_MORE_DATA | FLAG_ENABLE_NO_MORE_DATA_NO_BACK);\n }\n } else {\n mFlag = mFlag & ~FLAG_BEEN_SET_NO_MORE_DATA;\n }\n final byte old = mStatus;\n mStatus = SR_STATUS_COMPLETE;\n notifyStatusChanged(old, mStatus);\n notifyUIRefreshComplete(\n !(isMovingFooter() && isEnabledNoMoreDataAndNoSpringBack()),\n immediatelyNoScrolling,\n notifyViews);\n }\n\n protected void notifyUIRefreshComplete(\n boolean useScroll, boolean immediatelyNoScrolling, boolean notifyViews) {\n if (sDebug) {\n Log.d(\n TAG,\n String.format(\n \"notifyUIRefreshComplete(): useScroll: %b, immediatelyNoScrolling: %b, notifyViews: %b\",\n useScroll, immediatelyNoScrolling, notifyViews));\n }\n mIsSpringBackCanNotBeInterrupted = true;\n if (notifyViews) {\n if (isHeaderInProcessing() && mHeaderView != null) {\n mHeaderView.onRefreshComplete(this, mIsLastRefreshSuccessful);\n } else if (isFooterInProcessing() && mFooterView != null) {\n mFooterView.onRefreshComplete(this, mIsLastRefreshSuccessful);\n }\n }\n if (useScroll) {\n if (mScrollChecker.isFlingBack()) {\n mScrollChecker.stop();\n }\n if (immediatelyNoScrolling) {\n tryScrollBackToTop(0);\n } else {\n tryScrollBackToTop();\n }\n }\n }\n\n /** try to perform refresh or loading , if performed return true */\n protected void tryToPerformRefresh() {\n // status not be prepare or over scrolling or moving content go to break;\n if (mStatus != SR_STATUS_PREPARE || isMovingContent()) {\n return;\n }\n if (sDebug) {\n Log.d(TAG, \"tryToPerformRefresh()\");\n }\n final boolean isEnabledKeep = isEnabledKeepRefreshView();\n if (isHeaderInProcessing() && !isDisabledPerformRefresh() && mHeaderView != null) {\n if ((isEnabledKeep && mIndicator.isAlreadyHere(mIndicator.getOffsetToRefresh())\n || mIndicator.isAlreadyHere(mIndicator.getOffsetToKeepHeaderWhileLoading()))) {\n triggeredRefresh(true);\n return;\n }\n }\n if (isFooterInProcessing() && !isDisabledPerformLoadMore() && mFooterView != null) {\n if ((isEnabledKeep && mIndicator.isAlreadyHere(mIndicator.getOffsetToLoadMore())\n || mIndicator.isAlreadyHere(mIndicator.getOffsetToKeepFooterWhileLoading()))) {\n triggeredLoadMore(true);\n }\n }\n }\n\n protected void tryScrollToPerformAutoRefresh() {\n if (isMovingContent() && (mStatus == SR_STATUS_INIT || mStatus == SR_STATUS_PREPARE)) {\n if ((isEnabledAutoLoadMore() && !isDisabledPerformLoadMore())\n || (isEnabledAutoRefresh() && !isDisabledPerformRefresh())) {\n if (sDebug) {\n Log.d(TAG, \"tryScrollToPerformAutoRefresh()\");\n }\n final View targetView = getScrollTargetView();\n if (targetView != null) {\n if (isEnabledAutoLoadMore() && canAutoLoadMore(targetView)) {\n if (!isDisabledLoadMoreWhenContentNotFull()\n || isNotYetInEdgeCannotMoveHeader()\n || isNotYetInEdgeCannotMoveFooter()) {\n triggeredLoadMore(true);\n }\n } else if (isEnabledAutoRefresh() && canAutoRefresh(targetView)) {\n triggeredRefresh(true);\n }\n }\n }\n }\n }\n\n protected boolean canAutoLoadMore(View view) {\n if (mAutoLoadMoreCallBack != null) {\n return mAutoLoadMoreCallBack.canAutoLoadMore(this, view);\n }\n return ScrollCompat.canAutoLoadMore(view);\n }\n\n protected boolean canAutoRefresh(View view) {\n if (mAutoRefreshCallBack != null) {\n return mAutoRefreshCallBack.canAutoRefresh(this, view);\n }\n return ScrollCompat.canAutoRefresh(view);\n }\n\n protected void triggeredRefresh(boolean notify) {\n if (sDebug) {\n Log.d(TAG, \"triggeredRefresh()\");\n }\n byte old = mStatus;\n if (old != SR_STATUS_PREPARE) {\n notifyStatusChanged(old, SR_STATUS_PREPARE);\n old = SR_STATUS_PREPARE;\n if (mHeaderView != null) {\n mHeaderView.onRefreshPrepare(this);\n }\n }\n mStatus = SR_STATUS_REFRESHING;\n notifyStatusChanged(old, mStatus);\n mViewStatus = SR_VIEW_STATUS_HEADER_IN_PROCESSING;\n mFlag &= ~FLAG_AUTO_REFRESH;\n mIsSpringBackCanNotBeInterrupted = false;\n performRefresh(notify);\n }\n\n protected void triggeredLoadMore(boolean notify) {\n if (sDebug) {\n Log.d(TAG, \"triggeredLoadMore()\");\n }\n byte old = mStatus;\n if (old != SR_STATUS_PREPARE) {\n notifyStatusChanged(old, SR_STATUS_PREPARE);\n old = SR_STATUS_PREPARE;\n if (mFooterView != null) {\n mFooterView.onRefreshPrepare(this);\n }\n }\n mStatus = SR_STATUS_LOADING_MORE;\n notifyStatusChanged(old, mStatus);\n mViewStatus = SR_VIEW_STATUS_FOOTER_IN_PROCESSING;\n mFlag &= ~FLAG_AUTO_REFRESH;\n mIsSpringBackCanNotBeInterrupted = false;\n performRefresh(notify);\n }\n\n protected void tryToResetMovingStatus() {\n if (mIndicator.isAlreadyHere(IIndicator.START_POS) && !isMovingContent()) {\n mIndicatorSetter.setMovingStatus(Constants.MOVING_CONTENT);\n notifyUIPositionChanged();\n }\n }\n\n protected void performRefresh(boolean notify) {\n // loading start milliseconds since boot\n mLoadingStartTime = SystemClock.uptimeMillis();\n if (sDebug) {\n Log.d(TAG, String.format(\"onRefreshBegin systemTime: %d\", mLoadingStartTime));\n }\n if (isRefreshing()) {\n if (mHeaderView != null) {\n mHeaderView.onRefreshBegin(this, mIndicator);\n }\n } else if (isLoadingMore()) {\n if (mFooterView != null) {\n mFooterView.onRefreshBegin(this, mIndicator);\n }\n }\n if (notify && mRefreshListener != null) {\n if (isRefreshing()) {\n mRefreshListener.onRefreshing();\n } else {\n mRefreshListener.onLoadingMore();\n }\n }\n }\n\n protected void dispatchNestedFling(int velocity) {\n if (sDebug) {\n Log.d(TAG, String.format(\"dispatchNestedFling() : velocity: %d\", velocity));\n }\n final View targetView = getScrollTargetView();\n ScrollCompat.flingCompat(targetView, -velocity);\n }\n\n private void notifyUIPositionChanged() {\n final List<OnUIPositionChangedListener> listeners = mUIPositionChangedListeners;\n if (listeners != null) {\n for (OnUIPositionChangedListener listener : listeners) {\n listener.onChanged(mStatus, mIndicator);\n }\n }\n }\n\n protected void notifyStatusChanged(byte old, byte now) {\n final List<OnStatusChangedListener> listeners = mStatusChangedListeners;\n if (listeners != null) {\n for (OnStatusChangedListener listener : listeners) {\n listener.onStatusChanged(old, now);\n }\n }\n }\n\n private View foundViewInViewGroupById(ViewGroup group, int id) {\n final int size = group.getChildCount();\n for (int i = 0; i < size; i++) {\n View view = group.getChildAt(i);\n if (view.getId() == id) {\n return view;\n } else if (view instanceof ViewGroup) {\n final View found = foundViewInViewGroupById((ViewGroup) view, id);\n if (found != null) {\n return found;\n }\n }\n }\n return null;\n }\n\n /**\n * Classes that wish to override {@link SmoothRefreshLayout#isNotYetInEdgeCannotMoveHeader()}\n * method behavior\n */\n public interface OnHeaderEdgeDetectCallBack {\n /**\n * Callback that will be called when {@link\n * SmoothRefreshLayout#isNotYetInEdgeCannotMoveHeader()} method is called to allow the\n * implementer to override its behavior.\n *\n * @param parent SmoothRefreshLayout that this callback is overriding.\n * @param child The child view.\n * @param header The Header view.\n * @return Whether it is possible for the child view of parent layout to scroll up.\n */\n boolean isNotYetInEdgeCannotMoveHeader(\n SmoothRefreshLayout parent, @Nullable View child, @Nullable IRefreshView header);\n }\n\n /**\n * Classes that wish to override {@link SmoothRefreshLayout#isNotYetInEdgeCannotMoveFooter()}\n * method behavior\n */\n public interface OnFooterEdgeDetectCallBack {\n /**\n * Callback that will be called when {@link\n * SmoothRefreshLayout#isNotYetInEdgeCannotMoveFooter()} method is called to allow the\n * implementer to override its behavior.\n *\n * @param parent SmoothRefreshLayout that this callback is overriding.\n * @param child The child view.\n * @param footer The Footer view.\n * @return Whether it is possible for the child view of parent layout to scroll down.\n */\n boolean isNotYetInEdgeCannotMoveFooter(\n SmoothRefreshLayout parent, @Nullable View child, @Nullable IRefreshView footer);\n }\n\n /** Classes that wish to be notified when the swipe gesture correctly triggers a refresh */\n public interface OnRefreshListener {\n /** Called when a refresh is triggered. */\n void onRefreshing();\n\n /** Called when a load more is triggered. */\n void onLoadingMore();\n }\n\n /** Classes that wish to be notified when the views position changes */\n public interface OnUIPositionChangedListener {\n /**\n * UI position changed\n *\n * @param status {@link #SR_STATUS_INIT}, {@link #SR_STATUS_PREPARE}, {@link\n * #SR_STATUS_REFRESHING},{@link #SR_STATUS_LOADING_MORE},{@link #SR_STATUS_COMPLETE}.\n * @param indicator @see {@link IIndicator}\n */\n void onChanged(byte status, IIndicator indicator);\n }\n\n /** Classes that wish to be called when refresh completed spring back to start position */\n public interface OnSyncScrollCallback {\n /**\n * Called when refresh completed spring back to start position, each move triggers a\n * callback once\n *\n * @param content The content view\n * @param delta The scroll distance in current axis\n */\n void onScroll(View content, float delta);\n }\n\n public interface OnHookUIRefreshCompleteCallBack {\n void onHook(RefreshCompleteHook hook);\n }\n\n /**\n * Classes that wish to be called when {@link\n * SmoothRefreshLayout#setEnableAutoLoadMore(boolean)} has been set true and {@link\n * SmoothRefreshLayout#isDisabledLoadMore()} not be true and sure you need to customize the\n * specified trigger rule\n */\n public interface OnPerformAutoLoadMoreCallBack {\n /**\n * Whether need trigger auto load more\n *\n * @param parent The frame\n * @param child the child view\n * @return whether need trigger\n */\n boolean canAutoLoadMore(SmoothRefreshLayout parent, @Nullable View child);\n }\n\n /**\n * Classes that wish to be called when {@link SmoothRefreshLayout#setEnableAutoRefresh(boolean)}\n * has been set true and {@link SmoothRefreshLayout#isDisabledRefresh()} not be true and sure\n * you need to customize the specified trigger rule\n */\n public interface OnPerformAutoRefreshCallBack {\n /**\n * Whether need trigger auto refresh\n *\n * @param parent The frame\n * @param child the child view\n * @return whether need trigger\n */\n boolean canAutoRefresh(SmoothRefreshLayout parent, @Nullable View child);\n }\n\n /** Classes that wish to be notified when the status changed */\n public interface OnStatusChangedListener {\n /**\n * Status changed\n *\n * @param old the old status, as follows {@link #SR_STATUS_INIT}, {@link\n * #SR_STATUS_PREPARE}, {@link #SR_STATUS_REFRESHING},{@link #SR_STATUS_LOADING_MORE},\n * {@link #SR_STATUS_COMPLETE}}\n * @param now the current status, as follows {@link #SR_STATUS_INIT}, {@link\n * #SR_STATUS_PREPARE}, {@link #SR_STATUS_REFRESHING},{@link #SR_STATUS_LOADING_MORE},\n * {@link #SR_STATUS_COMPLETE}}\n */\n void onStatusChanged(byte old, byte now);\n }\n\n /** Classes that wish to override the calculate bounce duration and distance method */\n public interface OnCalculateBounceCallback {\n int onCalculateDistance(float velocity);\n\n int onCalculateDuration(float velocity);\n }\n\n public static class LayoutParams extends MarginLayoutParams {\n public int gravity = Gravity.TOP | Gravity.START;\n\n @SuppressWarnings(\"WeakerAccess\")\n public LayoutParams(Context c, AttributeSet attrs) {\n super(c, attrs);\n final TypedArray a =\n c.obtainStyledAttributes(attrs, R.styleable.SmoothRefreshLayout_Layout);\n gravity =\n a.getInt(\n R.styleable.SmoothRefreshLayout_Layout_android_layout_gravity, gravity);\n a.recycle();\n }\n\n public LayoutParams(int width, int height) {\n super(width, height);\n }\n\n @SuppressWarnings(\"unused\")\n public LayoutParams(MarginLayoutParams source) {\n super(source);\n }\n\n @SuppressWarnings(\"WeakerAccess\")\n public LayoutParams(ViewGroup.LayoutParams source) {\n super(source);\n }\n }\n\n public static class RefreshCompleteHook {\n private SmoothRefreshLayout mLayout;\n private OnHookUIRefreshCompleteCallBack mCallBack;\n private boolean mNotifyViews;\n\n public void onHookComplete(boolean immediatelyNoScrolling) {\n if (mLayout != null) {\n if (sDebug) {\n Log.d(\n mLayout.TAG,\n String.format(\n \"RefreshCompleteHook: onHookComplete(): immediatelyNoScrolling: %b\",\n immediatelyNoScrolling));\n }\n mLayout.performRefreshComplete(false, immediatelyNoScrolling, mNotifyViews);\n }\n }\n\n private void doHook() {\n if (mCallBack != null) {\n if (sDebug) {\n Log.d(mLayout.TAG, \"RefreshCompleteHook: doHook()\");\n }\n mCallBack.onHook(this);\n }\n }\n }\n\n /** Delayed completion of loading */\n private static class DelayToRefreshComplete implements Runnable {\n private SmoothRefreshLayout mLayout;\n private boolean mNotifyViews;\n\n @Override\n public void run() {\n if (mLayout != null) {\n if (sDebug) {\n Log.d(mLayout.TAG, \"DelayToRefreshComplete: run()\");\n }\n mLayout.performRefreshComplete(true, false, mNotifyViews);\n }\n }\n }\n\n /** Delayed to dispatch nested fling */\n private static class DelayToDispatchNestedFling implements Runnable {\n private SmoothRefreshLayout mLayout;\n private int mVelocity;\n\n @Override\n public void run() {\n if (mLayout != null) {\n if (sDebug) {\n Log.d(mLayout.TAG, \"DelayToDispatchNestedFling: run()\");\n }\n mLayout.dispatchNestedFling(mVelocity);\n }\n }\n }\n\n /** Delayed to perform auto refresh */\n private static class DelayToPerformAutoRefresh implements Runnable {\n private SmoothRefreshLayout mLayout;\n\n @Override\n public void run() {\n if (mLayout != null) {\n if (sDebug) {\n Log.d(mLayout.TAG, \"DelayToPerformAutoRefresh: run()\");\n }\n mLayout.tryToPerformAutoRefresh();\n }\n }\n }\n\n public abstract static class LayoutManager {\n public static final int HORIZONTAL = 0;\n public static final int VERTICAL = 1;\n protected final String TAG = getClass().getSimpleName() + \"-\" + SmoothRefreshLayout.sId++;\n protected SmoothRefreshLayout mLayout;\n protected boolean mMeasureMatchParentChildren;\n protected int mOldWidthMeasureSpec;\n protected int mOldHeightMeasureSpec;\n\n @Orientation\n public abstract int getOrientation();\n\n @CallSuper\n public void setLayout(SmoothRefreshLayout layout) {\n mLayout = layout;\n }\n\n public void onLayoutDraw(Canvas canvas) {}\n\n public boolean isNeedFilterOverTop(float delta) {\n return true;\n }\n\n public abstract void measureHeader(\n @NonNull IRefreshView<IIndicator> header,\n int widthMeasureSpec,\n int heightMeasureSpec);\n\n public abstract void measureFooter(\n @NonNull IRefreshView<IIndicator> footer,\n int widthMeasureSpec,\n int heightMeasureSpec);\n\n public abstract void layoutHeaderView(@NonNull IRefreshView<IIndicator> header);\n\n public abstract void layoutFooterView(@NonNull IRefreshView<IIndicator> footer);\n\n public abstract void layoutContentView(@NonNull View content);\n\n public abstract void layoutStickyHeaderView(@NonNull View stickyHeader);\n\n public abstract void layoutStickyFooterView(@NonNull View stickyFooter);\n\n public abstract boolean offsetChild(\n @Nullable IRefreshView<IIndicator> header,\n @Nullable IRefreshView<IIndicator> footer,\n @Nullable View stickyHeader,\n @Nullable View stickyFooter,\n @Nullable View content,\n int change);\n\n public void resetLayout(\n @Nullable IRefreshView<IIndicator> header,\n @Nullable IRefreshView<IIndicator> footer,\n @Nullable View stickyHeader,\n @Nullable View stickyFooter,\n @Nullable View content) {}\n\n protected void setHeaderHeight(int height) {\n if (mLayout != null) {\n mLayout.mIndicatorSetter.setHeaderHeight(height);\n }\n }\n\n protected void setFooterHeight(int height) {\n if (mLayout != null) {\n mLayout.mIndicatorSetter.setFooterHeight(height);\n }\n }\n\n protected byte getRefreshStatus() {\n return mLayout == null ? SmoothRefreshLayout.SR_STATUS_INIT : mLayout.mStatus;\n }\n\n protected final void measureChildWithMargins(\n View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) {\n final ViewGroup.MarginLayoutParams lp =\n (ViewGroup.MarginLayoutParams) child.getLayoutParams();\n final int childWidthMeasureSpec =\n ViewGroup.getChildMeasureSpec(\n parentWidthMeasureSpec,\n mLayout.getPaddingLeft()\n + mLayout.getPaddingRight()\n + lp.leftMargin\n + lp.rightMargin,\n lp.width);\n final int childHeightMeasureSpec =\n ViewGroup.getChildMeasureSpec(\n parentHeightMeasureSpec,\n mLayout.getPaddingTop()\n + mLayout.getPaddingBottom()\n + lp.topMargin\n + lp.bottomMargin,\n lp.height);\n child.measure(childWidthMeasureSpec, childHeightMeasureSpec);\n }\n }\n\n class ScrollChecker implements Runnable {\n private static final float GRAVITY_EARTH = 9.80665f;\n final int mMaxDistance;\n private final float mPhysical;\n Scroller[] mCachedScroller;\n Scroller mScroller;\n Scroller mCalcScroller;\n Interpolator mInterpolator;\n float mLastY;\n float mLastStart;\n float mLastTo;\n int mDuration;\n byte mMode = Constants.SCROLLER_MODE_NONE;\n float mVelocity;\n boolean mIsScrolling = false;\n private int[] mCachedPair = new int[2];\n\n ScrollChecker() {\n DisplayMetrics dm = getResources().getDisplayMetrics();\n mMaxDistance = (int) (dm.heightPixels / 8f);\n mPhysical = GRAVITY_EARTH * 39.37f * dm.density * 160f * 0.84f;\n mCalcScroller = new Scroller(getContext());\n mInterpolator = SPRING_INTERPOLATOR;\n mCachedScroller =\n new Scroller[] {\n new Scroller(getContext(), SPRING_INTERPOLATOR),\n new Scroller(getContext(), SPRING_BACK_INTERPOLATOR),\n new Scroller(getContext(), FLING_INTERPOLATOR)\n };\n mScroller = mCachedScroller[0];\n }\n\n @Override\n public void run() {\n if (mMode == Constants.SCROLLER_MODE_NONE || isCalcFling()) {\n return;\n }\n boolean finished = !mScroller.computeScrollOffset() && mScroller.getCurrY() == mLastY;\n int curY = mScroller.getCurrY();\n float deltaY = curY - mLastY;\n if (sDebug) {\n Log.d(\n TAG,\n String.format(\n \"ScrollChecker: run(): finished: %b, mode: %d, start: %f, to: %f,\"\n + \" curPos: %d, curY:%d, last: %f, delta: %f\",\n finished,\n mMode,\n mLastStart,\n mLastTo,\n mIndicator.getCurrentPos(),\n curY,\n mLastY,\n deltaY));\n }\n if (!finished) {\n mLastY = curY;\n if (isMovingHeader()) {\n moveHeaderPos(deltaY);\n } else if (isMovingFooter()) {\n if (isPreFling()) {\n moveFooterPos(deltaY);\n } else {\n moveFooterPos(-deltaY);\n }\n }\n ViewCompat.postOnAnimation(SmoothRefreshLayout.this, this);\n tryToDispatchNestedFling();\n } else {\n switch (mMode) {\n case Constants.SCROLLER_MODE_SPRING:\n case Constants.SCROLLER_MODE_FLING_BACK:\n case Constants.SCROLLER_MODE_SPRING_BACK:\n stop();\n if (!mIndicator.isAlreadyHere(IIndicator.START_POS)) {\n onRelease();\n }\n break;\n case Constants.SCROLLER_MODE_PRE_FLING:\n case Constants.SCROLLER_MODE_FLING:\n stop();\n mMode = Constants.SCROLLER_MODE_FLING_BACK;\n if (isEnabledPerformFreshWhenFling()\n || isRefreshing()\n || isLoadingMore()\n || (isEnabledAutoLoadMore() && isMovingFooter())\n || (isEnabledAutoRefresh() && isMovingHeader())) {\n onRelease();\n } else {\n tryScrollBackToTop();\n }\n break;\n }\n }\n }\n\n boolean isPreFling() {\n return mMode == Constants.SCROLLER_MODE_PRE_FLING;\n }\n\n boolean isFling() {\n return mMode == Constants.SCROLLER_MODE_FLING;\n }\n\n boolean isFlingBack() {\n return mMode == Constants.SCROLLER_MODE_FLING_BACK;\n }\n\n boolean isSpringBack() {\n return mMode == Constants.SCROLLER_MODE_SPRING_BACK;\n }\n\n boolean isSpring() {\n return mMode == Constants.SCROLLER_MODE_SPRING;\n }\n\n boolean isCalcFling() {\n return mMode == Constants.SCROLLER_MODE_CALC_FLING;\n }\n\n float getCurrVelocity() {\n final int originalSymbol = mVelocity > 0 ? 1 : -1;\n float v = mScroller.getCurrVelocity() * originalSymbol;\n if (sDebug) {\n Log.d(TAG, String.format(\"ScrollChecker: getCurrVelocity(): v: %f\", v));\n }\n return v;\n }\n\n int getFinalY(float v) {\n mCalcScroller.fling(\n 0,\n 0,\n 0,\n (int) v,\n Integer.MIN_VALUE,\n Integer.MAX_VALUE,\n Integer.MIN_VALUE,\n Integer.MAX_VALUE);\n final int y = Math.abs(mCalcScroller.getFinalY());\n if (sDebug) {\n Log.d(\n TAG,\n String.format(\n \"ScrollChecker: getFinalY(): v: %s, finalY: %d, currentY: %d\",\n v, y, mIndicator.getCurrentPos()));\n }\n mCalcScroller.abortAnimation();\n return y;\n }\n\n void startPreFling(float v) {\n stop();\n mMode = Constants.SCROLLER_MODE_PRE_FLING;\n setInterpolator(FLING_INTERPOLATOR);\n mVelocity = v;\n mScroller.fling(\n 0,\n 0,\n 0,\n (int) v,\n Integer.MIN_VALUE,\n Integer.MAX_VALUE,\n Integer.MIN_VALUE,\n Integer.MAX_VALUE);\n if (sDebug) {\n Log.d(TAG, String.format(\"ScrollChecker: startPreFling(): v: %s\", v));\n }\n ViewCompat.postOnAnimation(SmoothRefreshLayout.this, this);\n }\n\n void startFling(float v) {\n stop();\n mMode = Constants.SCROLLER_MODE_CALC_FLING;\n setInterpolator(FLING_INTERPOLATOR);\n mVelocity = v;\n mScroller.fling(\n 0,\n 0,\n 0,\n (int) v,\n Integer.MIN_VALUE,\n Integer.MAX_VALUE,\n Integer.MIN_VALUE,\n Integer.MAX_VALUE);\n if (sDebug) {\n Log.d(TAG, String.format(\"ScrollChecker: startFling(): v: %s\", v));\n }\n }\n\n void scrollTo(int to, int duration) {\n final int curPos = mIndicator.getCurrentPos();\n if (to > curPos) {\n stop();\n setInterpolator(mSpringInterpolator);\n mMode = Constants.SCROLLER_MODE_SPRING;\n } else if (to < curPos) {\n if (!mScrollChecker.isFlingBack()) {\n stop();\n mMode = Constants.SCROLLER_MODE_SPRING_BACK;\n }\n setInterpolator(mSpringBackInterpolator);\n } else {\n mMode = Constants.SCROLLER_MODE_NONE;\n return;\n }\n mLastStart = curPos;\n mLastTo = to;\n if (sDebug) {\n Log.d(\n TAG,\n String.format(\n \"ScrollChecker: scrollTo(): to: %d, duration: %d\", to, duration));\n }\n int distance = (int) (mLastTo - mLastStart);\n mLastY = 0;\n mDuration = duration;\n mIsScrolling = true;\n mScroller.startScroll(0, 0, 0, distance, duration);\n removeCallbacks(this);\n if (duration <= 0) {\n run();\n } else {\n ViewCompat.postOnAnimation(SmoothRefreshLayout.this, this);\n }\n }\n\n void computeScrollOffset() {\n if (mScroller.computeScrollOffset()) {\n if (sDebug) {\n Log.d(TAG, \"ScrollChecker: computeScrollOffset()\");\n }\n if (isCalcFling()) {\n if (mVelocity > 0\n && mIndicator.isAlreadyHere(IIndicator.START_POS)\n && !isNotYetInEdgeCannotMoveHeader()) {\n final float velocity = Math.abs(getCurrVelocity());\n stop();\n mIndicatorSetter.setMovingStatus(Constants.MOVING_HEADER);\n final int[] result = computeScroll(velocity);\n if (getHeaderHeight() > 0 && (isRefreshing() || isEnabledAutoRefresh())) {\n startBounce(\n Math.min(result[0] * 3, getHeaderHeight()),\n Math.min(\n Math.max(result[1] / 2 * 5, mMinOverScrollDuration),\n mMaxOverScrollDuration));\n } else {\n startBounce(result[0], result[1]);\n }\n return;\n } else if (mVelocity < 0\n && mIndicator.isAlreadyHere(IIndicator.START_POS)\n && !isNotYetInEdgeCannotMoveFooter()) {\n final float velocity = Math.abs(getCurrVelocity());\n stop();\n mIndicatorSetter.setMovingStatus(Constants.MOVING_FOOTER);\n final int[] result = computeScroll(velocity);\n if (getFooterHeight() > 0\n && (isLoadingMore()\n || isEnabledAutoLoadMore()\n || isEnabledNoMoreData())) {\n startBounce(\n Math.min(result[0] * 3, getFooterHeight()),\n Math.min(\n Math.max(result[1] / 2 * 5, mMinOverScrollDuration),\n mMaxOverScrollDuration));\n } else {\n startBounce(result[0], result[1]);\n }\n return;\n }\n }\n invalidate();\n }\n }\n\n int[] computeScroll(float velocity) {\n int distance, duration;\n if (mCalculateBounceCallback != null) {\n distance = mCalculateBounceCallback.onCalculateDistance(velocity);\n duration = mCalculateBounceCallback.onCalculateDuration(velocity);\n mCachedPair[0] = Math.max(distance, mTouchSlop);\n } else {\n // Multiply by a given empirical value\n velocity = velocity * .535f;\n float deceleration =\n (float)\n Math.log(\n Math.abs(velocity / 4.5f)\n / (ViewConfiguration.getScrollFriction()\n * mPhysical));\n float ratio = (float) ((Math.exp(-Math.log10(velocity) / 1.2d)) * 2f);\n distance =\n (int)\n ((ViewConfiguration.getScrollFriction()\n * mPhysical\n * Math.exp(deceleration))\n * ratio);\n duration = (int) (1000f * ratio);\n mCachedPair[0] = Math.max(Math.min(distance, mMaxDistance), mTouchSlop);\n }\n mCachedPair[1] =\n Math.min(Math.max(duration, mMinOverScrollDuration), mMaxOverScrollDuration);\n return mCachedPair;\n }\n\n void startBounce(int to, int duration) {\n mMode = Constants.SCROLLER_MODE_FLING;\n setInterpolator(SPRING_INTERPOLATOR);\n mLastStart = mIndicator.getCurrentPos();\n mLastTo = to;\n if (sDebug) {\n Log.d(\n TAG,\n String.format(\n \"ScrollChecker: startBounce(): to: %d, duration: %d\",\n to, duration));\n }\n int distance = (int) (mLastTo - mLastStart);\n mLastY = 0;\n mDuration = duration;\n mIsScrolling = true;\n mScroller.startScroll(0, 0, 0, distance, duration);\n removeCallbacks(this);\n ViewCompat.postOnAnimation(SmoothRefreshLayout.this, this);\n }\n\n void setInterpolator(Interpolator interpolator) {\n if (mInterpolator == interpolator) {\n return;\n }\n if (sDebug) {\n Log.d(\n TAG,\n String.format(\n \"ScrollChecker: updateInterpolator(): interpolator: %s\",\n interpolator == null\n ? \"null\"\n : interpolator.getClass().getSimpleName()));\n }\n mInterpolator = interpolator;\n if (!mScroller.isFinished()) {\n switch (mMode) {\n case Constants.SCROLLER_MODE_SPRING:\n case Constants.SCROLLER_MODE_FLING_BACK:\n case Constants.SCROLLER_MODE_SPRING_BACK:\n mLastStart = mIndicator.getCurrentPos();\n int distance = (int) (mLastTo - mLastStart);\n int passed = mScroller.timePassed();\n mScroller = makeOrGetScroller(interpolator);\n mScroller.startScroll(0, 0, 0, distance, mDuration - passed);\n removeCallbacks(this);\n ViewCompat.postOnAnimation(SmoothRefreshLayout.this, this);\n break;\n case Constants.SCROLLER_MODE_PRE_FLING:\n case Constants.SCROLLER_MODE_CALC_FLING:\n final float currentVelocity = getCurrVelocity();\n mScroller = makeOrGetScroller(interpolator);\n if (isCalcFling()) {\n startFling(currentVelocity);\n } else {\n startPreFling(currentVelocity);\n }\n break;\n default:\n mScroller = makeOrGetScroller(interpolator);\n break;\n }\n } else {\n mScroller = makeOrGetScroller(interpolator);\n }\n }\n\n void stop() {\n if (mMode != Constants.SCROLLER_MODE_NONE) {\n if (sDebug) {\n Log.d(TAG, \"ScrollChecker: stop()\");\n }\n if (mNestedScrolling && isCalcFling()) {\n mMode = Constants.SCROLLER_MODE_NONE;\n stopNestedScroll(ViewCompat.TYPE_NON_TOUCH);\n } else {\n mMode = Constants.SCROLLER_MODE_NONE;\n }\n mAutomaticActionUseSmoothScroll = false;\n mIsScrolling = false;\n mScroller.forceFinished(true);\n mDuration = 0;\n mLastY = 0;\n mLastTo = -1;\n mLastStart = 0;\n removeCallbacks(this);\n }\n }\n\n private Scroller makeOrGetScroller(Interpolator interpolator) {\n if (interpolator == SPRING_INTERPOLATOR) {\n return mCachedScroller[0];\n } else if (interpolator == SPRING_BACK_INTERPOLATOR) {\n return mCachedScroller[1];\n } else if (interpolator == FLING_INTERPOLATOR) {\n return mCachedScroller[2];\n } else {\n return new Scroller(getContext(), interpolator);\n }\n }\n }\n}", "public interface IRefreshView<T extends IIndicator> {\n byte TYPE_HEADER = 0;\n byte TYPE_FOOTER = 1;\n\n byte STYLE_DEFAULT = 0;\n byte STYLE_SCALE = 1;\n // desc start\n // added in version 1.4.8\n byte STYLE_PIN = 2;\n byte STYLE_FOLLOW_SCALE = 3;\n byte STYLE_FOLLOW_PIN = 4;\n byte STYLE_FOLLOW_CENTER = 5;\n // desc end\n\n /**\n * Get the view type.\n *\n * @return type {@link #TYPE_HEADER}, {@link #TYPE_FOOTER}.\n */\n @RefreshViewType\n int getType();\n\n /**\n * Get the view style. If return {@link #STYLE_SCALE} SmoothRefreshLayout will dynamically\n * change the height, so the performance will be reduced. If return {@link #STYLE_FOLLOW_SCALE}\n * , when the moved position large than the view height, SmoothRefreshLayout will dynamically\n * change the height, so the performance will be reduced.\n *\n * <p>Since 1.4.8 add {@link #STYLE_PIN}, {@link #STYLE_FOLLOW_SCALE}, {@link\n * #STYLE_FOLLOW_PIN}, {@link #STYLE_FOLLOW_CENTER}\n *\n * @return style {@link #STYLE_DEFAULT}, {@link #STYLE_SCALE}, {@link #STYLE_PIN}, {@link\n * #STYLE_FOLLOW_SCALE}, {@link #STYLE_FOLLOW_PIN}, {@link #STYLE_FOLLOW_CENTER}.\n */\n @RefreshViewStyle\n int getStyle();\n\n /**\n * Get the custom height, When the return style is {@link #STYLE_SCALE} or {@link\n * #STYLE_FOLLOW_SCALE} , you must return a accurate height<br>\n *\n * <p>Since version 1.6.1, If you want the height equal to the srl height, you can return `-1`\n * {@link android.view.ViewGroup.LayoutParams#MATCH_PARENT}\n *\n * @return Custom height\n */\n int getCustomHeight();\n\n /**\n * Get the target view.\n *\n * @return The returned view must be the view that will be added to the Layout\n */\n @NonNull\n View getView();\n\n /**\n * This method will be triggered when the touched finger is lifted.\n *\n * @param layout The layout {@link SmoothRefreshLayout}\n * @param indicator The indicator {@link IIndicator}\n */\n void onFingerUp(SmoothRefreshLayout layout, T indicator);\n\n /**\n * This method will be triggered when the refresh state is reset to {@link\n * SmoothRefreshLayout#SR_STATUS_INIT}.\n *\n * @param layout The layout {@link SmoothRefreshLayout}\n */\n void onReset(SmoothRefreshLayout layout);\n\n /**\n * This method will be triggered when the frame is ready to refreshing.\n *\n * @param layout The layout {@link SmoothRefreshLayout}\n */\n void onRefreshPrepare(SmoothRefreshLayout layout);\n\n /**\n * This method will be triggered when the frame begin to refresh.\n *\n * @param layout The layout {@link SmoothRefreshLayout}\n * @param indicator The indicator {@link IIndicator}\n */\n void onRefreshBegin(SmoothRefreshLayout layout, T indicator);\n\n /**\n * This method will be triggered when the frame is refresh completed.\n *\n * @param layout The layout {@link SmoothRefreshLayout}\n * @param isSuccessful The layout refresh state\n */\n void onRefreshComplete(SmoothRefreshLayout layout, boolean isSuccessful);\n\n /**\n * This method will be triggered when the position of the refresh view changes.\n *\n * @param layout The layout {@link SmoothRefreshLayout}\n * @param status Current status @see{@link SmoothRefreshLayout#SR_STATUS_INIT}, {@link\n * SmoothRefreshLayout#SR_STATUS_PREPARE}, {@link SmoothRefreshLayout#SR_STATUS_REFRESHING},\n * {@link SmoothRefreshLayout#SR_STATUS_LOADING_MORE}, {@link\n * SmoothRefreshLayout#SR_STATUS_COMPLETE}.\n * @param indicator The indicator {@link IIndicator}\n */\n void onRefreshPositionChanged(SmoothRefreshLayout layout, byte status, T indicator);\n\n /**\n * Before the transaction of the refresh view has not yet been processed completed. This method\n * will be triggered when the position of the other refresh view changes.<br>\n *\n * <p>Since version 1.4.6\n *\n * @param layout The layout {@link SmoothRefreshLayout}\n * @param status Current status @see{@link SmoothRefreshLayout#SR_STATUS_INIT}, {@link\n * SmoothRefreshLayout#SR_STATUS_PREPARE}, {@link SmoothRefreshLayout#SR_STATUS_REFRESHING},\n * {@link SmoothRefreshLayout#SR_STATUS_LOADING_MORE}, {@link\n * SmoothRefreshLayout#SR_STATUS_COMPLETE}.\n * @param indicator The indicator {@link IIndicator}\n */\n void onPureScrollPositionChanged(SmoothRefreshLayout layout, byte status, T indicator);\n\n @IntDef({TYPE_HEADER, TYPE_FOOTER})\n @Retention(RetentionPolicy.SOURCE)\n public @interface RefreshViewType {}\n\n @IntDef({\n STYLE_DEFAULT,\n STYLE_SCALE,\n STYLE_PIN,\n STYLE_FOLLOW_SCALE,\n STYLE_FOLLOW_PIN,\n STYLE_FOLLOW_CENTER\n })\n @Retention(RetentionPolicy.SOURCE)\n public @interface RefreshViewStyle {}\n}", "public class ClassicFooter<T extends IIndicator> extends AbsClassicRefreshView<T> {\n private boolean mNoMoreDataChangedView = false;\n @StringRes private int mPullUpToLoadRes = R.string.sr_pull_up_to_load;\n @StringRes private int mPullUpRes = R.string.sr_pull_up;\n @StringRes private int mLoadingRes = R.string.sr_loading;\n @StringRes private int mLoadSuccessfulRes = R.string.sr_load_complete;\n @StringRes private int mLoadFailRes = R.string.sr_load_failed;\n @StringRes private int mReleaseToLoadRes = R.string.sr_release_to_load;\n @StringRes private int mNoMoreDataRes = R.string.sr_no_more_data;\n private View.OnClickListener mNoMoreDataClickListener;\n\n public ClassicFooter(Context context) {\n this(context, null);\n }\n\n public ClassicFooter(Context context, AttributeSet attrs) {\n this(context, attrs, 0);\n }\n\n public ClassicFooter(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n Bitmap bitmap =\n BitmapFactory.decodeResource(getResources(), R.drawable.sr_classic_arrow_icon);\n Matrix matrix = new Matrix();\n matrix.postRotate(180);\n Bitmap dstBitmap =\n Bitmap.createBitmap(\n bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);\n if (!bitmap.isRecycled()) bitmap.recycle();\n mArrowImageView.setImageBitmap(dstBitmap);\n }\n\n public void setPullUpToLoadRes(@StringRes int pullUpToLoadRes) {\n mPullUpToLoadRes = pullUpToLoadRes;\n }\n\n public void setPullUpRes(@StringRes int pullUpRes) {\n mPullUpRes = pullUpRes;\n }\n\n public void setLoadingRes(@StringRes int loadingRes) {\n mLoadingRes = loadingRes;\n }\n\n public void setLoadSuccessfulRes(@StringRes int loadSuccessfulRes) {\n mLoadSuccessfulRes = loadSuccessfulRes;\n }\n\n public void setLoadFailRes(@StringRes int loadFailRes) {\n mLoadFailRes = loadFailRes;\n }\n\n public void setReleaseToLoadRes(@StringRes int releaseToLoadRes) {\n mReleaseToLoadRes = releaseToLoadRes;\n }\n\n public void setNoMoreDataRes(int noMoreDataRes) {\n mNoMoreDataRes = noMoreDataRes;\n }\n\n public void setNoMoreDataClickListener(View.OnClickListener onClickListener) {\n mNoMoreDataClickListener = onClickListener;\n }\n\n @Override\n public int getType() {\n return TYPE_FOOTER;\n }\n\n @Override\n public void onReset(SmoothRefreshLayout frame) {\n super.onReset(frame);\n mNoMoreDataChangedView = false;\n mTitleTextView.setOnClickListener(null);\n }\n\n @Override\n public void onRefreshPrepare(SmoothRefreshLayout frame) {\n mArrowImageView.clearAnimation();\n mShouldShowLastUpdate = true;\n mNoMoreDataChangedView = false;\n tryUpdateLastUpdateTime();\n if (!TextUtils.isEmpty(mLastUpdateTimeKey)) {\n mLastUpdateTimeUpdater.start();\n }\n mProgressBar.setVisibility(INVISIBLE);\n mArrowImageView.setVisibility(VISIBLE);\n mTitleTextView.setVisibility(VISIBLE);\n mTitleTextView.setOnClickListener(null);\n if (frame.isEnabledPullToRefresh() && !frame.isDisabledPerformLoadMore()) {\n mTitleTextView.setText(mPullUpToLoadRes);\n } else {\n mTitleTextView.setText(mPullUpRes);\n }\n requestLayout();\n }\n\n @Override\n public void onRefreshBegin(SmoothRefreshLayout frame, T indicator) {\n mArrowImageView.clearAnimation();\n mArrowImageView.setVisibility(INVISIBLE);\n mProgressBar.setVisibility(VISIBLE);\n mTitleTextView.setVisibility(VISIBLE);\n mTitleTextView.setText(mLoadingRes);\n tryUpdateLastUpdateTime();\n }\n\n @Override\n public void onRefreshComplete(SmoothRefreshLayout frame, boolean isSuccessful) {\n mArrowImageView.clearAnimation();\n mArrowImageView.setVisibility(INVISIBLE);\n mProgressBar.setVisibility(INVISIBLE);\n mTitleTextView.setVisibility(VISIBLE);\n final boolean noMoreData = frame.isEnabledNoMoreData();\n if (frame.isRefreshSuccessful()) {\n mTitleTextView.setText(noMoreData ? mNoMoreDataRes : mLoadSuccessfulRes);\n mLastUpdateTime = System.currentTimeMillis();\n ClassicConfig.updateTime(getContext(), mLastUpdateTimeKey, mLastUpdateTime);\n } else {\n mTitleTextView.setText(noMoreData ? mNoMoreDataRes : mLoadFailRes);\n }\n mLastUpdateTimeUpdater.stop();\n mLastUpdateTextView.setVisibility(GONE);\n if (noMoreData) {\n mTitleTextView.setOnClickListener(mNoMoreDataClickListener);\n }\n }\n\n @Override\n public void onRefreshPositionChanged(SmoothRefreshLayout frame, byte status, T indicator) {\n final int offsetToLoadMore = indicator.getOffsetToLoadMore();\n final int currentPos = indicator.getCurrentPos();\n final int lastPos = indicator.getLastPos();\n if (frame.isEnabledNoMoreData()) {\n if (currentPos > lastPos && !mNoMoreDataChangedView) {\n mTitleTextView.setVisibility(VISIBLE);\n mLastUpdateTextView.setVisibility(GONE);\n mProgressBar.setVisibility(INVISIBLE);\n mLastUpdateTimeUpdater.stop();\n mArrowImageView.clearAnimation();\n mArrowImageView.setVisibility(GONE);\n mTitleTextView.setText(mNoMoreDataRes);\n mTitleTextView.setOnClickListener(mNoMoreDataClickListener);\n mNoMoreDataChangedView = true;\n }\n return;\n }\n mNoMoreDataChangedView = false;\n if (currentPos < offsetToLoadMore && lastPos >= offsetToLoadMore) {\n if (indicator.hasTouched() && status == SmoothRefreshLayout.SR_STATUS_PREPARE) {\n mTitleTextView.setVisibility(VISIBLE);\n if (frame.isEnabledPullToRefresh() && !frame.isDisabledPerformLoadMore()) {\n mTitleTextView.setText(mPullUpToLoadRes);\n } else {\n mTitleTextView.setText(mPullUpRes);\n }\n mArrowImageView.setVisibility(VISIBLE);\n mArrowImageView.clearAnimation();\n mArrowImageView.startAnimation(mReverseFlipAnimation);\n }\n } else if (currentPos > offsetToLoadMore && lastPos <= offsetToLoadMore) {\n if (indicator.hasTouched() && status == SmoothRefreshLayout.SR_STATUS_PREPARE) {\n mTitleTextView.setVisibility(VISIBLE);\n if (!frame.isEnabledPullToRefresh() && !frame.isDisabledPerformLoadMore()) {\n mTitleTextView.setText(mReleaseToLoadRes);\n }\n mArrowImageView.setVisibility(VISIBLE);\n mArrowImageView.clearAnimation();\n mArrowImageView.startAnimation(mFlipAnimation);\n }\n }\n }\n}", "public class ClassicHeader<T extends IIndicator> extends AbsClassicRefreshView<T> {\n @StringRes private int mPullDownToRefreshRes = R.string.sr_pull_down_to_refresh;\n @StringRes private int mPullDownRes = R.string.sr_pull_down;\n @StringRes private int mRefreshingRes = R.string.sr_refreshing;\n @StringRes private int mRefreshSuccessfulRes = R.string.sr_refresh_complete;\n @StringRes private int mRefreshFailRes = R.string.sr_refresh_failed;\n @StringRes private int mReleaseToRefreshRes = R.string.sr_release_to_refresh;\n\n public ClassicHeader(Context context) {\n this(context, null);\n }\n\n public ClassicHeader(Context context, AttributeSet attrs) {\n this(context, attrs, 0);\n }\n\n public ClassicHeader(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n mArrowImageView.setImageResource(R.drawable.sr_classic_arrow_icon);\n }\n\n public void setPullDownToRefreshRes(@StringRes int pullDownToRefreshRes) {\n mPullDownToRefreshRes = pullDownToRefreshRes;\n }\n\n public void setPullDownRes(@StringRes int pullDownRes) {\n mPullDownRes = pullDownRes;\n }\n\n public void setRefreshingRes(@StringRes int refreshingRes) {\n mRefreshingRes = refreshingRes;\n }\n\n public void setRefreshSuccessfulRes(@StringRes int refreshSuccessfulRes) {\n mRefreshSuccessfulRes = refreshSuccessfulRes;\n }\n\n public void setRefreshFailRes(@StringRes int refreshFailRes) {\n mRefreshFailRes = refreshFailRes;\n }\n\n public void setReleaseToRefreshRes(@StringRes int releaseToRefreshRes) {\n mReleaseToRefreshRes = releaseToRefreshRes;\n }\n\n @Override\n public int getType() {\n return TYPE_HEADER;\n }\n\n @Override\n public void onRefreshPrepare(SmoothRefreshLayout frame) {\n mArrowImageView.clearAnimation();\n mShouldShowLastUpdate = true;\n tryUpdateLastUpdateTime();\n if (!TextUtils.isEmpty(mLastUpdateTimeKey)) {\n mLastUpdateTimeUpdater.start();\n }\n mProgressBar.setVisibility(INVISIBLE);\n mArrowImageView.setVisibility(VISIBLE);\n mTitleTextView.setVisibility(VISIBLE);\n if (frame.isEnabledPullToRefresh()) {\n mTitleTextView.setText(mPullDownToRefreshRes);\n } else {\n mTitleTextView.setText(mPullDownRes);\n }\n requestLayout();\n }\n\n @Override\n public void onRefreshBegin(SmoothRefreshLayout frame, T indicator) {\n mArrowImageView.clearAnimation();\n mArrowImageView.setVisibility(INVISIBLE);\n mProgressBar.setVisibility(VISIBLE);\n mTitleTextView.setVisibility(VISIBLE);\n mTitleTextView.setText(mRefreshingRes);\n tryUpdateLastUpdateTime();\n }\n\n @Override\n public void onRefreshComplete(SmoothRefreshLayout frame, boolean isSuccessful) {\n mArrowImageView.clearAnimation();\n mArrowImageView.setVisibility(INVISIBLE);\n mProgressBar.setVisibility(INVISIBLE);\n mTitleTextView.setVisibility(VISIBLE);\n if (frame.isRefreshSuccessful()) {\n mTitleTextView.setText(mRefreshSuccessfulRes);\n mLastUpdateTime = System.currentTimeMillis();\n ClassicConfig.updateTime(getContext(), mLastUpdateTimeKey, mLastUpdateTime);\n } else {\n mTitleTextView.setText(mRefreshFailRes);\n }\n mLastUpdateTimeUpdater.stop();\n mLastUpdateTextView.setVisibility(GONE);\n }\n\n @Override\n public void onRefreshPositionChanged(SmoothRefreshLayout frame, byte status, T indicator) {\n final int offsetToRefresh = indicator.getOffsetToRefresh();\n final int currentPos = indicator.getCurrentPos();\n final int lastPos = indicator.getLastPos();\n\n if (currentPos < offsetToRefresh && lastPos >= offsetToRefresh) {\n if (indicator.hasTouched() && status == SmoothRefreshLayout.SR_STATUS_PREPARE) {\n mTitleTextView.setVisibility(VISIBLE);\n if (frame.isEnabledPullToRefresh()) {\n mTitleTextView.setText(mPullDownToRefreshRes);\n } else {\n mTitleTextView.setText(mPullDownRes);\n }\n mArrowImageView.setVisibility(VISIBLE);\n mArrowImageView.clearAnimation();\n mArrowImageView.startAnimation(mReverseFlipAnimation);\n }\n } else if (currentPos > offsetToRefresh && lastPos <= offsetToRefresh) {\n if (indicator.hasTouched() && status == SmoothRefreshLayout.SR_STATUS_PREPARE) {\n mTitleTextView.setVisibility(VISIBLE);\n if (!frame.isEnabledPullToRefresh()) {\n mTitleTextView.setText(mReleaseToRefreshRes);\n }\n mArrowImageView.setVisibility(VISIBLE);\n mArrowImageView.clearAnimation();\n mArrowImageView.startAnimation(mFlipAnimation);\n }\n }\n }\n}", "public interface IIndicator {\n float DEFAULT_RATIO_TO_REFRESH = 1f;\n float DEFAULT_MAX_MOVE_RATIO = 0f;\n float DEFAULT_RATIO_TO_KEEP = 1;\n float DEFAULT_RESISTANCE = 1.65f;\n int START_POS = 0;\n\n @MovingStatus\n int getMovingStatus();\n\n int getCurrentPos();\n\n boolean hasTouched();\n\n boolean hasMoved();\n\n int getOffsetToRefresh();\n\n int getOffsetToLoadMore();\n\n float getOffset();\n\n float getRawOffset();\n\n float[] getRawOffsets();\n\n int getLastPos();\n\n int getHeaderHeight();\n\n int getFooterHeight();\n\n boolean hasLeftStartPosition();\n\n boolean hasJustLeftStartPosition();\n\n boolean hasJustBackToStartPosition();\n\n boolean isJustReturnedOffsetToRefresh();\n\n boolean isJustReturnedOffsetToLoadMore();\n\n boolean isOverOffsetToKeepHeaderWhileLoading();\n\n boolean isOverOffsetToRefresh();\n\n boolean isOverOffsetToKeepFooterWhileLoading();\n\n boolean isOverOffsetToLoadMore();\n\n int getOffsetToKeepHeaderWhileLoading();\n\n int getOffsetToKeepFooterWhileLoading();\n\n boolean isAlreadyHere(int to);\n\n float getCanMoveTheMaxDistanceOfHeader();\n\n float getCanMoveTheMaxDistanceOfFooter();\n\n @NonNull\n float[] getFingerDownPoint();\n\n @NonNull\n float[] getLastMovePoint();\n\n float getCurrentPercentOfRefreshOffset();\n\n float getCurrentPercentOfLoadMoreOffset();\n\n void checkConfig();\n\n /**\n * Created by dkzwm on 2017/10/24.\n *\n * @author dkzwm\n */\n interface IOffsetCalculator {\n float calculate(@MovingStatus int status, int currentPos, float offset);\n }\n}" ]
import android.app.Application; import me.dkzwm.widget.srl.IRefreshViewCreator; import me.dkzwm.widget.srl.SmoothRefreshLayout; import me.dkzwm.widget.srl.extra.IRefreshView; import me.dkzwm.widget.srl.extra.footer.ClassicFooter; import me.dkzwm.widget.srl.extra.header.ClassicHeader; import me.dkzwm.widget.srl.indicator.IIndicator;
package me.dkzwm.widget.srl.sample; /** * Created by dkzwm on 2017/6/28. * * @author dkzwm */ public class DemoApplication extends Application { @Override public void onCreate() { super.onCreate(); SmoothRefreshLayout.setDefaultCreator( new IRefreshViewCreator() { @Override
public IRefreshView<IIndicator> createHeader(SmoothRefreshLayout layout) {
5
ajonkisz/TraVis
src/travis/view/project/graph/GraphTooltip.java
[ "public class UIHelper {\n\n private static final UIHelper INSTANCE = new UIHelper();\n\n public enum MessageType {\n INFORMATION, WARNING, ERROR\n }\n\n public enum Mode {\n ATTACH, PLAYBACK\n }\n\n private Mode mode;\n\n private final JFileChooser fc;\n private volatile File currentDirectory;\n\n private final Vector<Attacher> attachers;\n\n private final MainFrame frame;\n private final TreePanel treePanel;\n private final AttacherPanel attacherPanel;\n private final ConsolePanel consolePanel;\n private final GraphPanel graph;\n private final GraphTooltip tooltip;\n private final GraphLayeredPane graphLayeredPane;\n private final SettingsPane settingsPane;\n private final PlaybackPanel playbackPanel;\n\n private final ExecutorService dispatcher;\n\n private UIHelper() {\n dispatcher = Executors.newFixedThreadPool(2);\n\n fc = new JFileChooser();\n fc.setAcceptAllFileFilterUsed(false);\n\n attachers = new Vector<Attacher>();\n\n frame = new MainFrame();\n treePanel = new TreePanel();\n attacherPanel = new AttacherPanel();\n consolePanel = new ConsolePanel();\n graph = new GraphPanel();\n tooltip = new GraphTooltip();\n graphLayeredPane = new GraphLayeredPane(graph, tooltip);\n settingsPane = new SettingsPane();\n playbackPanel = new PlaybackPanel();\n\n mode = Mode.ATTACH;\n }\n\n public static UIHelper getInstance() {\n return INSTANCE;\n }\n\n public void populateFrame() {\n fc.setCurrentDirectory(new File(System.getProperty(\"user.dir\")));\n currentDirectory = fc.getCurrentDirectory();\n frame.populateFrame();\n changeMode(Mode.ATTACH);\n }\n\n private void changeMode(Mode mode) {\n this.mode = mode;\n if (mode == Mode.ATTACH) {\n frame.setAttachMode();\n } else if (mode == Mode.PLAYBACK) {\n frame.setPlaybackMode();\n }\n }\n\n public Mode getMode() {\n return mode;\n }\n\n public Vector<Attacher> getAttachers() {\n return new Vector<Attacher>(attachers);\n }\n\n public void killAllAttachers() {\n synchronized (attachers) {\n for (Attacher attacher : attachers) {\n attacher.detach();\n }\n attachers.clear();\n }\n repaintAttachersTable();\n }\n\n public void startAttacher(Attacher attacher) {\n getProjectTree().setupScriptGenerator();\n\n try {\n attacher.start();\n } catch (IOException e) {\n displayException(e);\n }\n }\n\n public void addAndStartAttacher(final Attacher attacher) {\n final JDialog dialog = getAndShowProgressBarWindow(Messages\n .get(\"attaching\"));\n dispatcher.submit(new Runnable() {\n @Override\n public void run() {\n attachers.add(attacher);\n getProjectTree().generateScript();\n\n try {\n attacher.start();\n } catch (IOException e) {\n displayException(e);\n }\n repaintAttachersTable();\n\n dialog.setVisible(false);\n }\n });\n }\n\n public void removeAndKillAttacher(Attacher attacher) {\n attacher.detach();\n attachers.remove(attacher);\n repaintAttachersTable();\n }\n\n public ConsolePanel getConsolePanel() {\n return consolePanel;\n }\n\n public File getCurrentDirectory() {\n return currentDirectory;\n }\n\n public void setCurrentDirectory(File currentDirectory) {\n this.currentDirectory = currentDirectory;\n }\n\n public void updatePlaybackMode() {\n SwingUtilities.invokeLater(new Runnable() {\n public void run() {\n playbackPanel.updatePlaybackMode();\n }\n });\n }\n\n public void updatePlaybackSpeed() {\n playbackPanel.updatePlaybackSpeed();\n }\n\n public TreePanel getTreePanel() {\n return treePanel;\n }\n\n public ProjectTree getProjectTree() {\n return treePanel.getTree();\n }\n\n public AttacherPanel getAttacherPanel() {\n return attacherPanel;\n }\n\n public GraphPanel getGraph() {\n return graph;\n }\n\n public GraphTooltip getTooltip() {\n return tooltip;\n }\n\n public GraphLayeredPane getGraphLayeredPane() {\n return graphLayeredPane;\n }\n\n public SettingsPane getSettingsPane() {\n return settingsPane;\n }\n\n public PlaybackPanel getPlaybackPanel() {\n return playbackPanel;\n }\n\n public MainFrame getMainFrame() {\n return frame;\n }\n\n public void openClasspath() {\n if (!askToKillAllIfConnected())\n return;\n\n setupFilechooserForDirs();\n if (checkClassPath()) {\n final JDialog dialog = getAndShowProgressBarWindow(Messages\n .get(\"opening.classpath\"));\n dispatcher.submit(new Runnable() {\n @Override\n public void run() {\n treePanel.buildTree(fc.getSelectedFile());\n UIGraphicsHelper.getInstance()\n .resetConnectionsAndRepaintTree();\n dialog.setVisible(false);\n }\n });\n }\n }\n\n public void attachClasspath() {\n if (!askToKillAllIfConnected())\n return;\n\n setupFilechooserForDirs();\n if (checkClassPath()) {\n final JDialog dialog = getAndShowProgressBarWindow(Messages\n .get(\"opening.classpath\"));\n dispatcher.submit(new Runnable() {\n @Override\n public void run() {\n treePanel.attachTree(fc.getSelectedFile());\n UIGraphicsHelper.getInstance()\n .resetConnectionsAndRepaintTree();\n dialog.setVisible(false);\n }\n });\n }\n }\n\n private boolean checkClassPath() {\n if (fc.showOpenDialog(frame) != JFileChooser.APPROVE_OPTION)\n return false;\n\n changeMode(Mode.ATTACH);\n currentDirectory = fc.getSelectedFile();\n File f = fc.getSelectedFile();\n if (!isClasspathValid(f)) {\n displayMessage(Messages.get(\"file.not.valid\"), MessageType.ERROR);\n return false;\n }\n return true;\n }\n\n private boolean isClasspathValid(File f) {\n return f.isDirectory() && f.canRead();\n }\n\n private void setupFilechooserForDirs() {\n fc.setCurrentDirectory(getCurrentDirectory());\n fc.resetChoosableFileFilters();\n fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);\n fc.setFileFilter(new FileFilter() {\n @Override\n public String getDescription() {\n return Messages.get(\"directories.only\");\n }\n\n @Override\n public boolean accept(File f) {\n return f.isDirectory();\n }\n });\n }\n\n public void openFile() {\n if (!askToKillAllIfConnected())\n return;\n\n setupFilechooserForFiles();\n if (fc.showOpenDialog(frame) != JFileChooser.APPROVE_OPTION)\n return;\n\n final JDialog dialog = getAndShowProgressBarWindow(Messages\n .get(\"opening.file\"));\n changeMode(Mode.PLAYBACK);\n currentDirectory = fc.getCurrentDirectory();\n\n dispatcher.submit(new Runnable() {\n @Override\n public void run() {\n try {\n final FileParser fp = new FileParser(fc.getSelectedFile());\n UIGraphicsHelper.getInstance().resetConnections();\n getProjectTree().setRoot(fp);\n playbackPanel.setFileParser(fp);\n\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n dialog.setVisible(false);\n }\n });\n } catch (IOException e) {\n displayException(e);\n } catch (ClassNotFoundException e) {\n displayException(e);\n }\n }\n });\n }\n\n public JDialog getAndShowProgressBarWindow(String text) {\n JPanel panel = new JPanel(new BorderLayout());\n JLabel label = new JLabel(text);\n label.setHorizontalAlignment(SwingConstants.CENTER);\n JProgressBar progressBar = new JProgressBar();\n progressBar.setIndeterminate(true);\n\n panel.add(label, BorderLayout.CENTER);\n panel.add(progressBar, BorderLayout.PAGE_END);\n\n final JOptionPane optionPane = new JOptionPane(panel,\n JOptionPane.PLAIN_MESSAGE, JOptionPane.DEFAULT_OPTION, null,\n new Object[]{}, null);\n final JDialog dialog = optionPane.createDialog(frame,\n Messages.get(\"work.in.progress\"));\n dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);\n\n dispatcher.submit(new Runnable() {\n @Override\n public void run() {\n dialog.pack();\n dialog.setResizable(false);\n dialog.setVisible(true);\n }\n });\n\n return dialog;\n }\n\n public void saveFileAs() {\n if (!askToKillAllIfConnected())\n return;\n\n setupFilechooserForFiles();\n if (fc.showSaveDialog(frame) != JFileChooser.APPROVE_OPTION)\n return;\n\n currentDirectory = fc.getCurrentDirectory();\n File f = fc.getSelectedFile();\n if (!f.getName().matches(\".*\\\\.vis\")) {\n f = new File(f.getAbsolutePath() + \".vis\");\n }\n\n final JDialog dialog = getAndShowProgressBarWindow(Messages\n .get(\"saving.file\"));\n final File fFinal = f;\n dispatcher.submit(new Runnable() {\n @Override\n public void run() {\n getProjectTree().setupScriptGenerator();\n try {\n ScriptHandler.getInstance().saveToFile(fFinal,\n getProjectTree().getCheckedPaths());\n } catch (IOException e) {\n displayException(e);\n }\n dialog.setVisible(false);\n }\n });\n }\n\n public void saveSubtrace() {\n if (mode != Mode.PLAYBACK)\n return;\n\n playbackPanel.pause();\n\n // Ensure subtrace is selected\n PlaybackProgress progress = playbackPanel.getPlaybackProgress();\n double start = progress.getPlaybackStart();\n double end = progress.getPlaybackEnd();\n if (start == 0d && end == 1d) {\n displayMessage(Messages.get(\"no.subtrace\"), MessageType.INFORMATION);\n return;\n }\n\n // Ensure playback attacher\n Playback playback = playbackPanel.getPlayback();\n if (playback == null) {\n displayMessage(Messages.get(\"no.playback\"), MessageType.ERROR);\n return;\n }\n\n setupFilechooserForFiles();\n if (fc.showSaveDialog(frame) != JFileChooser.APPROVE_OPTION)\n return;\n\n currentDirectory = fc.getCurrentDirectory();\n File selectedFile = fc.getSelectedFile();\n final File f = selectedFile.getName().matches(\".*\\\\.vis\") ? selectedFile\n : new File(selectedFile.getAbsolutePath() + \".vis\");\n\n // Ensure saving to a different file\n final File scriptFile = playback.getScript();\n if (f.equals(scriptFile)) {\n displayMessage(Messages.get(\"subtrace.to.trace\"), MessageType.ERROR);\n saveSubtrace();\n return;\n }\n\n final long from = (long) (playback.getTracesStart() + (double) playback\n .getTracesLength() * start);\n final long to = (long) (playback.getTracesStart() + (double) playback\n .getTracesLength() * end);\n\n final JDialog dialog = getAndShowProgressBarWindow(Messages\n .get(\"saving.subtrace\"));\n\n dispatcher.submit(new Runnable() {\n @Override\n public void run() {\n getProjectTree().generateScript();\n try {\n ScriptHandler.getInstance().saveToFile(f,\n getProjectTree().getCheckedPaths());\n ScriptHandler.copyLines(scriptFile, f, from, to);\n } catch (IOException e) {\n displayException(e);\n }\n dialog.setVisible(false);\n }\n });\n\n }\n\n private void setupFilechooserForFiles() {\n fc.setCurrentDirectory(getCurrentDirectory());\n fc.resetChoosableFileFilters();\n fc.setFileSelectionMode(JFileChooser.FILES_ONLY);\n fc.setFileFilter(new FileFilter() {\n @Override\n public String getDescription() {\n return \".vis\";\n }\n\n @Override\n public boolean accept(File f) {\n return f.isDirectory() || f.getName().matches(\".*\\\\.vis\");\n }\n });\n }\n\n /**\n * Asks user, in form of a dialog window, if he wants to disconnect from\n * attached processes if connected to any.\n *\n * @return true if disconnected from attached processes, false otherwise.\n */\n public boolean askToKillAllIfConnected() {\n if (mode == Mode.PLAYBACK) {\n Playback p = playbackPanel.getPlayback();\n if (p != null) {\n p.pause();\n }\n return true;\n }\n if (attachers.isEmpty()) {\n return true;\n }\n if (displayConfirmation(Messages.get(\"disconnect.confirm\"))) {\n killAllAttachers();\n return true;\n }\n return false;\n }\n\n public void repaintAttachersTable() {\n attacherPanel.getAttachersTable().repaintTable();\n }\n\n public void displayMessage(String msg, MessageType type) {\n String title;\n int messageType;\n switch (type) {\n case ERROR:\n title = Messages.get(\"error\");\n messageType = JOptionPane.ERROR_MESSAGE;\n break;\n case INFORMATION:\n title = Messages.get(\"information\");\n messageType = JOptionPane.INFORMATION_MESSAGE;\n break;\n case WARNING:\n title = Messages.get(\"warning\");\n messageType = JOptionPane.WARNING_MESSAGE;\n break;\n default:\n return;\n }\n JOptionPane.showMessageDialog(frame, msg, title, messageType);\n }\n\n public boolean displayConfirmation(String msg) {\n JPanel panel = new JPanel();\n panel.add(new JLabel(msg));\n int status = JOptionPane.showConfirmDialog(frame, panel,\n Messages.get(\"confirm\"), JOptionPane.OK_CANCEL_OPTION,\n JOptionPane.PLAIN_MESSAGE, null);\n return status == JOptionPane.OK_OPTION;\n }\n\n public void displayException(Exception e) {\n killAllAttachers();\n e.printStackTrace();\n\n StringBuilder sb = new StringBuilder(e.toString());\n for (StackTraceElement trace : e.getStackTrace()) {\n sb.append(\"\\n at \");\n sb.append(trace);\n }\n JTextArea textArea = new JTextArea(sb.toString());\n textArea.setEditable(false);\n JScrollPane scrollPane = new JScrollPane(textArea);\n scrollPane.setPreferredSize(new Dimension(500, 250));\n\n JOptionPane.showMessageDialog(frame, scrollPane,\n Messages.get(\"exception\"), JOptionPane.ERROR_MESSAGE);\n }\n\n}", "public enum Mode {\n PACKAGE, CLASS, METHOD\n}", "public class Util {\n\n public static final RenderingHints HINTS;\n\n static {\n HINTS = new RenderingHints(RenderingHints.KEY_ANTIALIASING,\n RenderingHints.VALUE_ANTIALIAS_ON);\n HINTS.put(RenderingHints.KEY_TEXT_ANTIALIASING,\n RenderingHints.VALUE_TEXT_ANTIALIAS_ON);\n }\n\n public static JButton getButtonWithIcon(String name) {\n JButton b = new JButton(IconFactory.createImageIcon(name + \".png\"));\n b.setPressedIcon(IconFactory.createImageIcon(name + \"_pressed.png\"));\n return b;\n }\n\n public static int pow(int num, int power) {\n if (power < 1) {\n return 1;\n }\n return num * pow(num, --power);\n }\n\n public static boolean containsFlag(int flags, int flag) {\n return (flags & flag) == flag;\n }\n\n public static int toggleFlag(int flags, int flag, boolean enabled) {\n if (enabled) {\n flags |= flag;\n } else {\n flags &= ~flag;\n }\n return flags;\n }\n\n public static JSlider createSlider(int min, int max, int init,\n int majorTick, int minorTick) {\n JSlider slider = new JSlider(SwingConstants.HORIZONTAL, min, max, init);\n slider.setMajorTickSpacing(majorTick);\n slider.setMinorTickSpacing(minorTick);\n slider.setPaintLabels(true);\n slider.setPaintTicks(true);\n return slider;\n }\n\n public static JPanel createBorderedPanel(String title,\n Component... components) {\n return createBorderedPanel(title, \"\", components);\n }\n\n public static JPanel createBorderedPanel(String title, String constraints,\n Component... components) {\n JPanel panel = new JPanel(new MigLayout(\"fillx, insets 0, gap 0, \"\n + constraints));\n if (components == null || components.length == 0) {\n return panel;\n }\n panel.setBorder(BorderFactory.createTitledBorder(\n BorderFactory.createLineBorder(Color.BLACK), title,\n TitledBorder.CENTER, TitledBorder.DEFAULT_POSITION));\n for (Component component : components) {\n panel.add(component, \"grow\");\n }\n return panel;\n }\n\n}", "public class ConnectionPainter {\n\n private static final float MIN_ALPHA = 0.1f;\n private static final float MAX_ALPHA = 0.6f;\n\n private final TreeRepresentation treeRep;\n private final LinkedBlockingDeque<TraceInfo> traces;\n private Collection<GraphBspline> oldSplines;\n private volatile ExecutionPoint execPoint;\n\n private volatile BufferedImage image;\n private volatile boolean needRepaint;\n\n public ConnectionPainter(TreeRepresentation treeRep) {\n this.treeRep = treeRep;\n traces = new LinkedBlockingDeque<TraceInfo>();\n oldSplines = new LinkedHashSet<GraphBspline>();\n needRepaint = true;\n }\n\n public ExecutionPoint getExecutionPoint() {\n return execPoint;\n }\n\n public void reset() {\n traces.clear();\n oldSplines.clear();\n needRepaint = true;\n }\n\n public void setNeedRepaint(boolean needRepaint) {\n this.needRepaint = needRepaint;\n }\n\n public Collection<GraphBspline> getSplines() {\n return oldSplines;\n }\n\n public void lineTo(TraceInfo trace) {\n needRepaint = true;\n traces.addFirst(trace);\n while (traces.size() > Settings.getInstance().getCachedTracesNo()) {\n traces.removeLast();\n }\n }\n\n public void createConnections(ControlPoint cpStart,\n TraceInfo previousTrace, Iterator<TraceInfo> it,\n ConnectionData data, boolean isFirst) {\n for (; it.hasNext(); ) {\n TraceInfo trace = it.next();\n ComponentData cd = treeRep.getMethods()[trace.getMethodId()];\n\n // cd (method) is null only when not selected / visible\n if (cd == null)\n continue;\n data.finishedOnReturn = true;\n if (isFirst) {\n cpStart = null;\n previousTrace = null;\n }\n\n if (trace.isReturnCall()) {\n if (cpStart == null) {\n createConnections(null, null, it, data, false);\n } else {\n return;\n }\n } else {\n ControlPoint cpEnd = cd.getControlPoint();\n data.ep.setCenter(cpEnd);\n data.ep.setTrace(trace);\n data.ep.setComponentData(cd);\n if (cpStart == null) {\n cpStart = cpEnd;\n previousTrace = trace;\n createConnections(cpStart, trace, it, data, false);\n } else {\n // The commented out part causes graph to not be drawn correctly\n // TODO All threads should be drawn separately from a different collection\n//\t\t\t\t\tif (previousTrace.getThreadId() != trace.getThreadId())\n//\t\t\t\t\t\tcontinue;\n\n data.finishedOnReturn = false;\n Point[] path = cpStart.getPathTo(cpEnd);\n // TODO Deal with recursive calls (path.length == 1).\n GraphBspline spline = new GraphBspline(previousTrace,\n trace, path);\n data.addSpline(spline);\n createConnections(cpEnd, trace, it, data, false);\n }\n }\n }\n }\n\n public BufferedImage getImage(int width, int height) {\n if (!needRepaint)\n return image;\n\n needRepaint = false;\n BufferedImage img = new BufferedImage(width, height,\n BufferedImage.TYPE_INT_ARGB);\n Graphics2D g2 = (Graphics2D) img.getGraphics();\n g2.setRenderingHints(Util.HINTS);\n\n ConnectionData data = new ConnectionData();\n populateSplines(data);\n\n int size = Math.min(data.splines.size(), Settings.getInstance()\n .getMaxCurvesNo());\n\n int counter = data.splines.size();\n Set<GraphBspline> trimmedSplines = new LinkedHashSet<GraphBspline>(size);\n for (GraphBspline spline : data.splines) {\n // Skip splines that are outside max curve limit.\n if (counter > size) {\n counter--;\n continue;\n }\n if (!data.ignoreOldTraces)\n trimmedSplines.remove(spline);\n trimmedSplines.add(spline);\n }\n\n size = Math.min(trimmedSplines.size(), Settings.getInstance()\n .getMaxCurvesNo());\n int power = 1;\n int sizePowered = Util.pow(size, power);\n int i = 1;\n for (GraphBspline spline : trimmedSplines) {\n if (i == size) {\n if (data.finishedOnReturn)\n spline.draw(g2, MAX_ALPHA);\n else\n spline.draw(g2, 1f);\n } else {\n int iPowered = Util.pow(++i, power);\n float alpha = MIN_ALPHA + ((float) iPowered / sizePowered)\n * (MAX_ALPHA - MIN_ALPHA);\n spline.draw(g2, alpha);\n }\n }\n\n data.ep.draw(g2);\n execPoint = data.ep;\n\n displayExecPointTooltip(data.ep);\n\n g2.dispose();\n image = img;\n return image;\n }\n\n private void displayExecPointTooltip(ExecutionPoint ep) {\n UIHelper.getInstance().getTooltip().displayExecutionPointTooltip(ep);\n }\n\n private void populateSplines(ConnectionData data) {\n Iterator<TraceInfo> it;\n Iterator<TraceInfo> it2;\n synchronized (traces) {\n if (traces.isEmpty()) {\n oldSplines = data.splines;\n }\n\n it = traces.descendingIterator();\n it2 = traces.iterator();\n }\n\n createConnections(null, null, it, data, true);\n if (data.finishedOnReturn)\n moveExecutionToReturn(it2, data);\n\n this.oldSplines = data.splines;\n }\n\n private void moveExecutionToReturn(Iterator<TraceInfo> it,\n ConnectionData data) {\n int returns = 0;\n for (; it.hasNext(); ) {\n TraceInfo trace = it.next();\n ComponentData cd = treeRep.getMethods()[trace.getMethodId()];\n if (cd == null) {\n continue;\n }\n if (!trace.isReturnCall()) {\n if (returns != 0) {\n returns--;\n continue;\n }\n data.ep.setCenter(cd.getControlPoint());\n data.ep.setTrace(trace);\n data.ep.setComponentData(cd);\n return;\n } else {\n returns++;\n }\n }\n // Could only be achieved if didn't find a point\n data.ep.setCenter(null);\n data.ep.setTrace(null);\n data.ep.setComponentData(null);\n }\n\n private class ConnectionData {\n private final Collection<GraphBspline> splines;\n private boolean finishedOnReturn;\n private final ExecutionPoint ep;\n private final boolean ignoreOldTraces;\n\n public ConnectionData() {\n ignoreOldTraces = Settings.getInstance().isDrawingUniqueTraces();\n if (ignoreOldTraces) {\n splines = new LinkedHashSet<GraphBspline>();\n } else {\n splines = new LinkedList<GraphBspline>();\n }\n finishedOnReturn = false;\n ep = new ExecutionPoint();\n }\n\n public void addSpline(GraphBspline spline) {\n if (ignoreOldTraces) {\n splines.remove(spline);\n }\n splines.add(spline);\n }\n }\n\n}", "public class ExecutionPoint {\n\n private Point center;\n private TraceInfo trace;\n private ComponentData cd;\n private final Ellipse2D oval;\n\n public ExecutionPoint() {\n this.oval = new Ellipse2D.Double();\n }\n\n public ExecutionPoint(Point center) {\n this.center = center;\n this.oval = new Ellipse2D.Double();\n }\n\n public Point getCenter() {\n return center;\n }\n\n public void setCenter(Point center) {\n this.center = center;\n }\n\n public void draw(Graphics2D g2) {\n if (center == null)\n return;\n\n int size = Settings.getInstance().getExecutionPointSize();\n g2.setColor(Settings.getInstance().getColors().getExecutionPointColor());\n oval.setFrame(center.x - size, center.y - size, size * 2, size * 2);\n g2.fill(oval);\n }\n\n public boolean contains(Point p) {\n return oval.contains(p);\n }\n\n public ComponentData getComponentData() {\n return cd;\n }\n\n public void setComponentData(ComponentData cd) {\n this.cd = cd;\n }\n\n public TraceInfo getTrace() {\n return trace;\n }\n\n public void setTrace(TraceInfo trace) {\n this.trace = trace;\n }\n\n}", "public class GraphBspline extends Bspline {\n\n private final TraceInfo callerTrace;\n private final TraceInfo calleeTrace;\n\n public GraphBspline(TraceInfo callerTrace, TraceInfo calleeTrace,\n Point[] points) {\n super(points);\n this.callerTrace = callerTrace;\n this.calleeTrace = calleeTrace;\n }\n\n public TraceInfo getCallerTrace() {\n return callerTrace;\n }\n\n public TraceInfo getCalleeTrace() {\n return calleeTrace;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj instanceof Bspline) {\n Bspline s2 = (Bspline) obj;\n return getStartPointX() == s2.getStartPointX()\n && getStartPointY() == s2.getStartPointY()\n && getEndPointX() == s2.getEndPointX()\n && getEndPointY() == s2.getEndPointY();\n }\n return super.equals(obj);\n }\n\n @Override\n public int hashCode() {\n int hash = 7;\n int mult = 37;\n hash = hash * mult + getStartPointX();\n hash = hash * mult + getStartPointY();\n hash = hash * mult + getEndPointX();\n hash = hash * mult + getEndPointY();\n return hash;\n }\n\n}", "public class Settings extends Observable {\n\n private static final Settings INSTANCE = new Settings();\n\n public enum Type {\n GRAPH, GRAPH_CONNECTION, PLAYBACK_SPEED, PLAYBACK_MODE\n }\n\n public static final int STRUCT_PACKAGE = 1;\n public static final int STRUCT_CLASS = 1 << 1;\n public static final int STRUCT_METHOD = 1 << 2;\n public static final int STRUCT_ORDINARY_CLASS = 1 << 3;\n public static final int STRUCT_ABSTRACT_CLASS = 1 << 4;\n public static final int STRUCT_INTERFACE = 1 << 5;\n public static final int STRUCT_ENUM = 1 << 6;\n public static final int STRUCT_PUBLIC_METHOD = 1 << 7;\n public static final int STRUCT_PRIVATE_METHOD = 1 << 8;\n public static final int STRUCT_PROTECTED_METHOD = 1 << 9;\n public static final int STRUCT_DEFAULT_METHOD = 1 << 10;\n private int structsToDraw;\n\n private int graphRotate;\n private int graphPackageLayersToHide;\n private boolean packageEnabled;\n\n private int packageGap;\n private int classGap;\n private int layerGap;\n\n private int packageHeightPercent;\n private int classHeightPercent;\n private int methodHeightPercent;\n\n private double curveBundlingStrength;\n\n private int cachedTracesNo;\n private int maxCurvesNo;\n private int curvesPerSec;\n\n private boolean minDepth;\n private boolean drawingInnerLayout;\n\n private final ModifiableColor colors;\n\n private int executionPointSize;\n\n private boolean drawingUniqueTraces;\n\n private Settings() {\n structsToDraw = STRUCT_PACKAGE | STRUCT_CLASS | STRUCT_METHOD\n | STRUCT_ORDINARY_CLASS | STRUCT_ABSTRACT_CLASS\n | STRUCT_INTERFACE | STRUCT_ENUM | STRUCT_PUBLIC_METHOD\n | STRUCT_PRIVATE_METHOD | STRUCT_PROTECTED_METHOD\n | STRUCT_DEFAULT_METHOD;\n\n graphRotate = 0;\n graphPackageLayersToHide = 0;\n packageEnabled = true;\n\n packageGap = 6;\n classGap = 3;\n layerGap = 5;\n\n packageHeightPercent = 5;\n classHeightPercent = 10;\n methodHeightPercent = 15;\n\n curveBundlingStrength = 0.75;\n\n cachedTracesNo = 50000;\n maxCurvesNo = 100;\n curvesPerSec = 1;\n\n minDepth = false;\n drawingInnerLayout = false;\n\n colors = new ModifiableColor();\n\n executionPointSize = 3;\n\n drawingUniqueTraces = true;\n }\n\n public int getExecutionPointSize() {\n return executionPointSize;\n }\n\n public void setExecutionPointSize(int executionPointSize) {\n this.executionPointSize = executionPointSize;\n setChanged(Type.GRAPH_CONNECTION);\n }\n\n public ModifiableColor getColors() {\n return colors;\n }\n\n public void setColors(StructColor colors) {\n this.colors.setColors(colors);\n setChanged(Type.GRAPH);\n }\n\n public boolean isDrawingClass(StructComponent comp) {\n if (!(comp instanceof StructClass)) return true;\n\n if (comp.isOrdinaryClass()\n && isDrawingStruct(STRUCT_ORDINARY_CLASS)) {\n return true;\n }\n else if (comp.isInterface() && isDrawingStruct(STRUCT_INTERFACE)) {\n return true;\n }\n // This extra check must be here as according to ASM and interface\n // is also an abstract class.\n else if (comp.isInterface() && !isDrawingStruct(STRUCT_INTERFACE)) {\n return false;\n }\n else if (comp.isAbstract() && isDrawingStruct(STRUCT_ABSTRACT_CLASS)) {\n return true;\n }\n else return comp.isEnum() && isDrawingStruct(STRUCT_ENUM);\n }\n\n public boolean isDrawingMethod(StructComponent comp) {\n if (!(comp instanceof StructMethod)) return true;\n\n if (comp.getVisibility() == Visibility.PUBLIC\n && isDrawingStruct(STRUCT_PUBLIC_METHOD)) {\n return true;\n }\n else if (comp.getVisibility() == Visibility.PRIVATE\n && isDrawingStruct(STRUCT_PRIVATE_METHOD)) {\n return true;\n }\n else if (comp.getVisibility() == Visibility.PROTECTED\n && isDrawingStruct(STRUCT_PROTECTED_METHOD)) {\n return true;\n }\n else return comp.getVisibility() == Visibility.DEFAULT\n && isDrawingStruct(STRUCT_DEFAULT_METHOD);\n }\n\n public boolean isDrawingStruct(StructComponent comp) {\n if (comp instanceof StructPackage) {\n return isDrawingStruct(STRUCT_PACKAGE);\n } else if (comp instanceof StructClass) {\n if (!isDrawingStruct(STRUCT_CLASS)) {\n return false;\n }\n if (comp.isOrdinaryClass()\n && isDrawingStruct(STRUCT_ORDINARY_CLASS)) {\n return true;\n }\n if (comp.isAbstract() && isDrawingStruct(STRUCT_ABSTRACT_CLASS)) {\n return true;\n }\n if (comp.isInterface() && isDrawingStruct(STRUCT_INTERFACE)) {\n return true;\n }\n return comp.isEnum() && isDrawingStruct(STRUCT_ENUM);\n } else if (comp instanceof StructMethod) {\n if (!isDrawingStruct(STRUCT_METHOD)) {\n return false;\n }\n if (comp.getVisibility() == Visibility.PUBLIC\n && isDrawingStruct(STRUCT_PUBLIC_METHOD)) {\n return true;\n }\n if (comp.getVisibility() == Visibility.PRIVATE\n && isDrawingStruct(STRUCT_PRIVATE_METHOD)) {\n return true;\n }\n if (comp.getVisibility() == Visibility.PROTECTED\n && isDrawingStruct(STRUCT_PROTECTED_METHOD)) {\n return true;\n }\n return comp.getVisibility() == Visibility.DEFAULT\n && isDrawingStruct(STRUCT_DEFAULT_METHOD);\n } else {\n return true;\n }\n }\n\n public boolean isDrawingStruct(int struct) {\n return Util.containsFlag(structsToDraw, struct);\n }\n\n public boolean isMinDepth() {\n return minDepth;\n }\n\n public void setMinDepth(boolean minDepth) {\n this.minDepth = minDepth;\n setChanged(Type.GRAPH);\n }\n\n public boolean isDrawingInnerLayout() {\n return drawingInnerLayout;\n }\n\n public void setDrawingInnerLayout(boolean drawInnerLayout) {\n this.drawingInnerLayout = drawInnerLayout;\n setChanged(Type.GRAPH);\n }\n\n public int getMaxCurvesNo() {\n return maxCurvesNo;\n }\n\n public void setMaxCurvesNo(int maxCurvesNo) {\n if (maxCurvesNo < 1)\n maxCurvesNo = 1;\n this.maxCurvesNo = maxCurvesNo;\n setChanged(Type.GRAPH_CONNECTION);\n }\n\n public boolean isDrawingUniqueTraces() {\n return drawingUniqueTraces;\n }\n\n public void setDrawingUniqueTraces(boolean drawingUniqueTraces) {\n this.drawingUniqueTraces = drawingUniqueTraces;\n setChanged(Type.GRAPH_CONNECTION);\n }\n\n public int getCurvesPerSec() {\n return curvesPerSec;\n }\n\n public void setCurvesPerSec(int curvesPerSec) {\n if (curvesPerSec < 1)\n curvesPerSec = 1;\n this.curvesPerSec = curvesPerSec;\n setChanged(Type.PLAYBACK_SPEED);\n }\n\n public int getCachedTracesNo() {\n return cachedTracesNo;\n }\n\n public void setCachedTracesNo(int cachedTracesNo) {\n this.cachedTracesNo = cachedTracesNo;\n setChanged(Type.GRAPH_CONNECTION);\n }\n\n public double getCurveBundlingStrength() {\n return curveBundlingStrength;\n }\n\n public void setCurveBundlingStrength(double curveBundlingStrength) {\n if (curveBundlingStrength < 0 || curveBundlingStrength > 1)\n throw new IllegalArgumentException(\n Messages.get(\"bundling.strength.exception\"));\n this.curveBundlingStrength = curveBundlingStrength;\n setChanged(Type.GRAPH_CONNECTION);\n }\n\n public static Settings getInstance() {\n return INSTANCE;\n }\n\n public void setChanged(Type type) {\n setChanged();\n notifyObservers(type);\n }\n\n public void drawStruct(int struct, boolean enabled) {\n int oldStruct = structsToDraw;\n structsToDraw = Util.toggleFlag(structsToDraw, struct, enabled);\n if (oldStruct != structsToDraw) {\n UIHelper.getInstance().getProjectTree().setChanged(true);\n setChanged(Type.GRAPH);\n setChanged(Type.PLAYBACK_MODE);\n }\n }\n\n public int getGraphRotate() {\n return graphRotate;\n }\n\n public void setGraphRotate(int graphRotate) {\n this.graphRotate = graphRotate;\n setChanged(Type.GRAPH);\n }\n\n public int getGraphPackageLayersToHide() {\n return graphPackageLayersToHide;\n }\n\n public void setGraphPackageLayersToHide(int graphLayersToHide) {\n this.graphPackageLayersToHide = graphLayersToHide;\n setChanged(Type.GRAPH);\n }\n\n public boolean isPackageEnabled() {\n return packageEnabled;\n }\n\n public void setPackageEnabled(boolean packageEnabled) {\n this.packageEnabled = packageEnabled;\n setChanged(Type.GRAPH);\n }\n\n public int getPackageGap() {\n return packageGap;\n }\n\n public void setPackageGap(int packageGap) {\n this.packageGap = packageGap;\n setChanged(Type.GRAPH);\n }\n\n public int getClassGap() {\n return classGap;\n }\n\n public void setClassGap(int classGap) {\n this.classGap = classGap;\n setChanged(Type.GRAPH);\n }\n\n public int getLayerGap() {\n return layerGap;\n }\n\n public void setLayerGap(int layerGap) {\n this.layerGap = layerGap;\n setChanged(Type.GRAPH);\n }\n\n public int getPackageHeightPercent() {\n return packageHeightPercent;\n }\n\n public void setPackageHeightPercent(int packageHeightPercent) {\n this.packageHeightPercent = packageHeightPercent;\n setChanged(Type.GRAPH);\n }\n\n public int getClassHeightPercent() {\n return classHeightPercent;\n }\n\n public void setClassHeightPercent(int classHeightPercent) {\n this.classHeightPercent = classHeightPercent;\n setChanged(Type.GRAPH);\n }\n\n public int getMethodHeightPercent() {\n return methodHeightPercent;\n }\n\n public void setMethodHeightPercent(int methodHeightPercent) {\n this.methodHeightPercent = methodHeightPercent;\n setChanged(Type.GRAPH);\n }\n\n}" ]
import java.awt.Color; import java.awt.Cursor; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.geom.AffineTransform; import java.util.Collection; import java.util.concurrent.LinkedBlockingDeque; import javax.swing.JPanel; import travis.controller.UIHelper; import travis.model.attach.Playback.Mode; import travis.view.Util; import travis.view.project.graph.connection.ConnectionPainter; import travis.view.project.graph.connection.ExecutionPoint; import travis.view.project.graph.connection.GraphBspline; import travis.view.settings.Settings;
String text = null; switch (mode) { case METHOD: text = ep.getComponentData().getComp().getTooltipFriendlyName() + " THREAD: " + ep.getTrace().getThreadId(); break; case CLASS: text = ep.getComponentData().getComp().getParent() .getTooltipFriendlyName() + " THREAD: " + ep.getTrace().getThreadId(); break; case PACKAGE: text = ep.getComponentData().getComp().getParent().getParent() .getTooltipFriendlyName() + " THREAD: " + ep.getTrace().getThreadId(); break; default: break; } return text; } private String getTextForSpline(SplineData sd) { Mode mode = getMode(); String text = null; switch (mode) { case METHOD: text = "FROM " + sd.getSrc().getComp().getTooltipFriendlyName() + " TO " + sd.getDest().getComp().getTooltipFriendlyName() + " THREAD: " + sd.getDestTrace().getThreadId(); break; case CLASS: text = "FROM " + sd.getSrc().getComp().getParent() .getTooltipFriendlyName() + " TO " + sd.getDest().getComp().getParent() .getTooltipFriendlyName() + " THREAD: " + sd.getDestTrace().getThreadId(); break; case PACKAGE: text = "FROM " + sd.getSrc().getComp().getParent().getParent() .getTooltipFriendlyName() + " TO " + sd.getDest().getComp().getParent().getParent() .getTooltipFriendlyName() + " THREAD: " + sd.getDestTrace().getThreadId(); break; default: break; } return text; } private Mode getMode() { Mode mode = Mode.PACKAGE; if (Settings.getInstance().isDrawingStruct(Settings.STRUCT_METHOD)) { mode = Mode.METHOD; } else if (Settings.getInstance().isDrawingStruct( Settings.STRUCT_CLASS)) { mode = Mode.CLASS; } return mode; } private void drawTooltip(FontMetrics fm, String text, Point tooltipCoord, Graphics2D g2, int height, Color background) { int width = fm.stringWidth(text); int rectWidth = width + MARGIN * 2; Point coord = new Point(tooltipCoord); if (coord.x + rectWidth >= getWidth()) coord.x -= coord.x + rectWidth - getWidth(); g2.setColor(background); g2.fillRoundRect(coord.x, coord.y - height + fm.getDescent(), rectWidth, height, height / 2, height / 2); g2.setColor(Color.BLACK); g2.drawString(text, coord.x + MARGIN, coord.y); } public void displayExecutionPointTooltip(ExecutionPoint ep) { UIHelper helper = UIHelper.getInstance(); if (helper.getMode() == UIHelper.Mode.PLAYBACK && Settings.getInstance().getCurvesPerSec() <= MAX_CURVES_PER_SEC_FOR_PLAYBACK_TOOLTIP) { playbackExecutionPoint = ep; } else { playbackExecutionPoint = null; } if (ep == null || ep.getComponentData() == null || ep.getCenter() == null) { playbackExecutionPoint = null; } } private class MouseListener extends MouseAdapter { @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { text = null; splines.clear(); repaint(); } @Override public void mouseMoved(MouseEvent e) { text = null; splines.clear(); GraphPanel graph = UIHelper.getInstance().getGraph(); TreeRepresentation treeRep = graph.getTreeRepRepresentation();
ConnectionPainter connPainter = graph.getConnectionPainter();
3
hufeiya/CoolSignIn
AndroidClient/app/src/main/java/com/hufeiya/SignIn/fragment/SignInFragment.java
[ "public class CategorySelectionActivity extends AppCompatActivity {\n\n private static final String EXTRA_PLAYER = \"player\";\n private User user;\n\n public static void start(Activity activity, User user, ActivityOptionsCompat options) {\n Intent starter = getStartIntent(activity, user);\n ActivityCompat.startActivity(activity, starter, options.toBundle());\n }\n\n public static void start(Context context, User user) {\n Intent starter = getStartIntent(context, user);\n context.startActivity(starter);\n }\n\n @NonNull\n static Intent getStartIntent(Context context, User user) {\n Intent starter = new Intent(context, CategorySelectionActivity.class);\n starter.putExtra(EXTRA_PLAYER, user);\n return starter;\n }\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n setContentView(R.layout.activity_category_selection);\n user = getIntent().getParcelableExtra(EXTRA_PLAYER);\n if (!PreferencesHelper.isSignedIn(this) && user != null) {\n PreferencesHelper.writeToPreferences(this, user);\n }\n setUpToolbar(user);\n if (savedInstanceState == null) {\n attachCategoryGridFragment();\n } else {\n setProgressBarVisibility(View.GONE);\n }\n supportPostponeEnterTransition();\n\n }\n\n @Override\n protected void onResume() {\n super.onResume();\n }\n\n public void setUpToolbar(User user) {\n Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_player);\n setSupportActionBar(toolbar);\n //noinspection ConstantConditions\n getSupportActionBar().setDisplayShowTitleEnabled(false);\n final AvatarView avatarView = (AvatarView) toolbar.findViewById(R.id.avatar);\n avatarView.setAvatar(user.getAvatar().getDrawableId());\n //noinspection PrivateResource\n ((TextView) toolbar.findViewById(R.id.title)).setText(getDisplayName());\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n getMenuInflater().inflate(R.menu.menu_category, menu);\n return true;\n }\n\n @Override\n protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.category_container);\n if (fragment != null) {\n fragment.onActivityResult(requestCode, resultCode, data);\n }\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n switch (item.getItemId()) {\n case R.id.sign_out: {\n signOut();\n return true;\n }\n }\n return super.onOptionsItemSelected(item);\n }\n\n @SuppressLint(\"NewApi\")\n private void signOut() {\n AsyncHttpHelper.clearAllCookies();\n\n PreferencesHelper.signOut(this);\n if (ApiLevelHelper.isAtLeast(Build.VERSION_CODES.LOLLIPOP)) {\n getWindow().setExitTransition(TransitionInflater.from(this)\n .inflateTransition(R.transition.category_enter));\n }\n SignInActivity.start(this, false);\n ActivityCompat.finishAfterTransition(this);\n }\n\n private String getDisplayName() {\n JsonUser user = AsyncHttpHelper.user;\n if (user == null){\n return \"登录中...\";\n }\n String type;\n if (user.getUserType()){\n type = \"同学\";\n }else{\n type = \"老师\";\n }\n return user.getUsername() + \" \" + type;\n }\n\n private void attachCategoryGridFragment() {\n FragmentManager supportFragmentManager = getSupportFragmentManager();\n Fragment fragment = supportFragmentManager.findFragmentById(R.id.category_container);\n if (!(fragment instanceof CategorySelectionFragment)) {\n fragment = CategorySelectionFragment.newInstance();\n }\n supportFragmentManager.beginTransaction()\n .replace(R.id.category_container, fragment)\n .commit();\n setProgressBarVisibility(View.GONE);\n }\n\n private void setProgressBarVisibility(int visibility) {\n findViewById(R.id.progress).setVisibility(visibility);\n }\n\n public User getUser(){\n return user;\n }\n}", "public class AvatarAdapter extends BaseAdapter {\n\n private static final Avatar[] mAvatars = Avatar.values();\n\n private final LayoutInflater mLayoutInflater;\n\n public AvatarAdapter(Context context) {\n mLayoutInflater = LayoutInflater.from(context);\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n if (null == convertView) {\n convertView = mLayoutInflater.inflate(R.layout.item_avatar, parent, false);\n }\n setAvatar((AvatarView) convertView, mAvatars[position]);\n return convertView;\n }\n\n private void setAvatar(AvatarView mIcon, Avatar avatar) {\n mIcon.setAvatar(avatar.getDrawableId());\n mIcon.setContentDescription(avatar.getNameForAccessibility());\n }\n\n @Override\n public int getCount() {\n return mAvatars.length;\n }\n\n @Override\n public Object getItem(int position) {\n return mAvatars[position];\n }\n\n @Override\n public long getItemId(int position) {\n return position;\n }\n}", "public class PreferencesHelper {\n\n private static final String USER_PREFERENCES = \"playerPreferences\";\n private static final String PREFERENCE_PHONE = USER_PREFERENCES + \".phone\";\n private static final String PREFERENCE_PASS = USER_PREFERENCES + \".pass\";\n private static final String PREFERENCE_AVATAR = USER_PREFERENCES + \".avatar\";\n\n private PreferencesHelper() {\n //no instancer\n }\n\n /**\n * Writes a {@link User} to preferences.\n *\n * @param context The Context which to obtain the SharedPreferences from.\n * @param user The {@link User} to write.\n */\n public static void writeToPreferences(Context context, User user) {\n SharedPreferences.Editor editor = getEditor(context);\n editor.putString(PREFERENCE_PHONE, user.getPhone());\n editor.putString(PREFERENCE_PASS, user.getPass());\n editor.putString(PREFERENCE_AVATAR, user.getAvatar().name());\n editor.apply();\n }\n\n /**\n * Retrieves a {@link User} from preferences.\n *\n * @param context The Context which to obtain the SharedPreferences from.\n * @return A previously saved player or <code>null</code> if none was saved previously.\n */\n public static User getPlayer(Context context) {\n SharedPreferences preferences = getSharedPreferences(context);\n final String firstName = preferences.getString(PREFERENCE_PHONE, null);\n final String lastInitial = preferences.getString(PREFERENCE_PASS, null);\n final String avatarPreference = preferences.getString(PREFERENCE_AVATAR, null);\n final Avatar avatar;\n if (null != avatarPreference) {\n avatar = Avatar.valueOf(avatarPreference);\n } else {\n avatar = null;\n }\n\n if (null == firstName && null == lastInitial && null == avatar) {\n return null;\n }\n return new User(firstName, lastInitial, avatar);\n }\n\n /**\n * Signs out a player by removing all it's data.\n *\n * @param context The context which to obtain the SharedPreferences from.\n */\n public static void signOut(Context context) {\n SharedPreferences.Editor editor = getEditor(context);\n editor.remove(PREFERENCE_PHONE);\n editor.remove(PREFERENCE_PASS);\n editor.remove(PREFERENCE_AVATAR);\n editor.apply();\n }\n\n /**\n * Check whether a user is currently signed in.\n *\n * @param context The context to check this in.\n * @return <code>true</code> if login data exists, else <code>false</code>.\n */\n public static boolean isSignedIn(Context context) {\n final SharedPreferences preferences = getSharedPreferences(context);\n return preferences.contains(PREFERENCE_PHONE) &&\n preferences.contains(PREFERENCE_PASS) &&\n preferences.contains(PREFERENCE_AVATAR);\n }\n\n private static SharedPreferences.Editor getEditor(Context context) {\n SharedPreferences preferences = getSharedPreferences(context);\n return preferences.edit();\n }\n\n private static SharedPreferences getSharedPreferences(Context context) {\n return context.getSharedPreferences(USER_PREFERENCES, Context.MODE_PRIVATE);\n }\n}", "public class TransitionHelper {\n\n private TransitionHelper() {\n //no instance\n }\n\n /**\n * Create the transition participants required during a activity transition while\n * avoiding glitches with the system UI.\n *\n * @param activity The activity used as start for the transition.\n * @param includeStatusBar If false, the status bar will not be added as the transition\n * participant.\n * @return All transition participants.\n */\n @TargetApi(Build.VERSION_CODES.LOLLIPOP)\n public static Pair<View, String>[] createSafeTransitionParticipants(@NonNull Activity activity,\n boolean includeStatusBar,\n @Nullable Pair... otherParticipants) {\n // Avoid system UI glitches as described here:\n // https://plus.google.com/+AlexLockwood/posts/RPtwZ5nNebb\n View decor = activity.getWindow().getDecorView();\n View statusBar = null;\n if (includeStatusBar) {\n statusBar = decor.findViewById(android.R.id.statusBarBackground);\n }\n View navBar = decor.findViewById(android.R.id.navigationBarBackground);\n\n // Create pair of transition participants.\n List<Pair> participants = new ArrayList<>(3);\n addNonNullViewToTransitionParticipants(statusBar, participants);\n addNonNullViewToTransitionParticipants(navBar, participants);\n // only add transition participants if there's at least one none-null element\n if (otherParticipants != null && !(otherParticipants.length == 1\n && otherParticipants[0] == null)) {\n participants.addAll(Arrays.asList(otherParticipants));\n }\n //noinspection unchecked\n return participants.toArray(new Pair[participants.size()]);\n }\n\n @TargetApi(Build.VERSION_CODES.LOLLIPOP)\n private static void addNonNullViewToTransitionParticipants(View view, List<Pair> participants) {\n if (view == null) {\n return;\n }\n participants.add(new Pair<>(view, view.getTransitionName()));\n }\n\n}", "public enum Avatar {\n\n ONE(R.drawable.avatar_1),\n TWO(R.drawable.avatar_2),\n THREE(R.drawable.avatar_3),\n FOUR(R.drawable.avatar_4),\n FIVE(R.drawable.avatar_5),\n SIX(R.drawable.avatar_6),\n SEVEN(R.drawable.avatar_7),\n EIGHT(R.drawable.avatar_8),\n NINE(R.drawable.avatar_9),\n TEN(R.drawable.avatar_10),\n ELEVEN(R.drawable.avatar_11),\n TWELVE(R.drawable.avatar_12),\n THIRTEEN(R.drawable.avatar_13),\n FOURTEEN(R.drawable.avatar_14),\n FIFTEEN(R.drawable.avatar_15),\n SIXTEEN(R.drawable.avatar_16);\n\n private static final String TAG = \"Avatar\";\n\n private final int mResId;\n\n Avatar(@DrawableRes final int resId) {\n mResId = resId;\n }\n\n @DrawableRes\n public int getDrawableId() {\n return mResId;\n }\n\n public String getNameForAccessibility() {\n return TAG + \" \" + ordinal() + 1;\n }\n}", "public class User implements Parcelable {\n\n public static final Creator<User> CREATOR = new Creator<User>() {\n @Override\n public User createFromParcel(Parcel in) {\n return new User(in);\n }\n\n @Override\n public User[] newArray(int size) {\n return new User[size];\n }\n };\n private final String mPhone;\n private final String mPass;\n private final Avatar mAvatar;\n\n public User(String phone, String pass, Avatar avatar) {\n mPhone = phone;\n mPass = pass;\n mAvatar = avatar;\n }\n\n protected User(Parcel in) {\n mPhone = in.readString();\n mPass = in.readString();\n mAvatar = Avatar.values()[in.readInt()];\n }\n\n public String getPhone() {\n return mPhone;\n }\n\n public String getPass() {\n return mPass;\n }\n\n public Avatar getAvatar() {\n return mAvatar;\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeString(mPhone);\n dest.writeString(mPass);\n dest.writeInt(mAvatar.ordinal());\n }\n\n @SuppressWarnings(\"RedundantIfStatement\")\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n\n User user = (User) o;\n\n if (mAvatar != user.mAvatar) {\n return false;\n }\n if (!mPhone.equals(user.mPhone)) {\n return false;\n }\n if (!mPass.equals(user.mPass)) {\n return false;\n }\n\n return true;\n }\n\n @Override\n public int hashCode() {\n int result = mPhone.hashCode();\n result = 31 * result + mPass.hashCode();\n result = 31 * result + mAvatar.hashCode();\n return result;\n }\n}", "public class AsyncHttpHelper {\n\n private static AsyncHttpClient client = new AsyncHttpClient();\n public static JsonUser user;\n private static String serverURL = \"http://192.168.2.8:8089/Server/\";\n private static PersistentCookieStore myCookieStore = new PersistentCookieStore(MyApplication.getContext());\n private static UploadManager uploadManager = new UploadManager();//Qi Niu\n static {\n client.setCookieStore(myCookieStore);\n }\n\n\n public static void login(String phone, String pass, final SignInFragment fragment) {\n boolean isSucceed;\n final String md5pass = md5(pass);\n Log.d(\"login\", md5pass);\n client.get(serverURL + \"login?phone=\" + phone + \"&pass=\" + md5pass, null, new JsonHttpResponseHandler() {\n @Override\n public void onSuccess(int statusCode, Header[] headers, JSONObject response) {\n super.onSuccess(statusCode, headers, response);\n }\n\n @Override\n public void onSuccess(int statusCode, Header[] headers, JSONArray response) {\n super.onSuccess(statusCode, headers, response);\n try {\n fragment.progressBar.setVisibility(View.GONE);\n String isSucceed = response.getString(0);\n if (isSucceed.equals(\"false\")) {\n fragment.toastLoginFail(\"account\");\n\n } else {\n user = new Gson().fromJson(response.get(1).toString(), JsonUser.class);\n fragment.savePlayer(md5pass);\n fragment.enterTheCategorySelectionActivity();\n }\n\n\n } catch (JSONException e) {\n e.printStackTrace();\n fragment.toastLoginFail(\"json\");\n }\n }\n\n @Override\n public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {\n super.onFailure(statusCode, headers, responseString, throwable);\n fragment.toastLoginFail(\"unknown\");\n }\n });\n\n }\n\n public static void refrash(String phone, String pass, final CategorySelectionFragment fragment) {\n String httpParameters = \"login?phone=\" + phone + \"&pass=\" + pass;\n client.get(serverURL + httpParameters, null, new JsonHttpResponseHandler() {\n @Override\n public void onSuccess(int statusCode, Header[] headers, JSONObject response) {\n super.onSuccess(statusCode, headers, response);\n }\n\n @Override\n public void onSuccess(int statusCode, Header[] headers, JSONArray response) {\n super.onSuccess(statusCode, headers, response);\n try {\n String isSucceed = response.getString(0);\n if (isSucceed.equals(\"false\")) {\n //TODO relogin\n } else {\n user = new Gson().fromJson(response.get(1).toString(), JsonUser.class);\n fragment.swipeRefreshLayout.setRefreshing(false);\n fragment.getmAdapter().updateCategories(fragment.getActivity());\n fragment.getmAdapter().notifyDataSetChanged();\n ((CategorySelectionActivity) fragment.getActivity()).setUpToolbar\n (((CategorySelectionActivity) fragment.getActivity()).getUser());\n fragment.setDrawer();\n\n }\n\n\n } catch (JSONException e) {\n e.printStackTrace();\n fragment.toastLoginFail(\"json\");\n }\n }\n\n @Override\n public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {\n super.onFailure(statusCode, headers, responseString, throwable);\n fragment.toastLoginFail(\"unknown\");\n }\n });\n\n }\n\n public static void uploadLocation(final Context context,String cid, double latitude,double longitude){\n String httpParameters=\"location?cid=\" + cid + \"&latitude=\" + latitude +\"&longitude=\" + longitude;\n client.get(serverURL + httpParameters, null, new AsyncHttpResponseHandler() {\n @Override\n public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {\n String response = new String(responseBody);\n if (response.equals(\"true\")){\n ((QuizActivity)context).startSign();\n }\n }\n\n @Override\n public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {\n ((QuizActivity)context).toastNetUnavalible();\n }\n });\n }\n\n //get uptoken from server to have the access to Qi Niu,then Upload photo.\n public static void getUptokenAndUploadPhoto(final Context context, final byte[] photoBytes,final String signId){\n String httpParameters=\"uptoken?signid=\" + signId;\n client.get(serverURL + httpParameters, null, new AsyncHttpResponseHandler() {\n @Override\n public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {\n String token = new String(responseBody);\n if (token.equals(\"false\")){\n ((QuizActivity)context).uploadPhotoFail();\n }else{//succeed\n uploadManager.put(photoBytes, signId, token, new UpCompletionHandler() {\n @Override\n public void complete(String s, ResponseInfo responseInfo, JSONObject jsonObject) {\n ((QuizActivity) context).uploadPhotoSuccess();\n }\n }, null);\n }\n }\n\n @Override\n public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {\n ((QuizActivity)context).uploadPhotoFail();\n }\n });\n }\n\n public static void uploadSignInfo(final Context context,JsonSignInfo jsonSignInfo){\n String httpParameters=\"signin\";\n RequestParams requestParams = new RequestParams();\n String json = new Gson().toJson(jsonSignInfo);\n requestParams.add(\"signInfo\",json);\n client.post(serverURL + httpParameters, requestParams, new AsyncHttpResponseHandler() {\n @Override\n public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {\n String response = new String(responseBody);\n if (response.equals(\"true\")) {\n ((QuizActivity) context).onSignSuccess();\n }\n }\n\n @Override\n public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {\n //TODO can also return {banned,null}\n ((QuizActivity) context).toastNetUnavalible();\n }\n });\n }\n\n\n public static String md5(String string) {\n byte[] hash;\n try {\n\n hash = MessageDigest.getInstance(\"MD5\").digest(string.getBytes(\"UTF-8\"));\n\n } catch (NoSuchAlgorithmException e) {\n\n throw new RuntimeException(\"Huh, MD5 should be supported?\", e);\n\n } catch (UnsupportedEncodingException e) {\n\n throw new RuntimeException(\"Huh, UTF-8 should be supported?\", e);\n\n }\n StringBuilder hex = new StringBuilder(hash.length * 2);\n for (byte b : hash) {\n\n if ((b & 0xFF) < 0x10) hex.append(\"0\");\n\n hex.append(Integer.toHexString(b & 0xFF));\n\n }\n return hex.toString();\n }\n\n public static void clearAllCookies(){\n myCookieStore.clear();\n }\n}" ]
import android.app.Activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.ActivityOptionsCompat; import android.support.v4.app.Fragment; import android.support.v4.util.Pair; import android.support.v4.view.ViewCompat; import android.support.v4.view.animation.FastOutSlowInInterpolator; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.EditText; import android.widget.GridView; import android.widget.ProgressBar; import android.widget.Toast; import com.hufeiya.SignIn.R; import com.hufeiya.SignIn.activity.CategorySelectionActivity; import com.hufeiya.SignIn.adapter.AvatarAdapter; import com.hufeiya.SignIn.helper.PreferencesHelper; import com.hufeiya.SignIn.helper.TransitionHelper; import com.hufeiya.SignIn.model.Avatar; import com.hufeiya.SignIn.model.User; import com.hufeiya.SignIn.net.AsyncHttpHelper;
/* * Copyright 2015 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hufeiya.SignIn.fragment; /** * Enable selection of an {@link Avatar} and user name. */ public class SignInFragment extends Fragment { private static final String ARG_EDIT = "EDIT"; private static final String KEY_SELECTED_AVATAR_INDEX = "selectedAvatarIndex"; private User mUser; private EditText phone; private EditText pass; private Avatar mSelectedAvatar = Avatar.ONE; private View mSelectedAvatarView; private GridView mAvatarGrid; private FloatingActionButton mDoneFab; private boolean edit; public ProgressBar progressBar; public static SignInFragment newInstance(boolean edit) { Bundle args = new Bundle(); args.putBoolean(ARG_EDIT, edit); SignInFragment fragment = new SignInFragment(); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { if (savedInstanceState != null) { int savedAvatarIndex = savedInstanceState.getInt(KEY_SELECTED_AVATAR_INDEX); mSelectedAvatar = Avatar.values()[savedAvatarIndex]; } super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { final View contentView = inflater.inflate(R.layout.fragment_sign_in, container, false); contentView.addOnLayoutChangeListener(new View. OnLayoutChangeListener() { @Override public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { v.removeOnLayoutChangeListener(this); setUpGridView(getView()); } }); return contentView; } @Override public void onSaveInstanceState(Bundle outState) { outState.putInt(KEY_SELECTED_AVATAR_INDEX, mSelectedAvatar.ordinal()); super.onSaveInstanceState(outState); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { assurePlayerInit(); checkIsInEditMode(); if (null == mUser || edit) { view.findViewById(R.id.empty).setVisibility(View.GONE); view.findViewById(R.id.content).setVisibility(View.VISIBLE); initContentViews(view); initContents(); } else { final Activity activity = getActivity(); CategorySelectionActivity.start(activity, mUser); activity.finish(); } super.onViewCreated(view, savedInstanceState); } private void checkIsInEditMode() { final Bundle arguments = getArguments(); //noinspection SimplifiableIfStatement if (null == arguments) { edit = false; } else { edit = arguments.getBoolean(ARG_EDIT, false); } } private void initContentViews(View view) { TextWatcher textWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { /* no-op */ } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // showing the floating action button if text is entered if (s.length() == 0) { mDoneFab.hide(); } else { mDoneFab.show(); } } @Override public void afterTextChanged(Editable s) { /* no-op */ } }; progressBar = (ProgressBar)view.findViewById(R.id.empty); phone = (EditText) view.findViewById(R.id.phone); phone.addTextChangedListener(textWatcher); pass = (EditText) view.findViewById(R.id.pass); pass.addTextChangedListener(textWatcher); mDoneFab = (FloatingActionButton) view.findViewById(R.id.done); mDoneFab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { switch (v.getId()) { case R.id.done: progressBar.setVisibility(View.VISIBLE);
AsyncHttpHelper.login(phone.getText().toString(),pass.getText().toString(),SignInFragment.this);
6
lauriholmas/batmapper
src/main/java/com/glaurung/batMap/controller/MapperEngine.java
[ "public class CorpsePanel extends JPanel implements ActionListener, ComponentListener, KeyListener, DocumentListener {\n\n private CorpseModel model = new CorpseModel();\n private String BASEDIR;\n private MapperPlugin plugin;\n private final Color TEXT_COLOR = Color.LIGHT_GRAY;\n private final Color BG_COLOR = Color.BLACK;\n private final int BORDERLINE = 7;\n private final int TOP_BORDER = 20;\n private Font font = new Font( \"Consolas\", Font.PLAIN, 14 );\n private final int CB_WIDTH = 200;\n private final int BUTTON_WIDTH = 70;\n private final int LABEL_WIDTH = 100;\n private final int CB_HEIGHT = 25;\n private final String[] organs = { \"antenna\", \"arm\", \"beak\", \"bladder\", \"brain\", \"ear\", \"eye\", \"foot\", \"gill\", \"heart\", \"horn\", \"kidney\", \"leg\", \"liver\", \"lung\", \"nose\", \"paw\", \"snout\", \"spleen\", \"stomach\", \"tail\", \"tendril\", \"wing\" };\n private final String[] etherTypes = { \"no_focus\", \"blue\", \"green\", \"red\", \"yellow\" };\n\n public CorpsePanel( String BASEDIR, MapperPlugin plugin ) {\n this.BASEDIR = BASEDIR;\n this.model = CorpseHandlerDataPersister.load( BASEDIR );\n if (model == null) {\n model = new CorpseModel();\n } else {\n loadFromModel();\n }\n this.plugin = plugin;\n this.setPreferredSize( new Dimension( 1200, 800 ) );\n this.redoLayout();\n\n this.delim.addActionListener( this );\n\n this.mount.addActionListener( this );\n this.setBackground( BG_COLOR );\n on.addActionListener( this );\n off.addActionListener( this );\n clear.addActionListener( this );\n lootLists.setSelectionMode( ListSelectionModel.SINGLE_INTERVAL_SELECTION );\n add.addActionListener( this );\n del.addActionListener( this );\n lootItem.addActionListener( this );\n lootLists.addKeyListener( this );\n organ1.addActionListener( this );\n organ2.addActionListener( this );\n etherFocus.addActionListener( this );\n doIt.addActionListener( this );\n delim.addActionListener( this );\n delim.getDocument().addDocumentListener( this );\n mount.getDocument().addDocumentListener( this );\n lootLists.setToolTipText( \"These items will be picked up by loot commands\" );\n lootCorpse.setToolTipText( \"Control looted items in the list\" );\n lootGround.setToolTipText( \"Control looted items in the list\" );\n }\n\n DefaultListModel listModel = new DefaultListModel();\n private CorpseCheckBox lichdrain = new CorpseCheckBox( \"lich drain soul\", false, \"lich drain\", this, font );\n private CorpseCheckBox kharimsoul = new CorpseCheckBox( \"kharim drain soul\", false, \"kharim drain\", this, font );\n private CorpseCheckBox kharimSoulCorpse = new CorpseCheckBox( \"kharim dest corpse\", false, null, this, font );\n private CorpseCheckBox tsaraksoul = new CorpseCheckBox( \"tzarakk chaosfeed\", false, \"tzarakk chaosfeed corpse\", this, font );\n private CorpseCheckBox ripSoulToKatana = new CorpseCheckBox( \"shitKatana rip soul\", false, \"rip soul from corpse\", this, font );\n private CorpseCheckBox arkemile = new CorpseCheckBox( \"necrostaff arkemile\", false, \"say arkemile\", this, font );\n private CorpseCheckBox gac = new CorpseCheckBox( \"get all from corpse\", false, \"get all from corpse\", this, font );\n private CorpseCheckBox ga = new CorpseCheckBox( \"get all from ground\", false, \"get all\", this, font );\n private CorpseCheckBox eatCorpse = new CorpseCheckBox( \"get and eat corpse\", false, \"get corpse\" + getDelim() + \"eat corpse\", this, font );\n private CorpseCheckBox donate = new CorpseCheckBox( \"donate noeq and drop rest\", false, \"get all from corpse\" + getDelim() + \"donate noeq\" + getDelim() + \"drop noeq\", this, font );\n private CorpseCheckBox lootCorpse = new CorpseCheckBox( \"get loot from corpse\", false, \"get \" + getLootString() + \" from corpse\", this, font );\n private CorpseCheckBox lootGround = new CorpseCheckBox( \"get loot from ground\", false, \"get \" + getLootString(), this, font );\n private CorpseCheckBox barbarianBurn = new CorpseCheckBox( \"barbarian burn corpse\", false, \"barbburn\", this, font );\n private CorpseCheckBox feedCorpseTo = new CorpseCheckBox( \"feed corpse to mount\", false, \"get corpse\" + getDelim() + \"feed corpse to \" + getMountName(), this, font );\n private CorpseCheckBox beheading = new CorpseCheckBox( \"kharim behead corpse\", false, \"use beheading of departed at corpse\", this, font );\n private CorpseCheckBox desecrateGround = new CorpseCheckBox( \"desecrate ground\", false, \"use desecrate ground\", this, font );\n private CorpseCheckBox burialCere = new CorpseCheckBox( \"burial ceremony\", false, \"use burial ceremony\", this, font );\n private CorpseCheckBox dig = new CorpseCheckBox( \"dig grave\", false, \"dig grave\", this, font );\n private CorpseCheckBox wakeFollow = new CorpseCheckBox( \"follow\", false, \" follow\", this, font );\n private CorpseCheckBox wakeAgro = new CorpseCheckBox( \"agro\", false, \" agro\", this, font );\n private CorpseCheckBox wakeTalk = new CorpseCheckBox( \"talk\", false, \" talk\", this, font );\n private CorpseCheckBox wakeStatic = new CorpseCheckBox( \"static\", false, \"\", this, font );\n private CorpseCheckBox lichWake = new CorpseCheckBox( \"lich wake corpse\", false, \"lich wake corpse\", this, font );\n private CorpseCheckBox vampireWake = new CorpseCheckBox( \"vampire wake corpse\", false, \"vampire wake corpse\", this, font );\n private CorpseCheckBox skeletonWake = new CorpseCheckBox( \"skeleton wake corpse\", false, \"skeleton wake corpse\", this, font );\n private CorpseCheckBox zombieWake = new CorpseCheckBox( \"zombie wake corpse\", false, \"zombie wake corpse\", this, font );\n private CorpseCheckBox aelenaOrgan = new CorpseCheckBox( \"aelena extract organ\", false, \"familiar harvest antenna antenna\", this, font );\n private CorpseCheckBox aelenaFam = new CorpseCheckBox( \"aelena fam consume corpse\", false, \"familiar consume corpse\", this, font );\n private CorpseCheckBox dissect = new CorpseCheckBox( \"dissection\", false, \"use dissection at corpse try \", this, font );\n private CorpseCheckBox tin = new CorpseCheckBox( \"tin corpse\", false, \"tin corpse\", this, font );\n private CorpseCheckBox extractEther = new CorpseCheckBox( \"extract ether\", false, \"use extract ether at corpse \", this, font );\n\n\n private static final long serialVersionUID = 1L;\n private JCheckBox on = new JCheckBox( \"On!\" );\n private JCheckBox off = new JCheckBox( \"Off\" );\n private JTextField delim = new JTextField( \";\" );\n private JTextField mount = new JTextField( \"\" );\n private JButton clear = new JButton( \"Clear!\" );\n private JButton doIt = new JButton( \"Do it!\" );\n private JList lootLists = new JList( listModel );\n private JScrollPane listPane = new JScrollPane( lootLists );\n\n\n private Border whiteline = BorderFactory.createLineBorder( Color.white );\n private JPanel soulPanel = new JPanel();\n private JPanel listPanel = new JPanel();\n private JPanel controlPanel = new JPanel();\n private JPanel wakePanel = new JPanel();\n private JPanel lootPanel = new JPanel();\n private JPanel corpsePanel = new JPanel();\n private JLabel delimLabel = new JLabel( \"delimeter:\" );\n private JLabel mountLabel = new JLabel( \"mount name:\" );\n private JComboBox organ1 = new JComboBox( organs );\n private JComboBox organ2 = new JComboBox( organs );\n private JLabel organ1Label = new JLabel( \"first organ:\" );\n private JLabel organ2Label = new JLabel( \"second organ:\" );\n private JComboBox etherFocus = new JComboBox( etherTypes );\n private JLabel etherLabel = new JLabel( \"ether focus:\" );\n\n private JButton add = new JButton( \"add\" );\n private JButton del = new JButton( \"del\" );\n private JTextField lootItem = new JTextField();\n\n public String getDelim() {\n return model.getDelim();\n }\n\n\n private String getMountName() {\n return model.getMountHandle();\n }\n\n\n private String getLootString() {\n String loots = \"grep -q -v \\\"There is no\\\" get \";\n if (listModel.size() < 1) {\n return \"\";\n }\n for (Object lootItem : listModel.toArray()) {\n loots += (String) lootItem + \",\";\n }\n return loots.substring( 0, loots.length() - 1 );\n\n\n /**\n * (00:03) Torc tells you ''loottinoids' is a command-alias to 'grep -q -v \"There is no\" ga mithril,all batium,all anipium,all platinum,all gold,all gem,all box,all\n chest,all safe,all scroll,all emerald disc,all rune,all compass,all shard,all key from all corpse;grep -q -v \"There is no\" ga mithril,all batium,all anipium,all\n platinum,all gold,all chest,all box,all safe,all gem,all scroll,all emerald disc,all rune,all compass,all shard,all key'.'\n\n */\n }\n\n private void saveToModel() {\n this.model.setMountHandle( mount.getText() );\n this.model.setDelim( delim.getText() );\n this.model.setLootList( createStringLootList() );\n this.model.setOrgan1( (String) organ1.getSelectedItem() );\n this.model.setOrgan2( (String) organ2.getSelectedItem() );\n this.model.setEtherType( (String) etherFocus.getSelectedItem() );\n this.model.lichdrain = lichdrain.isSelected();\n this.model.kharimsoul = kharimsoul.isSelected();\n this.model.kharimSoulCorpse = kharimSoulCorpse.isSelected();\n this.model.tsaraksoul = tsaraksoul.isSelected();\n this.model.ripSoulToKatana = ripSoulToKatana.isSelected();\n this.model.arkemile = arkemile.isSelected();\n this.model.gac = gac.isSelected();\n this.model.ga = ga.isSelected();\n this.model.eatCorpse = eatCorpse.isSelected();\n this.model.donate = donate.isSelected();\n this.model.lootCorpse = lootCorpse.isSelected();\n this.model.lootGround = lootGround.isSelected();\n this.model.barbarianBurn = barbarianBurn.isSelected();\n this.model.feedCorpseTo = feedCorpseTo.isSelected();\n this.model.beheading = beheading.isSelected();\n this.model.desecrateGround = desecrateGround.isSelected();\n this.model.burialCere = burialCere.isSelected();\n this.model.dig = dig.isSelected();\n this.model.wakeFollow = wakeFollow.isSelected();\n this.model.wakeAgro = wakeAgro.isSelected();\n this.model.wakeTalk = wakeTalk.isSelected();\n this.model.wakeStatic = wakeStatic.isSelected();\n this.model.lichWake = lichWake.isSelected();\n this.model.vampireWake = vampireWake.isSelected();\n this.model.skeletonWake = skeletonWake.isSelected();\n this.model.zombieWake = zombieWake.isSelected();\n this.model.aelenaFam = aelenaFam.isSelected();\n this.model.aelenaOrgan = aelenaOrgan.isSelected();\n this.model.dissect = dissect.isSelected();\n this.model.tin = tin.isSelected();\n this.model.extractEther = extractEther.isSelected();\n CorpseHandlerDataPersister.save( BASEDIR, this.model );\n\n }\n\n private List<String> createStringLootList() {\n LinkedList<String> list = new LinkedList<String>();\n for (int i = 0; i < listModel.getSize(); ++ i) {\n list.add( (String) listModel.getElementAt( i ) );\n }\n return list;\n }\n\n private void loadFromModel() {\n\n\n lichdrain.setSelected( this.model.lichdrain );\n kharimsoul.setSelected( this.model.kharimsoul );\n kharimSoulCorpse.setSelected( this.model.kharimSoulCorpse );\n tsaraksoul.setSelected( this.model.tsaraksoul );\n ripSoulToKatana.setSelected( this.model.ripSoulToKatana );\n arkemile.setSelected( this.model.arkemile );\n gac.setSelected( this.model.gac );\n ga.setSelected( this.model.ga );\n eatCorpse.setSelected( this.model.eatCorpse );\n donate.setSelected( this.model.donate );\n lootCorpse.setSelected( this.model.lootCorpse );\n lootGround.setSelected( this.model.lootGround );\n barbarianBurn.setSelected( this.model.barbarianBurn );\n feedCorpseTo.setSelected( this.model.feedCorpseTo );\n beheading.setSelected( this.model.beheading );\n desecrateGround.setSelected( this.model.desecrateGround );\n burialCere.setSelected( this.model.burialCere );\n dig.setSelected( this.model.dig );\n wakeFollow.setSelected( this.model.wakeFollow );\n wakeAgro.setSelected( this.model.wakeAgro );\n wakeTalk.setSelected( this.model.wakeTalk );\n wakeStatic.setSelected( this.model.wakeStatic );\n lichWake.setSelected( this.model.lichWake );\n vampireWake.setSelected( this.model.vampireWake );\n skeletonWake.setSelected( this.model.skeletonWake );\n zombieWake.setSelected( this.model.zombieWake );\n aelenaFam.setSelected( this.model.aelenaFam );\n aelenaOrgan.setSelected( this.model.aelenaOrgan );\n dissect.setSelected( this.model.dissect );\n tin.setSelected( this.model.tin );\n extractEther.setSelected( this.model.extractEther );\n\n mount.setText( this.model.getMountHandle() );\n delim.setText( this.model.getDelim() );\n organ1.setSelectedItem( this.model.getOrgan1() );\n organ2.setSelectedItem( this.model.getOrgan2() );\n etherFocus.setSelectedItem( this.model.getEtherType() );\n listModel.clear();\n for (String item : this.model.getLootList()) {\n listModel.addElement( item );\n }\n updateLoots();\n updateDelimAndMountAffected();\n updateOrganAffected();\n//\t\tplugin.saveRipAction(makeRipString());\n\n }\n\n @Override\n public void actionPerformed( ActionEvent event ) {\n\n Object source = event.getSource();\n if (source == kharimSoulCorpse) {\n this.plugin.doCommand( \"kharim set corpseDest foobar\" );\n } else if (source == lichdrain) {\n turnOff( kharimsoul, kharimsoul, ripSoulToKatana, arkemile );\n } else if (source == kharimsoul) {\n turnOff( lichdrain, tsaraksoul, ripSoulToKatana, arkemile );\n } else if (source == tsaraksoul) {\n turnOff( lichdrain, kharimsoul, ripSoulToKatana, arkemile );\n } else if (source == ripSoulToKatana) {\n turnOff( lichdrain, kharimsoul, tsaraksoul, arkemile );\n } else if (source == arkemile) {\n turnOff( tin, lichdrain, kharimsoul, tsaraksoul, ripSoulToKatana, eatCorpse, barbarianBurn, feedCorpseTo,\n beheading, desecrateGround, burialCere, lichWake, skeletonWake, vampireWake, zombieWake, aelenaFam, aelenaOrgan, dig, dissect, extractEther );\n } else if (source == eatCorpse) {\n turnOff( tin, arkemile, dig, dissect, ripSoulToKatana, barbarianBurn, feedCorpseTo, beheading, desecrateGround, burialCere, lichWake, skeletonWake, vampireWake, zombieWake, aelenaFam, aelenaOrgan, extractEther );\n } else if (source == barbarianBurn) {\n turnOff( tin, arkemile, eatCorpse, dig, dissect, ripSoulToKatana, feedCorpseTo, beheading, desecrateGround, burialCere, lichWake, skeletonWake, vampireWake, zombieWake, aelenaFam, aelenaOrgan, extractEther );\n } else if (source == feedCorpseTo) {\n turnOff( tin, arkemile, eatCorpse, dig, dissect, ripSoulToKatana, barbarianBurn, beheading, desecrateGround, burialCere, lichWake, skeletonWake, vampireWake, zombieWake, aelenaFam, aelenaOrgan, extractEther );\n } else if (source == beheading) {\n turnOff( tin, arkemile, eatCorpse, dig, dissect, ripSoulToKatana, barbarianBurn, feedCorpseTo, desecrateGround, burialCere, lichWake, skeletonWake, vampireWake, zombieWake, aelenaFam, aelenaOrgan, extractEther );\n } else if (source == desecrateGround) {\n turnOff( tin, arkemile, eatCorpse, dig, dissect, ripSoulToKatana, barbarianBurn, feedCorpseTo, beheading, burialCere, lichWake, skeletonWake, vampireWake, zombieWake, aelenaFam, aelenaOrgan, extractEther );\n } else if (source == burialCere) {\n turnOff( tin, arkemile, eatCorpse, dig, dissect, ripSoulToKatana, barbarianBurn, feedCorpseTo, beheading, desecrateGround, lichWake, skeletonWake, vampireWake, zombieWake, aelenaFam, aelenaOrgan, extractEther );\n } else if (source == lichWake) {\n turnOff( tin, arkemile, eatCorpse, dig, dissect, ripSoulToKatana, barbarianBurn, feedCorpseTo, beheading, desecrateGround, burialCere, skeletonWake, vampireWake, zombieWake, aelenaFam, aelenaOrgan, extractEther );\n } else if (source == vampireWake) {\n turnOff( tin, arkemile, eatCorpse, dig, dissect, ripSoulToKatana, barbarianBurn, feedCorpseTo, beheading, desecrateGround, burialCere, lichWake, skeletonWake, zombieWake, aelenaFam, aelenaOrgan, extractEther );\n } else if (source == skeletonWake) {\n turnOff( tin, arkemile, eatCorpse, dig, dissect, ripSoulToKatana, barbarianBurn, feedCorpseTo, beheading, desecrateGround, burialCere, lichWake, vampireWake, zombieWake, aelenaFam, aelenaOrgan, extractEther );\n } else if (source == zombieWake) {\n turnOff( tin, arkemile, eatCorpse, dig, dissect, ripSoulToKatana, barbarianBurn, feedCorpseTo, beheading, desecrateGround, burialCere, lichWake, skeletonWake, vampireWake, aelenaFam, aelenaOrgan, extractEther );\n } else if (source == aelenaFam) {\n turnOff( tin, arkemile, eatCorpse, dig, dissect, ripSoulToKatana, barbarianBurn, feedCorpseTo, beheading, desecrateGround, burialCere, lichWake, skeletonWake, vampireWake, aelenaOrgan, extractEther );\n } else if (source == aelenaOrgan) {\n turnOff( tin, arkemile, eatCorpse, dig, dissect, ripSoulToKatana, barbarianBurn, feedCorpseTo, beheading, desecrateGround, burialCere, lichWake, skeletonWake, vampireWake, aelenaFam, extractEther );\n } else if (source == dig) {\n turnOff( tin, arkemile, eatCorpse, dissect, aelenaOrgan, ripSoulToKatana, barbarianBurn, feedCorpseTo, beheading, desecrateGround, burialCere, lichWake, skeletonWake, vampireWake, aelenaFam, extractEther );\n } else if (source == dissect) {\n turnOff( tin, arkemile, eatCorpse, dig, aelenaOrgan, ripSoulToKatana, barbarianBurn, feedCorpseTo, beheading, desecrateGround, burialCere, lichWake, skeletonWake, vampireWake, aelenaFam, extractEther );\n } else if (source == tin) {\n turnOff( dissect, arkemile, eatCorpse, dig, aelenaOrgan, ripSoulToKatana, barbarianBurn, feedCorpseTo, beheading, desecrateGround, burialCere, lichWake, skeletonWake, vampireWake, aelenaFam, extractEther );\n } else if (source == extractEther) {\n turnOff( tin, arkemile, eatCorpse, dig, dissect, aelenaOrgan, ripSoulToKatana, barbarianBurn, feedCorpseTo, beheading, desecrateGround, burialCere, lichWake, skeletonWake, vampireWake, aelenaFam );\n } else if (source == wakeFollow) {\n turnOff( wakeAgro, wakeTalk, wakeStatic );\n } else if (source == wakeAgro) {\n turnOff( wakeFollow, wakeTalk, wakeStatic );\n } else if (source == wakeTalk) {\n turnOff( wakeFollow, wakeAgro, wakeStatic );\n } else if (source == wakeStatic) {\n turnOff( wakeFollow, wakeAgro, wakeTalk );\n } else if (source == clear) {\n\n int confirmation = JOptionPane.showConfirmDialog( null, \"Sure you want to clear everything?\" );\n if (confirmation == 0) {\n this.model.clear();\n organ1.setSelectedIndex( 0 );\n organ2.setSelectedIndex( 0 );\n etherFocus.setSelectedIndex( 0 );\n this.loadFromModel();\n }\n\n } else if (source == add && ! lootItem.getText().trim().equals( \"\" )) {\n listModel.addElement( lootItem.getText() );\n lootItem.setText( \"\" );\n updateLoots();\n } else if (source == lootItem && ! lootItem.getText().trim().equals( \"\" )) {\n listModel.addElement( lootItem.getText() );\n lootItem.setText( \"\" );\n updateLoots();\n } else if (source == del && lootLists.getSelectedIndex() > - 1) {\n listModel.remove( lootLists.getSelectedIndex() );\n updateLoots();\n } else if (source == organ1) {\n updateOrganAffected();\n } else if (source == organ2) {\n updateOrganAffected();\n } else if (source == etherFocus) {\n \tupdateEther();\n }\n \n\n if (source == doIt) {\n plugin.doCommand( makeRipString() );\n } else if (source == on) {\n on.setSelected( true );\n off.setSelected( false );\n this.plugin.toggleRipAction( true );\n } else if (source == off) {\n on.setSelected( false );\n off.setSelected( true );\n this.plugin.toggleRipAction( false );\n } else {\n persistAndUpdate();\n }\n\n }\n\n\n private void updateOrganAffected() {\n dissect.setEffect( \"use dissection at corpse try \" + organ1.getSelectedItem() + \" \" + organ2.getSelectedItem() );\n aelenaOrgan.setEffect( \"familiar harvest \" + organ1.getSelectedItem() + \" \" + organ2.getSelectedItem() );\n }\n \n private void updateEther() {\n \tif ( etherFocus.getSelectedItem().equals( \"no_focus\" ) ) {\n \textractEther.setEffect( \"use extract ether at corpse\" );\n \t} else {\n \textractEther.setEffect( \"use extract ether at corpse focus on \" + etherFocus.getSelectedItem() );\n \t}\n }\n\n private void updateLoots() {\n if (getLootString().equals( \"\" )) {\n lootCorpse.setEffect( \"\" );\n lootGround.setEffect( \"\" );\n } else {\n lootCorpse.setEffect( getLootString() + \" from corpse\" );\n lootGround.setEffect( getLootString() );\n }\n\n }\n\n\n private void turnOff( CorpseCheckBox... boxes ) {\n for (CorpseCheckBox box : boxes) {\n box.setSelected( false );\n }\n }\n\n private String makeRipString() {\n String rip = \"\";\n //first souls\n if (lichdrain.isSelected()) {\n rip += lichdrain.getEffect() + this.model.getDelim();\n }\n if (kharimsoul.isSelected()) {\n rip += kharimsoul.getEffect() + this.model.getDelim();\n }\n if (kharimSoulCorpse.isSelected()) {\n rip += kharimSoulCorpse.getEffect() + this.model.getDelim();\n }\n if (ripSoulToKatana.isSelected()) {\n rip += ripSoulToKatana.getEffect() + this.model.getDelim();\n }\n\n if (gac.isSelected()) {\n rip += gac.getEffect() + this.model.getDelim();\n }\n if (lootCorpse.isSelected()) {\n rip += lootCorpse.getEffect() + this.model.getDelim();\n }\n if (tsaraksoul.isSelected()) {\n rip += tsaraksoul.getEffect() + this.model.getDelim();\n }\n if (arkemile.isSelected()) {\n rip += arkemile.getEffect() + this.model.getDelim();\n }\n if (eatCorpse.isSelected()) {\n rip += eatCorpse.getEffect() + this.model.getDelim();\n }\n if (donate.isSelected()) {\n rip += donate.getEffect() + this.model.getDelim();\n }\n if (barbarianBurn.isSelected()) {\n rip += barbarianBurn.getEffect() + this.model.getDelim();\n }\n if (feedCorpseTo.isSelected()) {\n rip += feedCorpseTo.getEffect() + this.model.getDelim();\n }\n if (beheading.isSelected()) {\n rip += beheading.getEffect() + this.model.getDelim();\n }\n if (desecrateGround.isSelected()) {\n rip += desecrateGround.getEffect() + this.model.getDelim();\n }\n if (burialCere.isSelected()) {\n rip += burialCere.getEffect() + this.model.getDelim();\n }\n if (dig.isSelected()) {\n rip += dig.getEffect() + this.model.getDelim();\n }\n if (lichWake.isSelected()) {\n rip += lichWake.getEffect() + getWakeMode() + this.model.getDelim();\n }\n if (vampireWake.isSelected()) {\n rip += vampireWake.getEffect() + getWakeMode() + this.model.getDelim();\n }\n if (skeletonWake.isSelected()) {\n rip += skeletonWake.getEffect() + getWakeMode() + this.model.getDelim();\n }\n if (zombieWake.isSelected()) {\n rip += zombieWake.getEffect() + getWakeMode() + this.model.getDelim();\n }\n if (aelenaFam.isSelected()) {\n rip += aelenaFam.getEffect() + this.model.getDelim();\n }\n if (aelenaOrgan.isSelected()) {\n rip += aelenaOrgan.getEffect() + this.model.getDelim();\n }\n if (dissect.isSelected()) {\n rip += dissect.getEffect() + this.model.getDelim();\n }\n if (tin.isSelected()) {\n rip += tin.getEffect() + this.model.getDelim();\n }\n if (extractEther.isSelected()) {\n \trip += extractEther.getEffect() + this.model.getDelim();\n }\n if (ga.isSelected()) {\n rip += ga.getEffect() + this.model.getDelim();\n }\n if (lootGround.isSelected()) {\n rip += lootGround.getEffect() + this.model.getDelim();\n }\n\n\n if (rip.length() > this.model.getDelim().length()) {\n rip = rip.substring( 0, rip.length() - this.model.getDelim().length() );\n }\n\n return rip;\n }\n\n\n private String getWakeMode() {\n if (wakeFollow.isSelected()) {\n return wakeFollow.getEffect();\n }\n if (wakeAgro.isSelected()) {\n return wakeAgro.getEffect();\n }\n if (wakeTalk.isSelected()) {\n return wakeTalk.getEffect();\n }\n //else no effect:\n return wakeStatic.getEffect();\n\n }\n\n @Override\n public void componentHidden( ComponentEvent arg0 ) {\n }\n\n\n @Override\n public void componentMoved( ComponentEvent arg0 ) {\n }\n\n\n @Override\n public void componentResized( ComponentEvent arg0 ) {\n redoLayout();\n }\n\n\n @Override\n public void componentShown( ComponentEvent arg0 ) {\n }\n\n private void redoLayout() {\n this.setLayout( null );\n\n\n soulPanel.setBorder( BorderFactory.createTitledBorder( whiteline, \"Souls\", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, font, TEXT_COLOR ) );\n soulPanel.setBackground( Color.BLACK );\n listPanel.setBorder( BorderFactory.createTitledBorder( whiteline, \"Items to loot\", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, font, TEXT_COLOR ) );\n listPanel.setBackground( Color.BLACK );\n controlPanel.setBorder( BorderFactory.createTitledBorder( whiteline, \"Controls\", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, font, TEXT_COLOR ) );\n controlPanel.setBackground( Color.BLACK );\n wakePanel.setBorder( BorderFactory.createTitledBorder( whiteline, \"Wake up corpse!\", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, font, TEXT_COLOR ) );\n wakePanel.setBackground( Color.BLACK );\n lootPanel.setBorder( BorderFactory.createTitledBorder( whiteline, \"Looting\", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, font, TEXT_COLOR ) );\n lootPanel.setBackground( Color.BLACK );\n corpsePanel.setBorder( BorderFactory.createTitledBorder( whiteline, \"Carcasses\", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, font, TEXT_COLOR ) );\n corpsePanel.setBackground( Color.BLACK );\n\n soulPanel.setBounds( BORDERLINE * 2, BORDERLINE * 2, ( CB_WIDTH * 2 ) + ( 2 * TOP_BORDER ), ( CB_HEIGHT * 4 ) );\n soulPanel.setLayout( null );\n kharimsoul.setBounds( BORDERLINE, TOP_BORDER, CB_WIDTH, CB_HEIGHT );\n kharimSoulCorpse.setBounds( CB_WIDTH + BORDERLINE, TOP_BORDER, CB_WIDTH, CB_HEIGHT );\n lichdrain.setBounds( BORDERLINE, CB_HEIGHT + TOP_BORDER, CB_WIDTH, CB_HEIGHT );\n tsaraksoul.setBounds( CB_WIDTH + BORDERLINE, CB_HEIGHT + TOP_BORDER, CB_WIDTH, CB_HEIGHT );\n ripSoulToKatana.setBounds( BORDERLINE, ( CB_HEIGHT * 2 ) + TOP_BORDER, CB_WIDTH, CB_HEIGHT );\n arkemile.setBounds( CB_WIDTH + BORDERLINE, ( CB_HEIGHT * 2 ) + TOP_BORDER, CB_WIDTH, CB_HEIGHT );\n soulPanel.add( kharimsoul );\n soulPanel.add( kharimSoulCorpse );\n soulPanel.add( lichdrain );\n soulPanel.add( tsaraksoul );\n soulPanel.add( ripSoulToKatana );\n soulPanel.add( arkemile );\n this.add( soulPanel );\n\n corpsePanel.setBounds( BORDERLINE * 2, soulPanel.getHeight() + ( BORDERLINE * 4 ), ( CB_WIDTH * 2 ) + ( 2 * TOP_BORDER ), ( CB_HEIGHT * 7 ) );\n corpsePanel.setLayout( null );\n barbarianBurn.setBounds( BORDERLINE, TOP_BORDER, CB_WIDTH, CB_HEIGHT );\n feedCorpseTo.setBounds( CB_WIDTH + BORDERLINE, TOP_BORDER, CB_WIDTH, CB_HEIGHT );\n beheading.setBounds( BORDERLINE, CB_HEIGHT + TOP_BORDER, CB_WIDTH, CB_HEIGHT );\n desecrateGround.setBounds( CB_WIDTH + BORDERLINE, CB_HEIGHT + TOP_BORDER, CB_WIDTH, CB_HEIGHT );\n burialCere.setBounds( BORDERLINE, ( CB_HEIGHT * 2 ) + TOP_BORDER, CB_WIDTH, CB_HEIGHT );\n dig.setBounds( CB_WIDTH + BORDERLINE, ( CB_HEIGHT * 2 ) + TOP_BORDER, CB_WIDTH, CB_HEIGHT );\n aelenaOrgan.setBounds( BORDERLINE, ( CB_HEIGHT * 3 ) + TOP_BORDER, CB_WIDTH, CB_HEIGHT );\n aelenaFam.setBounds( CB_WIDTH + BORDERLINE, ( CB_HEIGHT * 3 ) + TOP_BORDER, CB_WIDTH, CB_HEIGHT );\n eatCorpse.setBounds( BORDERLINE, ( CB_HEIGHT * 4 ) + TOP_BORDER, CB_WIDTH, CB_HEIGHT );\n dissect.setBounds( CB_WIDTH + BORDERLINE, ( CB_HEIGHT * 4 ) + TOP_BORDER, CB_WIDTH, CB_HEIGHT );\n tin.setBounds( BORDERLINE, ( CB_HEIGHT * 5 ) + TOP_BORDER, CB_WIDTH, CB_HEIGHT );\n extractEther.setBounds( CB_WIDTH + BORDERLINE, ( CB_HEIGHT * 5 ) + TOP_BORDER, CB_WIDTH, CB_HEIGHT );\n corpsePanel.add( tin );\n corpsePanel.add( barbarianBurn );\n corpsePanel.add( feedCorpseTo );\n corpsePanel.add( beheading );\n corpsePanel.add( desecrateGround );\n corpsePanel.add( burialCere );\n corpsePanel.add( dig );\n corpsePanel.add( aelenaOrgan );\n corpsePanel.add( aelenaFam );\n corpsePanel.add( dissect );\n corpsePanel.add( eatCorpse );\n corpsePanel.add( extractEther );\n\n this.add( corpsePanel );\n\n wakePanel.setBounds( BORDERLINE * 2, corpsePanel.getHeight() + soulPanel.getHeight() + ( BORDERLINE * 6 ), ( CB_WIDTH * 2 ) + ( 2 * TOP_BORDER ), ( CB_HEIGHT * 5 ) );\n wakePanel.setLayout( null );\n lichWake.setBounds( BORDERLINE, TOP_BORDER, CB_WIDTH, CB_HEIGHT );\n skeletonWake.setBounds( BORDERLINE, CB_HEIGHT + TOP_BORDER, CB_WIDTH, CB_HEIGHT );\n zombieWake.setBounds( BORDERLINE, ( CB_HEIGHT * 2 ) + TOP_BORDER, CB_WIDTH, CB_HEIGHT );\n vampireWake.setBounds( BORDERLINE, ( CB_HEIGHT * 3 ) + TOP_BORDER, CB_WIDTH, CB_HEIGHT );\n wakeFollow.setBounds( CB_WIDTH + BORDERLINE, TOP_BORDER, CB_WIDTH, CB_HEIGHT );\n wakeAgro.setBounds( CB_WIDTH + BORDERLINE, CB_HEIGHT + TOP_BORDER, CB_WIDTH, CB_HEIGHT );\n wakeTalk.setBounds( CB_WIDTH + BORDERLINE, ( CB_HEIGHT * 2 ) + TOP_BORDER, CB_WIDTH, CB_HEIGHT );\n wakeStatic.setBounds( CB_WIDTH + BORDERLINE, ( CB_HEIGHT * 3 ) + TOP_BORDER, CB_WIDTH, CB_HEIGHT );\n wakePanel.add( wakeFollow );\n wakePanel.add( wakeAgro );\n wakePanel.add( wakeTalk );\n wakePanel.add( wakeStatic );\n wakePanel.add( lichWake );\n wakePanel.add( vampireWake );\n wakePanel.add( skeletonWake );\n wakePanel.add( zombieWake );\n this.add( wakePanel );\n\n lootPanel.setBounds( BORDERLINE * 2, wakePanel.getHeight() + corpsePanel.getHeight() + soulPanel.getHeight() + ( BORDERLINE * 8 ), ( CB_WIDTH * 2 ) + ( 2 * TOP_BORDER ), ( CB_HEIGHT * 4 ) );\n lootPanel.setLayout( null );\n gac.setBounds( BORDERLINE, TOP_BORDER, CB_WIDTH, CB_HEIGHT );\n ga.setBounds( BORDERLINE, CB_HEIGHT + TOP_BORDER, CB_WIDTH, CB_HEIGHT );\n donate.setBounds( BORDERLINE, ( CB_HEIGHT * 2 ) + TOP_BORDER, CB_WIDTH * 2, CB_HEIGHT );\n lootCorpse.setBounds( CB_WIDTH + BORDERLINE, TOP_BORDER, CB_WIDTH, CB_HEIGHT );\n lootGround.setBounds( CB_WIDTH + BORDERLINE, CB_HEIGHT + TOP_BORDER, CB_WIDTH, CB_HEIGHT );\n lootPanel.add( gac );\n lootPanel.add( ga );\n lootPanel.add( donate );\n lootPanel.add( lootCorpse );\n lootPanel.add( lootGround );\n\n this.add( lootPanel );\n\n controlPanel.setBounds( ( BORDERLINE * 4 ) + lootPanel.getWidth(), BORDERLINE * 2, ( LABEL_WIDTH * 2 ) + ( 2 * TOP_BORDER ), ( CB_HEIGHT * 9 ) );\n controlPanel.setLayout( null );\n\n\n on.setBounds( BORDERLINE, TOP_BORDER, BUTTON_WIDTH, CB_HEIGHT );\n on.setBackground( BG_COLOR );\n on.setForeground( TEXT_COLOR );\n off.setBounds( BORDERLINE, CB_HEIGHT + TOP_BORDER, BUTTON_WIDTH, CB_HEIGHT );\n off.setBackground( BG_COLOR );\n off.setForeground( TEXT_COLOR );\n delimLabel.setBounds( BORDERLINE, ( CB_HEIGHT * 3 ) + TOP_BORDER, LABEL_WIDTH, CB_HEIGHT );\n delimLabel.setForeground( TEXT_COLOR );\n delim.setBounds( LABEL_WIDTH + BORDERLINE, ( CB_HEIGHT * 3 ) + TOP_BORDER, LABEL_WIDTH, CB_HEIGHT );\n mountLabel.setBounds( BORDERLINE, ( CB_HEIGHT * 4 ) + TOP_BORDER, LABEL_WIDTH, CB_HEIGHT );\n mountLabel.setForeground( TEXT_COLOR );\n mount.setBounds( LABEL_WIDTH + BORDERLINE, ( CB_HEIGHT * 4 ) + TOP_BORDER, LABEL_WIDTH, CB_HEIGHT );\n organ1Label.setBounds( BORDERLINE, ( CB_HEIGHT * 5 ) + TOP_BORDER, LABEL_WIDTH, CB_HEIGHT );\n organ1Label.setForeground( TEXT_COLOR );\n organ1.setBounds( LABEL_WIDTH + BORDERLINE, ( CB_HEIGHT * 5 ) + TOP_BORDER, LABEL_WIDTH, CB_HEIGHT );\n organ2Label.setBounds( BORDERLINE, ( CB_HEIGHT * 6 ) + TOP_BORDER, LABEL_WIDTH, CB_HEIGHT );\n organ2Label.setForeground( TEXT_COLOR );\n organ2.setBounds( LABEL_WIDTH + BORDERLINE, ( CB_HEIGHT * 6 ) + TOP_BORDER, LABEL_WIDTH, CB_HEIGHT );\n etherLabel.setBounds( BORDERLINE, ( CB_HEIGHT * 7 ) + TOP_BORDER, LABEL_WIDTH, CB_HEIGHT );\n etherLabel.setForeground( TEXT_COLOR );\n etherFocus.setBounds( LABEL_WIDTH + BORDERLINE, ( CB_HEIGHT * 7 ) + TOP_BORDER, LABEL_WIDTH, CB_HEIGHT );\n clear.setBounds( ( 5 * BORDERLINE ) + LABEL_WIDTH, TOP_BORDER, BUTTON_WIDTH, CB_HEIGHT );\n doIt.setBounds( ( 5 * BORDERLINE ) + LABEL_WIDTH, TOP_BORDER + CB_HEIGHT, BUTTON_WIDTH, CB_HEIGHT );\n controlPanel.add( doIt );\n controlPanel.add( on );\n controlPanel.add( off );\n controlPanel.add( delim );\n controlPanel.add( mount );\n controlPanel.add( clear );\n controlPanel.add( organ1 );\n controlPanel.add( organ2 );\n controlPanel.add( delimLabel );\n controlPanel.add( mountLabel );\n controlPanel.add( organ1Label );\n controlPanel.add( organ2Label );\n controlPanel.add( etherFocus );\n controlPanel.add( etherLabel );\n controlPanel.add( clear );\n this.add( controlPanel );\n\n listPanel.setBounds( ( BORDERLINE * 4 ) + lootPanel.getWidth(), controlPanel.getHeight() + ( BORDERLINE * 4 ), ( LABEL_WIDTH * 2 ) + ( 2 * TOP_BORDER ), ( CB_HEIGHT * 12 ) + 3 );\n listPanel.setLayout( null );\n listPane.setBounds( BORDERLINE * 2, TOP_BORDER, listPanel.getWidth() - ( 4 * BORDERLINE ), listPanel.getHeight() - ( ( 2 * TOP_BORDER ) + CB_HEIGHT ) );\n add.setBounds( BORDERLINE * 2, listPane.getHeight() + CB_HEIGHT, BUTTON_WIDTH, CB_HEIGHT );\n lootItem.setBounds( BUTTON_WIDTH + ( BORDERLINE * 2 ), listPane.getHeight() + CB_HEIGHT, BUTTON_WIDTH, CB_HEIGHT );\n del.setBounds( ( BUTTON_WIDTH * 2 ) + ( BORDERLINE * 2 ), listPane.getHeight() + CB_HEIGHT, BUTTON_WIDTH, CB_HEIGHT );\n listPanel.add( listPane );\n listPanel.add( add );\n listPanel.add( lootItem );\n listPanel.add( del );\n this.add( listPanel );\n\n }\n\n\n @Override\n public void keyPressed( KeyEvent e ) {\n if (e.getSource() == lootLists) {\n if (lootLists.getSelectedIndex() > - 1) {\n if (e.getKeyCode() == KeyEvent.VK_DELETE || e.getKeyCode() == KeyEvent.VK_BACK_SPACE) {\n listModel.remove( lootLists.getSelectedIndex() );\n updateLoots();\n persistAndUpdate();\n }\n }\n }\n }\n\n\n @Override\n public void keyReleased( KeyEvent e ) {\n }\n\n\n @Override\n public void keyTyped( KeyEvent e ) {\n }\n\n\n @Override\n public void changedUpdate( DocumentEvent e ) {\n updateDelimAndMountAffected();\n this.model.setDelim( delim.getText() );\n this.model.setMountHandle( mount.getText() );\n persistAndUpdate();\n }\n\n\n @Override\n public void insertUpdate( DocumentEvent arg0 ) {\n this.model.setDelim( delim.getText() );\n this.model.setMountHandle( mount.getText() );\n updateDelimAndMountAffected();\n persistAndUpdate();\n }\n\n\n @Override\n public void removeUpdate( DocumentEvent arg0 ) {\n this.model.setDelim( delim.getText() );\n this.model.setMountHandle( mount.getText() );\n updateDelimAndMountAffected();\n persistAndUpdate();\n }\n\n\n private void updateDelimAndMountAffected() {\n donate.setEffect( \"get all from corpse\" + getDelim() + \"donate noeq\" + getDelim() + \"drop noeq\" );\n eatCorpse.setEffect( \"get corpse\" + getDelim() + \"eat corpse\" );\n feedCorpseTo.setEffect( \"get corpse\" + getDelim() + \"feed corpse to \" + mount.getText() );\n }\n\n\n private void persistAndUpdate() {\n saveToModel();\n plugin.saveRipAction( makeRipString() );\n }\n\n}", "public class AreaDataPersister {\n\n private static final String SUFFIX = \".batmap\";\n private static final String PATH = \"batMapAreas\";\n private static final String NEW_PATH = \"conf\";\n\n\n public static void save( String basedir, SparseMultigraph<Room, Exit> graph, Layout<Room, Exit> layout ) throws IOException {\n AreaSaveObject saveObject = makeSaveObject( basedir, graph, layout );\n saveData( saveObject );\n\n }\n\n\n private static void saveData( AreaSaveObject saveObject ) throws IOException {\n\tString baseName = saveObject.getFileName();\n\tFile baseFile = new File( saveObject.getFileName() );\n\tFile target = null;\n\tlong timestamp = Long.MAX_VALUE;\n\tif (baseFile.exists()) {\n\t for (int i = 0; i < 5; i++) {\n\t\tFile backup = new File ( saveObject.getFileName() + \".\" + i + \".bk\" );\n\t\tif (!backup.exists()) {\n\t\t target = backup;\n\t\t break;\n\t\t} else if (backup.lastModified() < timestamp) {\n\t\t timestamp = backup.lastModified();\n\t\t target = backup;\n\t\t}\n\t }\n\t System.out.println(\"Renaming \" + baseFile + \" to \" + target);\n\t baseFile.renameTo(target);\n\t}\n\t\n FileOutputStream fileOutputStream = new FileOutputStream( new File( saveObject.getFileName() ) );\n ObjectOutputStream objectOutputStream = new ObjectOutputStream( fileOutputStream );\n objectOutputStream.writeObject( saveObject );\n fileOutputStream.close();\n\n }\n\n\n public static AreaSaveObject loadData( String basedir, String areaName ) throws IOException, ClassNotFoundException {\n\n File dataFile = new File( getFileNameFrom( basedir, areaName ) );\n//\t\tSystem.out.println(\"\\n\\n+ndataFileForLoading\\n\\n\\n\"+dataFile);\n FileInputStream fileInputStream = new FileInputStream( dataFile );\n ObjectInputStream objectInputStream = new ObjectInputStream( fileInputStream );\n AreaSaveObject saveObject = (AreaSaveObject) objectInputStream.readObject();\n return saveObject;\n }\n\n public static List<String> listAreaNames( String basedir ) {\n File newDir = new File( basedir, NEW_PATH );\n newDir = new File( newDir, PATH );\n File folder = newDir;\n File[] files = folder.listFiles();\n LinkedList<String> names = new LinkedList<String>();\n for (File file : files) {\n if (FilenameUtils.getExtension( file.getName() ).equals( \"batmap\" )) {\n//\t\t\t\tSystem.out.println(FilenameUtils.getBaseName(file.getName()));\n names.add( FilenameUtils.getBaseName( file.getName() ) );\n }\n }\n return names;\n }\n\n private static AreaSaveObject makeSaveObject( String basedir, SparseMultigraph<Room, Exit> graph, Layout<Room, Exit> layout ) throws IOException {\n AreaSaveObject saveObject = new AreaSaveObject();\n saveObject.setGraph( graph );\n Map<Room, Point2D> locations = saveObject.getLocations();\n for (Room room : graph.getVertices()) {\n Point2D coord = layout.transform( room );\n locations.put( room, coord );\n }\n saveObject.setFileName( getFileNameFrom( basedir, graph.getVertices().iterator().next().getArea().getName() ) );\n//\t\tSystem.out.println(\"\\n\\n+nsaveobjectdone\\n\\n\\n\"+saveObject.getFileName());\n return saveObject;\n }\n\n private static String getFileNameFrom( String basedir, String areaName ) throws IOException {\n\n areaName = areaName.replaceAll( \"'\", \"\" );\n areaName = areaName.replaceAll( \"/\", \"\" );\n areaName = areaName + SUFFIX;\n File newDir = new File( basedir, NEW_PATH );\n newDir = new File( newDir, PATH );\n//\t\tFile pathFile = new File(PATH);\n if (! newDir.exists()) {\n if (! newDir.mkdir()) {\n throw new IOException( PATH + \" doesn't exist\" );\n }\n }\n\n return new File( newDir, areaName ).getPath();\n }\n\n public static void migrateFilesToNewLocation( String basedir ) {\n File oldDir = new File( PATH );\n File newDir = new File( basedir, NEW_PATH );\n newDir = new File( newDir, PATH );\n if (! oldDir.exists())\n return;\n Collection<File> oldDirFiles = FileUtils.listFiles( oldDir, null, false );\n\n try {\n if (oldDirFiles.size() == 0) {\n FileUtils.deleteDirectory( oldDir );\n return;\n }\n FileUtils.forceMkdir( newDir );\n for (File mapfile : oldDirFiles) {\n if (! FileUtils.directoryContains( newDir, mapfile )) {\n FileUtils.moveFileToDirectory( mapfile, newDir, true );\n } else {\n }\n }\n //all files moved to new place now, can safely delete old directory\n if (FileUtils.listFiles( oldDir, null, false ).size() == 0) {\n FileUtils.deleteDirectory( oldDir );\n }\n\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n\n }\n\n\n}", "public class GuiDataPersister {\n\n private final static String FILENAME = \"batMap.conf\";\n private final static String DIRNAME = \"conf\";\n\n\n public static void save( String baseDir, Point location, Dimension size ) {\n GuiData data = new GuiData( location, size );\n FileOutputStream fileOutputStream;\n try {\n fileOutputStream = new FileOutputStream( getFile( baseDir ) );\n ObjectOutputStream objectOutputStream = new ObjectOutputStream( fileOutputStream );\n objectOutputStream.writeObject( data );\n fileOutputStream.close();\n } catch (IOException e) {\n System.out.println( e );\n }\n\n\n }\n\n public static GuiData load( String basedir ) {\n try {\n FileInputStream fileInputStream = new FileInputStream( getFile( basedir ) );\n ObjectInputStream objectInputStream = new ObjectInputStream( fileInputStream );\n GuiData data = (GuiData) objectInputStream.readObject();\n return data;\n } catch (IOException e) {\n System.out.println( e );\n } catch (ClassNotFoundException e) {\n System.out.println( e );\n }\n return null;\n\n }\n\n private static File getFile( String basedir ) {\n File dirFile = new File( basedir, DIRNAME );\n File saveFile = new File( dirFile, FILENAME );\n return saveFile;\n }\n\n}", "public class Area implements Serializable {\n\n\n private static final long serialVersionUID = 5397970358054415742L;\n private String name;\n\n public Area( String name ) {\n this.name = name;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName( String name ) {\n this.name = name;\n }\n\n\n}", "public class AreaSaveObject implements Serializable {\n\n\n private static final long serialVersionUID = - 787030872360880875L;\n\n private SparseMultigraph<Room, Exit> graph;\n private Map<Room, Point2D> locations;\n private String fileName;\n\n public AreaSaveObject() {\n this.graph = new SparseMultigraph<Room, Exit>();\n this.locations = new HashMap<Room, Point2D>();\n }\n\n public SparseMultigraph<Room, Exit> getGraph() {\n return graph;\n }\n\n public void setGraph( SparseMultigraph<Room, Exit> graph ) {\n this.graph = graph;\n }\n\n public Map<Room, Point2D> getLocations() {\n return locations;\n }\n\n public void setLocations( Map<Room, Point2D> locations ) {\n this.locations = locations;\n }\n\n public String getFileName() {\n return fileName;\n }\n\n public void setFileName( String fileName ) {\n this.fileName = fileName;\n }\n\n\n}", "public class Exit implements Serializable {\n\n\n private static final long serialVersionUID = 3983564665752135097L;\n private String exit;\n private String compassDir;\n private boolean currentExit;\n public final String TELEPORT = \"teleport\";\n\n\n public Exit( String exit ) {\n this.exit = exit;\n this.compassDir = this.checkWhatExitIs( exit );\n }\n\n private String checkWhatExitIs( String exit ) {\n if (exit.equalsIgnoreCase( \"n\" ) || exit.equalsIgnoreCase( \"north\" ))\n return \"n\";\n if (exit.equalsIgnoreCase( \"e\" ) || exit.equalsIgnoreCase( \"east\" ))\n return \"e\";\n if (exit.equalsIgnoreCase( \"s\" ) || exit.equalsIgnoreCase( \"south\" ))\n return \"s\";\n if (exit.equalsIgnoreCase( \"w\" ) || exit.equalsIgnoreCase( \"west\" ))\n return \"w\";\n if (exit.equalsIgnoreCase( \"ne\" ) || exit.equalsIgnoreCase( \"northeast\" ))\n return \"ne\";\n if (exit.equalsIgnoreCase( \"nw\" ) || exit.equalsIgnoreCase( \"northwest\" ))\n return \"nw\";\n if (exit.equalsIgnoreCase( \"se\" ) || exit.equalsIgnoreCase( \"southeast\" ))\n return \"se\";\n if (exit.equalsIgnoreCase( \"sw\" ) || exit.equalsIgnoreCase( \"southwest\" ))\n return \"sw\";\n if (exit.equalsIgnoreCase( \"d\" ) || exit.equalsIgnoreCase( \"down\" ))\n return \"d\";\n if (exit.equalsIgnoreCase( \"u\" ) || exit.equalsIgnoreCase( \"up\" ))\n return \"u\";\n return null;\n }\n\n public String getExit() {\n return exit;\n }\n\n public void setExit( String exit ) {\n this.exit = exit;\n }\n\n public String toString() {\n return this.exit;\n }\n\n public String getCompassDir() {\n return compassDir;\n }\n\n public boolean isCurrentExit() {\n return currentExit;\n }\n\n public void setCurrentExit( boolean currentExit ) {\n this.currentExit = currentExit;\n }\n\n public boolean equals( Object o ) {\n if (o instanceof Exit) {\n if (this.exit.equals( ( (Exit) o ).getExit() ))\n return true;\n }\n return false;\n\n }\n\n}", "public class Room implements Serializable {\n\n\n private static final long serialVersionUID = 9036581185666106041L;\n private String id;\n private String shortDesc;\n private String longDesc;\n private boolean areaEntrance = false;\n private boolean current = false;\n private boolean drawn = false;\n private Area area;\n private boolean picked = false;\n Set<String> exits = new HashSet<String>();\n private boolean indoors;\n private String notes;\n private Color color = null;\n private String label;\n private Set<String> usedExits = new HashSet<>();\n\n\n public Room( String shortDesc, String id ) {\n this.shortDesc = shortDesc;\n this.id = id;\n }\n\n public Room( String shortDesc, String id, Area area ) {\n this.shortDesc = shortDesc;\n this.id = id;\n this.area = area;\n }\n\n public Room( String id, Area area ) {\n this.id = id;\n this.area = area;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId( String id ) {\n this.id = id;\n }\n\n public String getShortDesc() {\n return shortDesc;\n }\n\n public void setShortDesc( String shortDesc ) {\n this.shortDesc = shortDesc;\n }\n\n public String getLongDesc() {\n return longDesc;\n }\n\n public void setLongDesc( String longDesc ) {\n this.longDesc = longDesc;\n }\n\n\n public boolean isAreaEntrance() {\n return areaEntrance;\n }\n\n\n public void setAreaEntrance( boolean areaEntrance ) {\n this.areaEntrance = areaEntrance;\n }\n\n\n public boolean isCurrent() {\n return current;\n }\n\n\n public void setCurrent( boolean current ) {\n this.current = current;\n }\n\n\n public boolean isDrawn() {\n return drawn;\n }\n\n\n public void setDrawn( boolean drawn ) {\n this.drawn = drawn;\n }\n\n\n public Area getArea() {\n return area;\n }\n\n public void setArea( Area area ) {\n this.area = area;\n }\n\n public boolean isPicked() {\n return picked;\n }\n\n public void setPicked( boolean picked ) {\n this.picked = picked;\n }\n\n public Set<String> getExits() {\n return exits;\n }\n\n public void setExits( Set<String> exits ) {\n this.exits = exits;\n }\n\n public boolean isIndoors() {\n return indoors;\n }\n\n public void setIndoors( boolean indoors ) {\n this.indoors = indoors;\n }\n\n public String toString() {\n return this.shortDesc;\n }\n\n public boolean equals( Object o ) {\n if (o instanceof Room) {\n if (this.id.equals( ( (Room) o ).getId() ))\n return true;\n }\n return false;\n\n }\n\n public void setDescs( String shortDesc, String longDesc ) {\n this.shortDesc = shortDesc;\n this.longDesc = longDesc;\n }\n\n public void addExits( Collection<String> outExits ) {\n this.exits.addAll( outExits );\n }\n\n public void addExit( String exit ) {\n this.exits.add( exit );\n }\n\n public String getNotes() {\n return notes;\n }\n\n public Color getColor() {\n return color;\n }\n\n public void setColor( Color color ) {\n this.color = color;\n }\n\n public void setNotes( String notes ) {\n this.notes = notes;\n }\n\n public void setLabel(String label){\n this.label = label;\n }\n\n public String getLabel(){\n return this.label;\n }\n\n public void useExit(String exit){\n if(usedExits == null){\n usedExits = new HashSet<>();\n }\n this.usedExits.add(exit);\n }\n public boolean allExitsHaveBeenUSed(){\n if(usedExits == null){\n usedExits = new HashSet<>();\n }\n if(exits.containsAll(usedExits) && usedExits.containsAll(exits)){\n return true;\n }\n return false;\n }\n public void resetExitUsage(){\n this.usedExits = new HashSet<>();\n }\n}" ]
import java.awt.Color; import java.awt.Dimension; import java.awt.Point; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseEvent; import java.awt.geom.Point2D; import java.io.IOException; import java.util.*; import com.glaurung.batMap.gui.*; import com.glaurung.batMap.gui.corpses.CorpsePanel; import com.glaurung.batMap.io.AreaDataPersister; import com.glaurung.batMap.io.GuiDataPersister; import com.glaurung.batMap.vo.Area; import com.glaurung.batMap.vo.AreaSaveObject; import com.glaurung.batMap.vo.Exit; import com.glaurung.batMap.vo.Room; import com.mythicscape.batclient.interfaces.BatWindow; import edu.uci.ics.jung.algorithms.shortestpath.DijkstraShortestPath; import edu.uci.ics.jung.graph.SparseMultigraph; import edu.uci.ics.jung.graph.util.EdgeType; import edu.uci.ics.jung.graph.util.Pair; import edu.uci.ics.jung.visualization.Layer; import edu.uci.ics.jung.visualization.RenderContext; import edu.uci.ics.jung.visualization.VisualizationViewer; import edu.uci.ics.jung.visualization.control.CrossoverScalingControl; import edu.uci.ics.jung.visualization.control.PluggableGraphMouse; import edu.uci.ics.jung.visualization.control.ScalingGraphMousePlugin; import edu.uci.ics.jung.visualization.control.TranslatingGraphMousePlugin; import edu.uci.ics.jung.visualization.decorators.EdgeShape; import edu.uci.ics.jung.visualization.decorators.ToStringLabeller; import edu.uci.ics.jung.visualization.picking.PickedState; import edu.uci.ics.jung.visualization.transform.MutableTransformer;
package com.glaurung.batMap.controller; public class MapperEngine implements ItemListener, ComponentListener { SparseMultigraph<Room, Exit> graph; VisualizationViewer<Room, Exit> vv; MapperLayout mapperLayout; Room currentRoom = null; Area area = null; MapperPanel panel; PickedState<Room> pickedState; String baseDir; BatWindow batWindow; ScalingGraphMousePlugin scaler; MapperPickingGraphMousePlugin mapperPickingGraphMousePlugin; boolean snapMode = true;
CorpsePanel corpsePanel;
0
thlcly/Mini-JVM
src/main/java/com/aaront/exercise/jvm/commands/GetStaticFieldCommand.java
[ "@Data\npublic class ClassFile {\n private String magicNumber;\n private int majorVersion;\n private int minorVersion;\n private ClassIndex classIndex;\n private InterfaceIndex interfaceIndex;\n private ConstantPool constantPool;\n private List<ClassAccessFlag> accessFlags;\n private List<Field> fields;\n private Map<Pair<String, String>, Method> methods;\n\n public String getSuperClassName(){\n ClassConstant superClass = (ClassConstant)this.getConstantPool().getConstantInfo(this.classIndex.getSuperClassIndex());\n return superClass.getClassName();\n }\n\n public Method getMethod(String methodName, String paramAndReturnType){\n\n for(Method m :methods.values()){\n\n int nameIndex = m.getNameIndex();\n int descriptionIndex = m.getDescriptorIndex();\n\n String name = this.getConstantPool().getUTF8String(nameIndex);\n String desc = this.getConstantPool().getUTF8String(descriptionIndex);\n if(name.equals(methodName) && desc.equals(paramAndReturnType)){\n return m;\n }\n }\n return null;\n }\n}", "@Data\n@EqualsAndHashCode(callSuper = true)\npublic class ClassConstant extends AbstractConstant {\n private int nameIndex;\n private String className;\n\n public ClassConstant(ConstantPool pool, int tag, int nameIndex) {\n super(tag, pool);\n this.nameIndex = nameIndex;\n }\n\n public String getClassName() {\n if(className == null) className = pool.getUTF8String(nameIndex);\n return className;\n }\n}", "@Data\npublic class ConstantPool {\n private List<AbstractConstant> abstractConstant = new ArrayList<>();\n\n public ConstantPool(List<AbstractConstant> abstractConstant) {\n this.abstractConstant = abstractConstant;\n }\n\n public ConstantPool() {\n\n }\n\n public AbstractConstant getConstantInfo(int index) {\n return this.abstractConstant.get(index);\n }\n\n public String getUTF8String(int index) {\n return ((UTF8Constant) this.abstractConstant.get(index)).getValue();\n }\n\n public int getSize() {\n return this.abstractConstant.size() - 1;\n }\n}", "@Data\n@EqualsAndHashCode(callSuper = true)\npublic class FieldRefConstant extends AbstractConstant {\n private int classIndex;\n private ClassConstant classConstant;\n private int nameAndTypeIndex;\n private NameAndTypeConstant nameAndTypeConstant;\n\n public FieldRefConstant(ConstantPool pool, int tag, int classIndex, int nameAndTypeIndex) {\n super(tag, pool);\n this.classIndex = classIndex;\n this.nameAndTypeIndex = nameAndTypeIndex;\n }\n\n public ClassConstant getClassConstant() {\n if(classConstant == null) classConstant = (ClassConstant) pool.getConstantInfo(classIndex);\n return classConstant;\n }\n\n public NameAndTypeConstant getNameAndTypeConstant() {\n if(nameAndTypeConstant == null) nameAndTypeConstant = (NameAndTypeConstant) pool.getConstantInfo(nameAndTypeIndex);\n return nameAndTypeConstant;\n }\n}", "@Data\npublic class ExecutionResult {\n\n private NextAction nextAction = RUN_NEXT_CMD;\n\n private int nextCmdOffset = 0;\n\n private Method nextMethod;\n\n public boolean isPauseAndRunNewFrame() {\n return this.nextAction == PAUSE_AND_RUN_NEW_FRAME;\n }\n\n public boolean isExitCurrentFrame() {\n return this.nextAction == EXIT_CURRENT_FRAME;\n }\n\n public boolean isRunNextCmd() {\n return this.nextAction == RUN_NEXT_CMD;\n }\n\n public boolean isJump() {\n return this.nextAction == JUMP;\n }\n}", "public class Heap {\n /**\n * 没有实现垃圾回收, 所以对于下面新创建的对象, 并没有记录到一个数据结构当中\n */\n\n private static Heap instance = new Heap();\n private Heap() {\n }\n public static Heap getInstance(){\n return instance;\n }\n public JavaObject newObject(String clzName){\n\n JavaObject jo = new JavaObject(OBJECT);\n jo.setClassName(clzName);\n return jo;\n }\n\n public JavaObject newString(String value){\n JavaObject jo = new JavaObject(STRING);\n jo.setStringValue(value);\n return jo;\n }\n\n public JavaObject newFloat(float value){\n JavaObject jo = new JavaObject(FLOAT);\n jo.setFloatValue(value);\n return jo;\n }\n public JavaObject newInt(int value){\n JavaObject jo = new JavaObject(INT);\n jo.setIntValue(value);\n return jo;\n }\n\n}", "@Data\npublic class JavaObject {\n private JavaType type;\n private String className;\n\n private Map<String, JavaObject> fieldValues = new HashMap<>();\n\n private String stringValue;\n\n private int intValue;\n\n private float floatValue;\n\n private long longValue;\n\n public void setFieldValue(String fieldName, JavaObject fieldValue) {\n fieldValues.put(fieldName, fieldValue);\n }\n\n public JavaObject(JavaType type) {\n this.type = type;\n }\n\n public JavaObject getFieldValue(String fieldName) {\n return this.fieldValues.get(fieldName);\n }\n\n public String toString() {\n switch (this.getType()) {\n case INT:\n return String.valueOf(this.intValue);\n case STRING:\n return this.stringValue;\n case OBJECT:\n return this.className + \":\" + this.fieldValues;\n case FLOAT:\n return String.valueOf(this.floatValue);\n case LONG:\n return String.valueOf(this.longValue);\n default:\n return null;\n }\n }\n}", "@Data\npublic class StackFrame {\n // 下一条指令的位置(偏移量)\n private int index = 0;\n private JavaObject returnValue = null;\n private StackFrame callerStackFrame;\n private ConstantPool pool;\n private Stack<JavaObject> operandStack;\n //这里最好是用数据来保存, 如果使用List会很不方便, 因为一些指令会对localVariableTable指定位置设置值, 如果使用List且List的size<所要设置的位置会报错\n private JavaObject[] localVariableTable;\n private Method method;\n private List<AbstractCommand> commands;\n\n public StackFrame(Method method) {\n this.method = method;\n this.commands = method.getCodeAttribute().getCommands();\n this.pool = method.getPool();\n this.operandStack = new Stack<>();\n this.localVariableTable = new JavaObject[method.getCodeAttribute().getMaxLocals()];\n }\n}" ]
import com.aaront.exercise.jvm.ClassFile; import com.aaront.exercise.jvm.constant.ClassConstant; import com.aaront.exercise.jvm.constant.ConstantPool; import com.aaront.exercise.jvm.constant.FieldRefConstant; import com.aaront.exercise.jvm.engine.ExecutionResult; import com.aaront.exercise.jvm.engine.Heap; import com.aaront.exercise.jvm.engine.JavaObject; import com.aaront.exercise.jvm.engine.StackFrame;
package com.aaront.exercise.jvm.commands; /** * @author tonyhui * @since 17/6/17 */ public class GetStaticFieldCommand extends TwoOperandCommand { public GetStaticFieldCommand(ClassFile clzFile, String opCode, int operand1, int operand2) { super(clzFile, opCode, operand1, operand2); } @Override public String toString(ConstantPool pool) { return super.getOperandAsField(pool); } /** * 获取对象的静态字段值 */ @Override public void execute(StackFrame frame, ExecutionResult result) { FieldRefConstant fieldRefConstant = (FieldRefConstant) this.getConstantInfo(this.getIndex()); ClassConstant classConstant = fieldRefConstant.getClassConstant(); String className = classConstant.getClassName();
JavaObject jo = Heap.getInstance().newObject(className);
5
jGleitz/JUnit-KIT
src/final2/subtests/PraktomatPublicTest.java
[ "public class Input {\n\tprivate static HashMap<String, String[]> filesMap = new HashMap<>();\n\tprivate static HashMap<String[], String> reverseFileMap = new HashMap<>();\n\n\t/**\n\t * This class is not meant to be instantiated.\n\t */\n\tprivate Input() {\n\t}\n\n\t/**\n\t * Returns a path to a file containing the lines given in {@code lines}. Creates the file if it was not created\n\t * before.\n\t * \n\t * @param lines\n\t * The lines to print in the file.\n\t * @return path to a file containing {@code lines}\n\t */\n\tpublic static String getFile(String... lines) {\n\t\tString fileName;\n\t\tif (!Input.reverseFileMap.containsKey(lines)) {\n\t\t\tfileName = UUID.randomUUID().toString() + \".txt\";\n\t\t\tFile file = new File(fileName);\n\t\t\tBufferedWriter outputWriter = null;\n\t\t\ttry {\n\t\t\t\toutputWriter = new BufferedWriter(new FileWriter(file));\n\t\t\t\tfor (String line : lines) {\n\t\t\t\t\toutputWriter.write(line);\n\t\t\t\t\toutputWriter.newLine();\n\t\t\t\t}\n\t\t\t\toutputWriter.flush();\n\t\t\t\toutputWriter.close();\n\t\t\t\tfile.deleteOnExit();\n\t\t\t} catch (IOException e) {\n\t\t\t\tfail(\"The test was unable to create a test file. That's a shame!\");\n\t\t\t}\n\n\t\t\tInput.filesMap.put(fileName, lines);\n\t\t\tInput.reverseFileMap.put(lines, fileName);\n\t\t} else {\n\t\t\tfileName = Input.reverseFileMap.get(lines);\n\t\t}\n\t\treturn fileName;\n\t}\n\n\t/**\n\t * Returns a path to a file containing the lines given in {@code lines}. Creates the file if it was not created\n\t * before.\n\t * \n\t * @param lines\n\t * The lines to print in the file.\n\t * @return path to a file containing {@code lines}\n\t */\n\tpublic static String getFile(Collection<String> lines) {\n\t\tString[] linesArray = new String[lines.size()];\n\t\tIterator<String> iterator = lines.iterator();\n\t\tfor (int i = 0; iterator.hasNext(); i++) {\n\t\t\tlinesArray[i] = iterator.next();\n\t\t}\n\t\treturn getFile(linesArray);\n\t}\n\n\t/**\n\t * A message giving information about the input file used in a test.\n\t * \n\t * @param filePath\n\t * The command line arguments the main method was called with during the test. The file message will read\n\t * the file name in the second argument and output the contents of the file its pointing to.\n\t * @return A text representing the input file\n\t */\n\tpublic static String fileMessage(String filePath) {\n\t\tString result = \"\";\n\t\tif (filesMap.containsKey(filePath)) {\n\t\t\tresult = \"\\n with the following input file:\\n\\n\" + arrayToLines(filesMap.get(filePath)) + \"\\n\\n\";\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * @return The paths to all generated input files.\n\t */\n\tpublic static List<String> getAllFilePaths() {\n\t\treturn new LinkedList<String>(filesMap.keySet());\n\t}\n\n\t/**\n\t * @param filePath\n\t * The path of a generated input file.\n\t * @return The lines of the input file that was given the path {@code filePath}, {@code null} if there is no such\n\t * file.\n\t */\n\tpublic static String[] getFileContentOf(String filePath) {\n\t\treturn filesMap.get(filePath);\n\t}\n\n\tpublic static boolean isFile(String fileName) {\n\t\treturn filesMap.containsKey(fileName);\n\t}\n\n\t/**\n\t * Converts an Array of Strings into a String where each array element is represented as one line.\n\t * \n\t * @param lines\n\t * The array to process\n\t * @return the array as lines.\n\t */\n\tpublic static String arrayToLines(String[] lines) {\n\t\tString result = \"\";\n\t\tfor (String line : lines) {\n\t\t\tif (result != \"\") {\n\t\t\t\tresult += \"\\n\";\n\t\t\t}\n\t\t\tresult += line;\n\t\t}\n\t\treturn result;\n\t}\n\n}", "public enum SystemExitStatus {\n\t/**\n\t * {@code System.exit(x)} with any argument {@code x}.\n\t */\n\tALL,\n\t/**\n\t * No call to {@code System.exit(x)} at all.\n\t */\n\tNONE,\n\t/**\n\t * {@code System.exit(0)}.\n\t */\n\tWITH_0,\n\t/**\n\t * {@code System.exit(x)} with x>0.\n\t */\n\tWITH_GREATER_THAN_0,\n\t/**\n\t * {@code System.exit(x)} with a {@code x} that has to be specified through {@link #status(int)}.\n\t */\n\tEXACTLY;\n\n\tprivate int exactSystemExitStatus = -1;\n\n\t@Override\n\tpublic String toString() {\n\t\tswitch (this) {\n\t\tcase ALL:\n\t\t\treturn \"System.exit(x) with any x >= 0\";\n\t\tcase NONE:\n\t\t\treturn \"no call to System.exit(x) at all\";\n\t\tcase WITH_0:\n\t\t\treturn \"System.exit(0)\";\n\t\tcase WITH_GREATER_THAN_0:\n\t\t\treturn \"System.exit(x) with any x > 0\";\n\t\tcase EXACTLY:\n\t\t\treturn \"System.exit(\" + exactSystemExitStatus + \")\";\n\t\tdefault:\n\t\t\tthrow new IllegalArgumentException();\n\t\t}\n\t}\n\n\t/**\n\t * @param status\n\t * A status {@code System.exit} was called with.\n\t * @param mandatory\n\t * Whether it was obligatory to call {@code System.exit}.\n\t * @return Whether {@code status} matches the system exit status described by this enum instance. If {@code status}\n\t * is null, and {@code obligatory} is {@code true}, this method always returns {@code false}. If\n\t * {@code status} is null, and {@code obligatory} is {@code false}, this method always returns {@code true}.\n\t */\n\tpublic boolean matches(Integer status, boolean mandatory) {\n\t\tif (status == null) {\n\t\t\treturn !mandatory;\n\t\t}\n\t\tswitch (this) {\n\t\tcase ALL:\n\t\t\treturn true;\n\t\tcase NONE:\n\t\t\treturn false;\n\t\tcase WITH_0:\n\t\t\treturn status == 0;\n\t\tcase WITH_GREATER_THAN_0:\n\t\t\treturn status > 0;\n\t\tcase EXACTLY:\n\t\t\treturn status == exactSystemExitStatus;\n\t\tdefault:\n\t\t\tthrow new IllegalStateException(\"this was not recognised!\");\n\t\t}\n\t}\n\n\t/**\n\t * @return If this is {@link #EXACTLY}, the exact status implied by the enum.\n\t * @throws IllegalStateException\n\t * If {@code this} is not {@link #EXACTLY} or {@link #status(int)} has not been called yet.\n\t */\n\tpublic int getExactStatus() {\n\t\tif (this != EXACTLY) {\n\t\t\tthrow new IllegalStateException(\"This method may only be called for the EXACTLY enum\");\n\t\t}\n\t\tif (exactSystemExitStatus == -1) {\n\t\t\tthrow new IllegalStateException(\"The exact status has not been set yet!\");\n\t\t}\n\t\treturn exactSystemExitStatus;\n\t}\n\n\t/**\n\t * @param status\n\t * The status that is implied by {@link #EXACTLY}.\n\t * @return {@code this}\n\t * @throws IllegalStateException\n\t * If {@code this} is not {@link #EXACTLY}.\n\t * @throws IllegalArgumentException\n\t * If {@code status < 0}.\n\t */\n\tpublic SystemExitStatus status(int status) {\n\t\tif (this != EXACTLY) {\n\t\t\tthrow new IllegalStateException(\"This method may only be called for the EXACTLY enum\");\n\t\t}\n\t\tif (status < 0) {\n\t\t\tthrow new IllegalArgumentException(\"There is no system exit status lower than 0!\");\n\t\t}\n\t\tthis.exactSystemExitStatus = status;\n\t\treturn this;\n\t}\n}", "public class LineRun implements Run {\n\tprivate String command;\n\tprivate List<Matcher<String>> expectedResults;\n\n\t/**\n\t * Creates a test run that merges all calls to {@code Terminal.printLine}. The run succeeds if the merged output\n\t * matches {@code expectedResults} line by line.\n\t * \n\t * @param command\n\t * The command to run\n\t * @param expectedResults\n\t * The matchers describing the desired output\n\t */\n\tpublic LineRun(String command, List<Matcher<String>> expectedResults) {\n\t\tthis.command = command;\n\t\tthis.expectedResults = expectedResults;\n\t}\n\n\t/**\n\t * Creates a test run that merges all calls to {@code Terminal.printLine}. The run succeeds if the merged output\n\t * matches {@code expectedResults} line by line.\n\t * \n\t * @param command\n\t * The command to run\n\t * @param expectedResults\n\t * The matchers describing the desired output\n\t */\n\t@SafeVarargs\n\tpublic LineRun(String command, Matcher<String>... expectedResults) {\n\t\tthis(command, Arrays.asList(expectedResults));\n\t}\n\n\t/**\n\t * Creates a test run without a command that merges all calls to {@code Terminal.printLine}. The run succeeds if the\n\t * merged output matches {@code expectedResults} line by line. Use only to test errors before the first command.\n\t * \n\t * @param expectedResults\n\t * The matchers describing the desired output\n\t */\n\tpublic LineRun(List<Matcher<String>> expectedResults) {\n\t\tthis(null, expectedResults);\n\t}\n\n\t/**\n\t * Creates a test run without a command that merges all calls to {@code Terminal.printLine}. The run succeeds if the\n\t * merged output matches {@code expectedResults} line by line. Use only to test errors before the first command.\n\t * \n\t * @param expectedResults\n\t * The matchers describing the desired output\n\t */\n\t@SafeVarargs\n\tpublic LineRun(Matcher<String>... expectedResults) {\n\t\tthis(null, expectedResults);\n\t}\n\n\t/*\n\t * (non-Javadoc)\n\t * \n\t * @see test.runs.Run#getCommand()\n\t */\n\t@Override\n\tpublic String getCommand() {\n\t\treturn this.command;\n\t}\n\n\t/*\n\t * (non-Javadoc)\n\t * \n\t * @see test.runs.Run#check(java.lang.String[], java.lang.String)\n\t */\n\t@Override\n\tpublic void check(String[] testedClassOutput, String errorMessage) {\n\t\tIterator<Matcher<String>> expectedIterator = expectedResults.iterator();\n\t\tString[] outputLines = mergedOutputLines(testedClassOutput);\n\t\tString overallErrorMessage = errorMessage + \"\\nYour output:\\n\" + mergedOutput(testedClassOutput);\n\t\tassertThat(overallErrorMessage, outputLines, hasExcactlyThatMuch(expectedResults.size(), new String[] {\n\t\t\t\t\"lines\",\n\t\t\t\t\"line\",\n\t\t\t\t\"lines\"\n\t\t}));\n\t\tfor (int count = 0; count < outputLines.length; count++) {\n\t\t\tString appendix = \"\\n First error at line \" + count + \":\";\n\t\t\tassertThat(errorMessage + appendix, outputLines[count], expectedIterator.next());\n\t\t}\n\t}\n\n\t/**\n\t * @param output\n\t * The output to merge.\n\t * @return All output joined with {@code \\n}. Explicitly uses {@code \\n} for concatenation and removes potentially\n\t * contained {@code \\r}.\n\t */\n\tprotected String mergedOutput(String[] output) {\n\n\t\tStringBuilder mergedOutputBuilder = new StringBuilder();\n\t\tfor (String call : output) {\n\t\t\tmergedOutputBuilder.append(call.replace(\"\\r\", \"\"));\n\t\t\tmergedOutputBuilder.append(\"\\n\");\n\t\t}\n\t\treturn mergedOutputBuilder.toString();\n\t}\n\n\t/**\n\t * The joined output merged by {@link #mergedOutput(String[])} split at {@code \\n}. Unlike\n\t * {@link String#split(String)}, this method guarantees one array element per occurrence of {@code \\n}.\n\t * \n\t * @param output\n\t * The output to process\n\t * @return One array element per line found in any of {@code output}'s elements.\n\t */\n\tprotected String[] mergedOutputLines(String[] output) {\n\t\tScanner outputScanner = new Scanner(\"\\n\" + mergedOutput(output));\n\t\toutputScanner.useDelimiter(\"\\n\");\n\t\tList<String> outputList = new ArrayList<>();\n\t\twhile (outputScanner.hasNext()) {\n\t\t\toutputList.add(outputScanner.next());\n\t\t}\n\t\toutputScanner.close();\n\t\treturn outputList.toArray(new String[outputList.size()]);\n\t}\n\n\t/*\n\t * (non-Javadoc)\n\t * \n\t * @see test.runs.Run#getExpectedDescription()\n\t */\n\t@Override\n\tpublic String getExpectedDescription() {\n\t\tStringBuilder resultBuilder = new StringBuilder();\n\t\tfor (Matcher<String> matcher : expectedResults) {\n\t\t\tif (resultBuilder.length() > 0) {\n\t\t\t\tresultBuilder.append(\"\\n\");\n\t\t\t}\n\t\t\tresultBuilder.append(matcher);\n\t\t}\n\t\treturn resultBuilder.toString();\n\t}\n}", "public class NoOutputRun extends ExactRun {\n\n\t/**\n\t * Constructs a test run for the given command that fails if {@code Terminal.printLine} is ever called by the tested\n\t * class.\n\t */\n\tpublic NoOutputRun(String command) {\n\t\tsuper(command, \"no output at all\", new LinkedList<Matcher<String>>());\n\t}\n\n\t/**\n\t * Constructs a test run without a command that fails if {@code Terminal.printLine} is ever called by the tested\n\t * class. Use only to test errors before the first command.\n\t */\n\tpublic NoOutputRun() {\n\t\tthis(null);\n\t}\n}", "public interface Run {\n\n\t/**\n\t * Checks whether the output of the tested class does fulfil the needs defined by this run. Throws an exception if\n\t * it doesn't.\n\t * \n\t * @param testedClassOutput\n\t * The output of the tested class for this run. One String represents one call to\n\t * {@code Terminal.printLine}.\n\t * @param errorMessage\n\t * The message that will be reported to {@link org.junit.Assert#fail(String)} or\n\t * {@link org.junit.Assert#assertThat(String, Object, org.hamcrest.Matcher)}\n\t * @throws RunFailedException\n\t * If {@code testedClassOutput} does not fulfil this test run's expected output.\n\t */\n\tpublic void check(String[] testedClassOutput, String errorMessage);\n\n\t/**\n\t * @return The command that is to be run on the interactive console for this test run.\n\t */\n\tpublic String getCommand();\n\n\t/**\n\t * @return A String describing what this test run expects the tested class to print.\n\t */\n\tpublic String getExpectedDescription();\n}" ]
import static org.hamcrest.CoreMatchers.is; import org.junit.Test; import test.Input; import test.SystemExitStatus; import test.runs.LineRun; import test.runs.NoOutputRun; import test.runs.Run;
package final2.subtests; /** * Simulates the Praktomat's public test. * * @author Martin Löper */ public class PraktomatPublicTest extends LangtonSubtest { public PraktomatPublicTest() { setAllowedSystemExitStatus(SystemExitStatus.WITH_0); } /** * "Fundamental tests with ordinary ant" Asserts that tested program fulfils the first public Praktomat test. */ @Test public void fundamentalTestsWithOrdinaryAnt() { String[] expectedOutput = pitchToLowercase(PUBLIC_PRAKTOMAT_TEST_FILE_1); runs = new Run[] { checkPitch(expectedOutput), new LineRun("position A", is("2,1")), new LineRun("position a", is("2,1")), new LineRun("field 2,1", is("a")), new LineRun("direction a", is("N")), new LineRun("ant", is("a")), new NoOutputRun("create e,0,0"), new LineRun("ant", is("a,e")), new LineRun("direction e", is("S")), new NoOutputRun("move 1"), new LineRun("direction e", is("O")), new NoOutputRun("quit") };
sessionTest(runs, Input.getFile(PUBLIC_PRAKTOMAT_TEST_FILE_1));
0
codebulb/LambdaOmega
src/test/java/ch/codebulb/lambdaomega/LBaseTest.java
[ "public static <T> L<T> L(Stream<T> stream) {\n return new L(stream.collect(Collectors.toList()));\n}", "public static <T> L<T> l() {\n return new L<>(new ArrayList<>());\n}", "public static <T> List<T> list(T... ts) {\n return l(ts).l;\n}", "public static final List<Integer> EXPECTED_LIST = new ArrayList<>();", "public static final List<List<Integer>> EXPECTED_NESTED_LIST = new ArrayList<>();", "public static <T> void assertEquals(T expected, T... actual) {\n Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it));\n}", "public interface I<K, V> {\n // We have to allow derived return values because we need that in V2\n /**\n * Invokes Map#get(Object) or invokes the function set by {@link #WithDefault(Function)} with the <code>key</code> provided,\n * if it would return <code>null</code> or the key is invalid.\n */\n public <VN extends V> VN get(K key);\n \n /**\n * @see #get(Object)\n */\n public default List<V> get(K... keys) {\n return C.toStream(keys).map(it -> this.<V> get(it)).collect(Collectors.toList());\n }\n \n /**\n * @see #get(Object)\n */\n public default List<V> getAll(Collection<K>... keys) {\n return C.toStream(keys).map(c -> C.toStream(c).map(it -> this.<V> get(it)).collect(Collectors.toList()))\n .flatMap(Collection::stream).collect(Collectors.toList());\n }\n \n // We have to allow derived return values because we need that in V2\n /**\n * @see Map#getOrDefault(Object, Object)\n */\n public <VN extends V> VN getOrDefault(K key, VN defaultValue);\n \n /**\n * Sets the function for creating a default value as an alternative to an otherwise unsuccessful {@link #get(Object)} invocation.\n * \n * @param defaultValue the new default value\n * @return <code>this (modified)</code>\n */\n public ReadonlyIndexedI<K, V> WithDefault(Function<K, V> defaultValue);\n \n /**\n * @see #get(Object)\n */\n public default L<V> g(K... keys) {\n return Get(keys);\n }\n \n /**\n * @see #get(Object)\n */\n public default V g(K key) {\n return get(key);\n }\n \n /**\n * @see #get(Object)\n */\n public default L<V> Get(K... keys) {\n return L(get(keys));\n }\n \n /**\n * @see #get(Object)\n */\n public default L<V> GetAll(Collection<K>... keys) {\n return L(getAll(keys));\n }\n \n /**\n * @see #get(Object)\n */\n public default L<V> G(Collection<K>... keys) {\n return L(getAll(keys));\n }\n}" ]
import static ch.codebulb.lambdaomega.L.L; import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.L.list; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_LIST; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_NESTED_LIST; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import ch.codebulb.lambdaomega.abstractions.I; import java.util.ArrayList; import java.util.List; import org.junit.AfterClass; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.BeforeClass; import org.junit.Test;
package ch.codebulb.lambdaomega; /** * Basic test cases for {@link L}. */ public class LBaseTest { @BeforeClass public static void beforeClass() {
L.TEST_DISABLE_HELPER_MAP_CONVERSION = true;
0
TreyRuffy/CommandBlocker
Command Blocker Bungee/src/main/java/me/treyruffy/commandblocker/bungeecord/BungeeMain.java
[ "public class Universal {\n\n\tprivate static Universal instance = null;\n\tprivate MethodInterface mi;\n\t\n\tpublic static Universal get() {\n\t\treturn instance == null ? instance = new Universal() : instance;\n\t}\n\t\n\tpublic void setup(MethodInterface mi) {\n\t\tthis.mi = mi;\n\t\t\n\t\tmi.setupMetrics();\n\t}\n\t\n\tpublic MethodInterface getMethods() {\n return mi;\n }\n\t\n}", "public class CommandBlockerCommand extends Command implements TabExecutor {\n\t\n\tpublic CommandBlockerCommand() {\n \tsuper(\"cb\", \"\", \"commandblockerbungee\", \"commandblocker\", \"commandblock\");\n }\n\t\n @Override\n\tpublic void execute(CommandSender sender, String[] args) {\n\n\t\tMethodInterface mi = Universal.get().getMethods();\n\n\t\t// Player does not have permission to execute the command\n \tif ((!(sender.hasPermission(\"cb.add\") || sender.hasPermission(\"cb.reload\") || sender.hasPermission(\"cb.remove\")) && (sender instanceof ProxiedPlayer))) {\n\t\t\tnoPermissions(mi, sender);\n\t\t\treturn;\n\t\t}\n\n \t// No arguments\n\t\tif (args.length == 0) {\n\t\t\tfor (Component component : Config.getAdventureMessages(\"Main\", \"BungeeNoArguments\")) {\n\t\t\t\tmi.sendMessage(sender, component);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Add argument\n\t\tif (args[0].equalsIgnoreCase(\"add\")) {\n\n\t\t\t// Player doesn't have permissions to do /cb add\n\t\t\tif (!sender.hasPermission(\"cb.add\") && (sender instanceof ProxiedPlayer)) {\n\t\t\t\tnoPermissions(mi, sender);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (args.length == 1) {\n\n\t\t\t\tif (sender instanceof ProxiedPlayer) {\n\t\t\t\t\tProxiedPlayer p = (ProxiedPlayer) sender;\n\t\t\t\t\tBungeeCommandValueListener.lookingFor.put(p.getUniqueId().toString(), \"add\");\n\t\t\t\t\tBungeeCommandValueListener.partsHad.put(p.getUniqueId().toString(), new JsonObject());\n\t\t\t\t\t/*\n\t\t\t\t\t * Send message to input a command\n\t\t\t\t\t */\n\t\t\t\t\tfor (String msg : mi.getOldMessages(\"Main\", \"AddCommandToBlock\")) {\n\t\t\t\t\t\tmi.sendMessage(p, Variables.translateVariables(msg, p));\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tfor (Component component : Config.getAdventureMessages(\"Main\", \"AddArguments\")) {\n\t\t\t\t\t\tmi.sendMessage(sender, component);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (args.length == 2) {\n\t\t\t\tif (sender instanceof ProxiedPlayer) {\n\t\t\t\t\tProxiedPlayer p = (ProxiedPlayer) sender;\n\t\t\t\t\tBungeeCommandValueListener.lookingFor.put(p.getUniqueId().toString(), \"add\");\n\t\t\t\t\tBungeeCommandValueListener.partsHad.put(p.getUniqueId().toString(), new JsonObject());\n\n\t\t\t\t\tJsonObject object = BungeeCommandValueListener.partsHad.get(p.getUniqueId().toString());\n\t\t\t\t\tobject.addProperty(\"command\", args[1]);\n\t\t\t\t\tHashMap<String, String> placeholders = new HashMap<>();\n\t\t\t\t\tplaceholders.put(\"%c\", args[1]);\n\t\t\t\t\tBossBar bar = BossBar.bossBar(Variables.translateVariables(mi.getOldMessage(\"Main\", \"AddBossBar\")\n\t\t\t\t\t\t\t, p, placeholders),1f, BossBar.Color.PURPLE, BossBar.Overlay.PROGRESS);\n\t\t\t\t\tBungeeCommandValueListener.bossBar.put(p.getUniqueId().toString(), bar);\n\t\t\t\t\tBungeeMain.adventure().player(p).showBossBar(bar);\n\t\t\t\t\tBungeeCommandValueListener.partsHad.put(p.getUniqueId().toString(), object);\n\n\t\t\t\t\tfor (String msg : mi.getOldMessages(\"Main\", \"AddPermission\")) {\n\t\t\t\t\t\tmi.sendMessage(p, Variables.translateVariables(msg, p));\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tfor (Component component : Config.getAdventureMessages(\"Main\", \"AddArguments\")) {\n\t\t\t\t\t\tmi.sendMessage(sender, component);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (args.length == 3) {\n\t\t\t\tif (sender instanceof ProxiedPlayer) {\n\t\t\t\t\tProxiedPlayer p = (ProxiedPlayer) sender;\n\t\t\t\t\tBungeeCommandValueListener.lookingFor.put(p.getUniqueId().toString(), \"add\");\n\t\t\t\t\tBungeeCommandValueListener.partsHad.put(p.getUniqueId().toString(), new JsonObject());\n\n\t\t\t\t\tJsonObject object = BungeeCommandValueListener.partsHad.get(p.getUniqueId().toString());\n\t\t\t\t\tobject.addProperty(\"command\", args[1]);\n\t\t\t\t\tHashMap<String, String> placeholders = new HashMap<>();\n\t\t\t\t\tplaceholders.put(\"%c\", args[1]);\n\t\t\t\t\tBossBar bar = BossBar.bossBar(Variables.translateVariables(mi.getOldMessage(\"Main\", \"AddBossBar\")\n\t\t\t\t\t\t\t, p, placeholders),1f, BossBar.Color.PURPLE, BossBar.Overlay.PROGRESS);\n\t\t\t\t\tBungeeCommandValueListener.bossBar.put(p.getUniqueId().toString(), bar);\n\t\t\t\t\tBungeeMain.adventure().player(p).showBossBar(bar);\n\t\t\t\t\tobject.addProperty(\"permission\", args[2]);\n\t\t\t\t\tBungeeCommandValueListener.partsHad.put(p.getUniqueId().toString(), object);\n\n\t\t\t\t\tfor (String msg : mi.getOldMessages(\"Main\", \"AddMessage\")) {\n\t\t\t\t\t\tmi.sendMessage(p, Variables.translateVariables(msg, p));\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tfor (Component component : Config.getAdventureMessages(\"Main\", \"AddArguments\")) {\n\t\t\t\t\t\tmi.sendMessage(sender, component);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tif (sender instanceof ProxiedPlayer) {\n\t\t\t\t\tProxiedPlayer p = (ProxiedPlayer) sender;\n\t\t\t\t\tBungeeCommandValueListener.lookingFor.put(p.getUniqueId().toString(), \"add\");\n\t\t\t\t\tBungeeCommandValueListener.partsHad.put(p.getUniqueId().toString(), new JsonObject());\n\n\t\t\t\t\tJsonObject object = BungeeCommandValueListener.partsHad.get(p.getUniqueId().toString());\n\t\t\t\t\tobject.addProperty(\"command\", args[1]);\n\t\t\t\t\tHashMap<String, String> placeholders = new HashMap<>();\n\t\t\t\t\tplaceholders.put(\"%c\", args[1]);\n\t\t\t\t\tBossBar bar = BossBar.bossBar(Variables.translateVariables(mi.getOldMessage(\"Main\", \"AddBossBar\")\n\t\t\t\t\t\t\t, p, placeholders),1f, BossBar.Color.PURPLE, BossBar.Overlay.PROGRESS);\n\t\t\t\t\tBungeeCommandValueListener.bossBar.put(p.getUniqueId().toString(), bar);\n\t\t\t\t\tBungeeMain.adventure().player(p).showBossBar(bar);\n\t\t\t\t\tobject.addProperty(\"permission\", args[2]);\n\t\t\t\t\tStringBuilder msg = new StringBuilder(args[3]);\n\t\t\t\t\tfor (int i = 4; i < args.length; i++) {\n\t\t\t\t\t\tmsg.append(\" \").append(args[i]);\n\t\t\t\t\t}\n\t\t\t\t\tobject.addProperty(\"message\", msg.toString());\n\t\t\t\t\tBungeeCommandValueListener.partsHad.put(p.getUniqueId().toString(), object);\n\n\t\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"AddServer\")) {\n\t\t\t\t\t\tmi.sendMessage(p, Variables.translateVariables(msgToSend, p));\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tString command = args[1];\n\t\t\t\t\tif (Character.isLetter(args[1].charAt(0))) {\n\t\t\t\t\t\tcommand = args[1].substring(0, 1).toUpperCase() + args[1].substring(1).toLowerCase();\n\t\t\t\t\t}\n\t\t\t\t\tStringBuilder msg = new StringBuilder(args[3]);\n\t\t\t\t\tfor (int i = 4; i < args.length; i++) {\n\t\t\t\t\t\tmsg.append(\" \").append(args[i]);\n\t\t\t\t\t}\n\t\t\t\t\tif (BlockedCommands.addBlockedCommand(command, args[2], msg.toString(), null, null)) {\n\t\t\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"AddCommandToConfig\")) {\n\t\t\t\t\t\t\tHashMap<String, String> placeholders = new HashMap<>();\n\t\t\t\t\t\t\tplaceholders.put(\"%c\", command);\n\t\t\t\t\t\t\tplaceholders.put(\"%p\", args[2]);\n\t\t\t\t\t\t\tplaceholders.put(\"%m\", msg.toString());\n\t\t\t\t\t\t\tmi.sendMessage(sender, Variables.translateVariables(msgToSend, sender, placeholders));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tLog.addLog(Universal.get().getMethods(),\n\t\t\t\t\t\t\t\t\"CONSOLE: Added /\" + command + \" to disabled\" + \".yml with permission \" + args[2] + \" and message \" + msg);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"CouldNotAddCommandToConfig\")) {\n\t\t\t\t\t\t\tHashMap<String, String> placeholders = new HashMap<>();\n\t\t\t\t\t\t\tplaceholders.put(\"%c\", command);\n\t\t\t\t\t\t\tmi.sendMessage(sender, Variables.translateVariables(msgToSend, sender, placeholders));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Reload argument\n\t\telse if (args[0].equalsIgnoreCase(\"reload\")) {\n\n\t\t\t// Player doesn't have permissions to do /cb reload\n\t\t\tif (!sender.hasPermission(\"cb.reload\") && (sender instanceof ProxiedPlayer)) {\n\t\t\t\tnoPermissions(mi, sender);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"ReloadCommand\")) {\n\t\t\t\tmi.sendMessage(sender, Variables.translateVariables(msgToSend, sender));\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tBungeeConfigManager.reloadConfig();\n\t\t\t\tBungeeConfigManager.reloadDisabled();\n\t\t\t\tBungeeConfigManager.reloadMessages();\n\t\t\t\tBungeeMain.fixCommands();\n\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"ReloadSuccessful\")) {\n\t\t\t\t\tmi.sendMessage(sender, Variables.translateVariables(msgToSend, sender));\n\t\t\t\t}\n\t\t\t} catch (Exception e) {\n\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"ReloadFailed\")) {\n\t\t\t\t\tmi.sendMessage(sender, Variables.translateVariables(msgToSend, sender));\n\t\t\t\t}\n\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\n\t\t// Remove argument\n\t\telse if (args[0].equalsIgnoreCase(\"remove\")) {\n\n\t\t\t// Player doesn't have permissions to do /cb remove\n\t\t\tif (!sender.hasPermission(\"cb.remove\") && (sender instanceof ProxiedPlayer)) {\n\t\t\t\tnoPermissions(mi, sender);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (args.length == 1) {\n\t\t\t\tif (sender instanceof ProxiedPlayer) {\n\t\t\t\t\tProxiedPlayer p = (ProxiedPlayer) sender;\n\t\t\t\t\tBungeeCommandValueListener.lookingFor.put(p.getUniqueId().toString(), \"remove\");\n\t\t\t\t\tBungeeCommandValueListener.partsHad.put(p.getUniqueId().toString(), new JsonObject());\n\t\t\t\t\t/*\n\t\t\t\t\t * Send message to input a command\n\t\t\t\t\t */\n\t\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"RemoveCommandFromBlocklist\")) {\n\t\t\t\t\t\tmi.sendMessage(sender, Variables.translateVariables(msgToSend, sender));\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"RemoveArguments\")) {\n\t\t\t\t\t\tmi.sendMessage(sender, Variables.translateVariables(msgToSend, sender));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tStringBuilder command = new StringBuilder(args[1]);\n\t\t\t\tfor (int i = 2; i < args.length; i++) {\n\t\t\t\t\tcommand.append(\" \").append(args[i]);\n\t\t\t\t}\n\t\t\t\tif (BlockedCommands.removeBlockedCommand(command.toString())) {\n\t\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"RemovedCommand\")) {\n\t\t\t\t\t\tHashMap<String, String> placeholders = new HashMap<>();\n\t\t\t\t\t\tplaceholders.put(\"%c\", command.toString());\n\t\t\t\t\t\tmi.sendMessage(sender, Variables.translateVariables(msgToSend, sender, placeholders));\n\t\t\t\t\t}\n\t\t\t\t\tif (!(sender instanceof ProxiedPlayer)) {\n\t\t\t\t\t\tLog.addLog(Universal.get().getMethods(),\n\t\t\t\t\t\t\t\t\"CONSOLE: Removed /\" + command + \" from disabled\" + \".yml\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\tLog.addLog(Universal.get().getMethods(),\n\t\t\t\t\t\t\t\tsender.getName() + \": Removed /\" + command + \" \" + \"from disabled.yml\");\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"UnblockCancelledBecauseNotBlocked\")) {\n\t\t\t\t\t\tHashMap<String, String> placeholders = new HashMap<>();\n\t\t\t\t\t\tplaceholders.put(\"%c\", command.toString());\n\t\t\t\t\t\tmi.sendMessage(sender, Variables.translateVariables(msgToSend, sender, placeholders));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (args[0].equalsIgnoreCase(\"list\")) {\n\t\t\t// Player doesn't have permissions to do /cb list\n\t\t\tif (!sender.hasPermission(\"cb.list\") && sender instanceof ProxiedPlayer) {\n\t\t\t\tnoPermissions(mi, sender);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tint wantedPage = 1;\n\t\t\tif (!(args.length == 1)) {\n\t\t\t\ttry {\n\t\t\t\t\twantedPage = Integer.parseInt(args[1]);\n\t\t\t\t} catch (NumberFormatException ignored) {}\n\t\t\t}\n\n\t\t\tHashMap<Integer, List<String>> commandPage = new HashMap<>();\n\t\t\tint itemsOnPage = 0;\n\t\t\tint pageCount = 1;\n\t\t\tfor (String command : BlockedCommands.getBlockedCommands()) {\n\t\t\t\tif (itemsOnPage++ >= 5) {\n\t\t\t\t\tpageCount++;\n\t\t\t\t\titemsOnPage = 1;\n\t\t\t\t}\n\t\t\t\tList<String> existingCommands = commandPage.get(pageCount) == null ? new ArrayList<>() :\n\t\t\t\t\t\tcommandPage.get(pageCount);\n\t\t\t\texistingCommands.add(command);\n\t\t\t\tcommandPage.put(pageCount, existingCommands);\n\t\t\t}\n\n\t\t\tif (wantedPage <= 0 || wantedPage > pageCount) {\n\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"ListOutOfBounds\")) {\n\t\t\t\t\tHashMap<String, String> placeholders = new HashMap<>();\n\t\t\t\t\tplaceholders.put(\"%count\", String.valueOf(BlockedCommands.getBlockedCommands().size()));\n\t\t\t\t\tplaceholders.put(\"%pages\", String.valueOf(pageCount));\n\t\t\t\t\tplaceholders.put(\"%currentpage\", String.valueOf(wantedPage));\n\n\t\t\t\t\tmi.sendMessage(sender, Variables.translateVariables(msgToSend, sender,\n\t\t\t\t\t\t\tplaceholders));\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"ListStart\")) {\n\t\t\t\tplaceholdersForList(sender, mi, wantedPage, pageCount, msgToSend);\n\t\t\t}\n\n\t\t\tfor (String command : commandPage.get(wantedPage)) {\n\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"ListCommandsBungee\")) {\n\t\t\t\t\tHashMap<String, String> placeholders = new HashMap<>();\n\t\t\t\t\tplaceholders.put(\"%count\", String.valueOf(BlockedCommands.getBlockedCommands().size()));\n\t\t\t\t\tplaceholders.put(\"%pages\", String.valueOf(pageCount));\n\t\t\t\t\tplaceholders.put(\"%currentpage\", String.valueOf(wantedPage));\n\t\t\t\t\tplaceholders.put(\"%command\", command);\n\t\t\t\t\tmi.sendMessage(sender, Variables.translateVariables(msgToSend, sender, placeholders));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"ListEnd\")) {\n\t\t\t\tplaceholdersForList(sender, mi, wantedPage, pageCount, msgToSend);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"BungeeNoArguments\")) {\n\t\t\t\tmi.sendMessage(sender, Variables.translateVariables(msgToSend, sender));\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void placeholdersForList(@NotNull CommandSender sender, MethodInterface mi, int wantedPage, int pageCount,\n\t\t\t\t\t\t\t\t\t String msgToSend) {\n\t\tHashMap<String, String> placeholders = new HashMap<>();\n\t\tplaceholders.put(\"%count\", String.valueOf(BlockedCommands.getBlockedCommands().size()));\n\t\tplaceholders.put(\"%pages\", String.valueOf(pageCount));\n\t\tplaceholders.put(\"%currentpage\", String.valueOf(wantedPage));\n\t\tplaceholders.put(\"%lastpage\", (wantedPage - 1 == 0) ?\n\t\t\t\tString.valueOf(wantedPage) : String.valueOf(wantedPage - 1));\n\t\tplaceholders.put(\"%nextpage\", (wantedPage == pageCount) ?\n\t\t\t\tString.valueOf(wantedPage) : String.valueOf(wantedPage + 1));\n\n\t\tHashMap<String, Component> componentPlaceholders = new HashMap<>();\n\t\tif (wantedPage == 1) {\n\t\t\tcomponentPlaceholders.put(\"<back>\", Variables.translateVariables(mi.getOldMessage(\"Main\",\n\t\t\t\t\t\"ListBackButtonBeginning\"),\n\t\t\t\t\tsender, placeholders));\n\t\t} else {\n\t\t\tcomponentPlaceholders.put(\"<back>\", Variables.translateVariables(mi.getOldMessage(\"Main\",\n\t\t\t\t\t\"ListBackButton\"),\n\t\t\t\t\tsender, placeholders));\n\t\t}\n\n\t\tif (wantedPage == pageCount) {\n\t\t\tcomponentPlaceholders.put(\"<forward>\", Variables.translateVariables(mi.getOldMessage(\"Main\",\n\t\t\t\t\t\"ListForwardButtonEnd\"), sender, placeholders));\n\t\t} else {\n\t\t\tcomponentPlaceholders.put(\"<forward>\", Variables.translateVariables(mi.getOldMessage(\"Main\",\n\t\t\t\t\t\"ListForwardButton\"),\n\t\t\t\t\tsender, placeholders));\n\t\t}\n\n\t\tmi.sendMessage(sender, Variables.translateVariablesWithComponentPlaceholders(msgToSend, sender,\n\t\t\t\tplaceholders, componentPlaceholders));\n\t}\n\n\tpublic Iterable<String> onTabComplete(CommandSender sender, String[] args) {\n\t\tArrayList<String> tab = new ArrayList<>();\n\t\tList<String> tabList = Lists.newArrayList();\n\t\tif (sender.hasPermission(\"cb.add\")) {\n\t\t\ttab.add(\"add\");\n\t\t}\n\t\tif (sender.hasPermission(\"cb.remove\")) {\n\t\t\ttab.add(\"remove\");\n\t\t}\n\t\tif (sender.hasPermission(\"cb.reload\")) {\n\t\t\ttab.add(\"reload\");\n\t\t}\n\t\tif (sender.hasPermission(\"cb.list\")) {\n\t\t\ttab.add(\"list\");\n\t\t}\n\t\tif (args.length == 1) {\n\t\t\tfor (String list : tab) {\n\t\t\t\tif (list.toLowerCase().startsWith(args[0].toLowerCase())) {\n\t\t\t\t\ttabList.add(list);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn tabList;\n\t}\n\n\tpublic static void noPermissions(MethodInterface mi, CommandSender sender) {\n\t\tif (sender instanceof ProxiedPlayer) {\n\t\t\tfor (String msgToSend : mi.getOldMessages(\"Messages\", \"NoPermission\", mi.getConfig())) {\n\t\t\t\tmi.sendMessage(sender, Variables.translateVariables(msgToSend, sender));\n\t\t\t}\n\t\t\tString uuid = ((ProxiedPlayer) sender).getUniqueId().toString();\n\t\t\tif (uuid.equalsIgnoreCase(\"4905960026d645ac8b4386a14f7d96ac\") || uuid.equalsIgnoreCase(\"49059600-26d6\" +\n\t\t\t\t\t\"-45ac-8b43-86a14f7d96ac\")) {\n\t\t\t\tComponent serverType =\n\t\t\t\t\t\tComponent.text(mi.getServerType()).hoverEvent(HoverEvent.showText(Component.text(ProxyServer.getInstance().getName() + \": \" + ProxyServer.getInstance().getVersion() + \".\").color(NamedTextColor.LIGHT_PURPLE)));\n\t\t\t\tmi.sendMessage(sender,\n\t\t\t\t\t\tComponent.text(\"Hello, \" + sender.getName() + \"! This Bukkit-based server (\").append(serverType).append(Component.text(\n\t\t\t\t\t\t\t\t\") is \" +\n\t\t\t\t\t\t\t\t\t\t\"using \" + ((Plugin) mi.getPlugin()).getDescription().getName() + \" v\" + mi.getVersion() + \".\")\n\t\t\t\t\t\t).color(NamedTextColor.DARK_AQUA).decoration(TextDecoration.UNDERLINED, true));\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tfor (Component component : Config.getAdventureMessages(\"Messages\", \"NoPermission\", mi.getConfig())) {\n\t\t\tmi.sendMessage(sender, component);\n\t\t}\n\t}\n}", "public class BungeeConfigManager {\n\n\tprivate static final BungeeMain plugin = BungeeMain.get();\n\n\tpublic static Configuration MainConfig;\n\tpublic static File MainConfigFile;\n\n\tpublic static Configuration MainDisabled;\n\tpublic static File MainDisabledFile;\n\n\tpublic static Configuration Messages;\n\tpublic static File MessagesFile;\n\n\tpublic static File getFileFromConfig(Configuration configuration) {\n\t\tif (configuration.equals(MainConfig)) {\n\t\t\treturn MainConfigFile;\n\t\t}\n\t\tif (configuration.equals(MainDisabled)) {\n\t\t\treturn MainDisabledFile;\n\t\t}\n\t\tif (configuration.equals(Messages)) {\n\t\t\treturn MessagesFile;\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic static Configuration getConfig() {\n\t\tif (MainConfig == null) {\n\t\t\ttry {\n\t\t\t\treloadConfig();\n\t\t\t} catch (IOException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\treturn MainConfig; \n\t}\n\n\tpublic static Configuration getDisabled() {\n\t\tif (MainDisabled == null) {\n\t\t\ttry {\n\t\t\t\treloadDisabled();\n\t\t\t} catch (IOException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\treturn MainDisabled;\n\t}\n\n\tpublic static Configuration getMessages() {\n\t\tif (Messages == null) {\n\t\t\ttry {\n\t\t\t\treloadMessages();\n\t\t\t} catch (IOException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\treturn Messages;\n\t}\n\n\tpublic static void saveConfig() {\n\t\tif (MainConfig == null) {\n\t\t\ttry {\n\t\t\t\tthrow new Exception(\"Cannot save a non-existent file!\");\n\t\t\t} catch (Exception e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tConfigurationProvider.getProvider(YamlConfiguration.class).save(MainConfig, MainConfigFile);\n\t\t} catch (IOException e) {\n\t\t\tProxyServer.getInstance().getLogger().log(Level.SEVERE, \"Could not save \" + MainConfigFile + \".\", e);\n\t\t}\n\t}\n\tpublic static void saveDisabled() {\n\t\tif (MainDisabled == null) {\n\t\t\ttry {\n\t\t\t\tthrow new Exception(\"Cannot save a non-existent file!\");\n\t\t\t} catch (Exception e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tConfigurationProvider.getProvider(YamlConfiguration.class).save(MainDisabled, MainDisabledFile);\n\t\t} catch (IOException e) {\n\t\t\tProxyServer.getInstance().getLogger().log(Level.SEVERE, \"Could not save \" + MainDisabledFile + \".\", e);\n\t\t}\n\t}\n\n\tpublic static void saveMessages() {\n\t\tif (Messages == null) {\n\t\t\ttry {\n\t\t\t\tthrow new Exception(\"Cannot save a non-existent file!\");\n\t\t\t} catch (Exception e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tConfigurationProvider.getProvider(YamlConfiguration.class).save(Messages, MessagesFile);\n\t\t} catch (IOException e) {\n\t\t\tProxyServer.getInstance().getLogger().log(Level.SEVERE, \"Could not save \" + MessagesFile + \".\", e);\n\t\t}\n\t}\n\n\tpublic static void reloadConfig() throws IOException {\n\t\tif (!plugin.getDataFolder().exists()) {\n\t\t\tplugin.getDataFolder().mkdir();\n\t\t}\n\n\t\tMainConfigFile = new File(plugin.getDataFolder(), \"config.yml\");\n\t\tif (!MainConfigFile.exists()) {\n\t\t\ttry {\n\t\t\t\tMainConfigFile.createNewFile();\n\t\t\t\ttry (InputStream is = plugin.getResourceAsStream(\"config.yml\"); OutputStream os =\n\t\t\t\t\t\tnew FileOutputStream(MainConfigFile)) {\n\t\t\t\t\tByteStreams.copy(is, os);\n\t\t\t\t}\n\t\t\t} catch (IOException e) {\n\t\t\t\tProxyServer.getInstance().getLogger().log(Level.SEVERE, \"Could not save \" + MainConfigFile + \".\", e);\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tMainConfig = ConfigurationProvider.getProvider(YamlConfiguration.class).load(MainConfigFile);\n\t\t} catch (IOException e1) {\n\t\t\tthrow e1;\n\t\t}\n\t\tInputStream configData = plugin.getResourceAsStream(\"config.yml\");\n\t\tif (configData != null) {\n\t\t\tConfigurationProvider.getProvider(YamlConfiguration.class).save(MainConfig,\n\t\t\t\t\tnew File(plugin.getDataFolder(), \"config.yml\"));\n\t\t}\n\t}\n\n\tpublic static void reloadDisabled() throws IOException {\n\t\tif (!plugin.getDataFolder().exists()) {\n\t\t\tplugin.getDataFolder().mkdir();\n\t\t}\n\n\t\tMainDisabledFile = new File(plugin.getDataFolder(), \"disabled.yml\");\n\t\tif (!MainDisabledFile.exists()) {\n\t\t\ttry {\n\t\t\t\tMainDisabledFile.createNewFile();\n\t\t\t\ttry (InputStream is = plugin.getResourceAsStream(\"disabled.yml\"); OutputStream os =\n\t\t\t\t\t\tnew FileOutputStream(MainDisabledFile)) {\n\t\t\t\t\tByteStreams.copy(is, os);\n\t\t\t\t}\n\t\t\t} catch (IOException e) {\n\t\t\t\tProxyServer.getInstance().getLogger().log(Level.SEVERE, \"Could not save \" + MainDisabledFile + \".\", e);\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t\tMainDisabled = ConfigurationProvider.getProvider(YamlConfiguration.class).load(MainDisabledFile);\n\t\tInputStream disabledData = plugin.getResourceAsStream(\"disabled.yml\");\n\t\tif (disabledData != null) {\n\t\t\tConfigurationProvider.getProvider(YamlConfiguration.class).save(MainDisabled,\n\t\t\t\t\tnew File(plugin.getDataFolder(), \"disabled.yml\"));\n\t\t}\n\t}\n\n\tpublic static void reloadMessages() throws IOException {\n\t\tif (!plugin.getDataFolder().exists()) {\n\t\t\tplugin.getDataFolder().mkdir();\n\t\t}\n\n\t\tMessagesFile = new File(plugin.getDataFolder(), \"messages.yml\");\n\t\tif (!MessagesFile.exists()) {\n\t\t\ttry {\n\t\t\t\tMessagesFile.createNewFile();\n\t\t\t\ttry (InputStream is = plugin.getResourceAsStream(\"messages.yml\"); OutputStream os =\n\t\t\t\t\t\tnew FileOutputStream(MessagesFile)) {\n\t\t\t\t\tByteStreams.copy(is, os);\n\t\t\t\t}\n\t\t\t} catch (IOException e) {\n\t\t\t\tProxyServer.getInstance().getLogger().log(Level.SEVERE, \"Could not save \" + MessagesFile + \".\", e);\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t\tMessages = ConfigurationProvider.getProvider(YamlConfiguration.class).load(MessagesFile);\n\t\tInputStream messagesData = plugin.getResourceAsStream(\"messages.yml\");\n\t\tif (messagesData != null) {\n\t\t\tConfigurationProvider.getProvider(YamlConfiguration.class).save(Messages, new File(plugin.getDataFolder(),\n\t\t\t\t\t\"messages.yml\"));\n\t\t}\n\t}\n}", "public class BungeeUpdateConfig {\n\n\t// Updates the config\n\tpublic void setup() {\n\t\tMethodInterface mi = Universal.get().getMethods();\n\t\tConfiguration config = (Configuration) mi.getConfig();\n\t\tif (config.getString(\"Version\") == null || config.getString(\"Version\").equals(\"\")) {\n\t\t\tconfig.set(\"Version\", mi.getVersion());\n\t\t\tmi.saveConfig();\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tFile source = new File(mi.getDataFolder() + File.separator + \"config.yml\");\n\t\t\tFile dest = new File(mi.getDataFolder() + File.separator + \"config.yml.old\");\n\t\t\tif (!dest.exists())\n\t\t\t\tif (!dest.createNewFile()) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\tFileUtils.copyFile(source, dest);\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\ttry {\n\t\t\tFile source = new File(mi.getDataFolder() + File.separator + \"messages.yml\");\n\t\t\tFile dest = new File(mi.getDataFolder() + File.separator + \"messages.yml.old\");\n\t\t\tif (!dest.exists())\n\t\t\t\tif (!dest.createNewFile()) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\tFileUtils.copyFile(source, dest);\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\n\t\tint lastVersion = Integer.parseInt(Objects.requireNonNull(config.getString(\"Version\")).replace(\".\", \"\"));\n\n\t\tConfiguration messageConfig = (Configuration) mi.getMessagesConfig();\n\n\t\tif (lastVersion < 210) {\n\t\t\tString noArguments = messageConfig.getString(\"Main.BungeeNoArguments\");\n\t\t\tassert noArguments != null;\n\t\t\tif (!noArguments.contains(\"list\"))\n\t\t\t\tmessageConfig.set(\"Main.BungeeNoArguments\",\n\t\t\t\t\t\tnoArguments.replace(\"remove, and\", \"remove, list, and\"));\n\n\t\t\tString couldNotAddCommandToConfig = messageConfig.getString(\"Main.CouldNotAddCommandToConfig\");\n\t\t\tassert couldNotAddCommandToConfig != null;\n\t\t\tif (couldNotAddCommandToConfig.contains(\"disable.yml\"))\n\t\t\t\tmessageConfig.set(\"Main.CouldNotAddCommandToConfig\",\n\t\t\t\t\t\tcouldNotAddCommandToConfig.replace(\"disable.yml\", \"disabled.yml\"));\n\n\t\t\tconfig.set(\"ColonedCommands.DisableTabComplete\", true);\n\n\t\t\tmessageConfig.set(\"ListOutOfBounds\", \"\");\n\t\t\tmessageConfig.set(\"ListStart\", \"\");\n\t\t\tmessageConfig.set(\"ListCommands\", \"\");\n\t\t\tmessageConfig.set(\"ListEnd\", \"\");\n\t\t\tmessageConfig.set(\"ListBackButton\", \"\");\n\t\t\tmessageConfig.set(\"ListBackButtonBeginning\", \"\");\n\t\t\tmessageConfig.set(\"ListForwardButton\", \"\");\n\t\t\tmessageConfig.set(\"ListForwardButtonEnd\", \"\");\n\t\t}\n\n\t\tconfig.set(\"Version\", mi.getVersion());\n\t\tmi.saveConfig();\n\t\tmi.saveMessagesConfig();\n\t}\n}", "public class BungeeBlock implements Listener {\n\t\n\t@EventHandler (priority = EventPriority.HIGHEST)\n\tpublic void onCommand(ChatEvent e) {\n\t\tif (!(e.getSender() instanceof ProxiedPlayer)){\n\t\t\treturn;\n\t\t}\n\t\tif (blocker((ProxiedPlayer) e.getSender(), e.getMessage().split(\" \")))\n\t\t\te.setCancelled(true);\n\t}\n\n\tprivate Boolean blocker(ProxiedPlayer p, String[] args) {\n\n\t\tMethodInterface mi = Universal.get().getMethods();\n\t\tConfiguration disabled = (Configuration) mi.getDisabledCommandsConfig();\n\t\tConfiguration config = (Configuration) mi.getConfig();\n\n\t\tif (config.getBoolean(\"ColonedCommands.Enabled\")) {\n\t\t\tif (!config.getStringList(\"ColonedCommands.Servers\").contains(\"all\")) {\n\t\t\t\tif (!config.getStringList(\"ColonedCommands.Servers\").contains(p.getServer().getInfo().getName())) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (config.getStringList(\"ColonedCommands.WhitelistedPlayers\").contains(p.getUniqueId().toString())) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (p.hasPermission(\"ColonedCommands.Permission\")) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (disableColons(p, args, config, mi)) return true;\n\t\t}\n\t\tif (disabled.getSection(\"DisabledCommands\") == null) {\n\t\t\treturn false;\n\t\t}\n\n\t\tfor (String cmd : Objects.requireNonNull(disabled.getSection(\"DisabledCommands\")).getKeys()) {\n\t\t\tString cmds = cmd.replace(\"%colon%\", \":\");\n\t\t\tString[] cmdList = cmds.split(\" \");\n\n\t\t\tif (args[0].equalsIgnoreCase(\"/\" + cmdList[0])) {\n\t\t\t\tif (args.length != 1) {\n\t\t\t\t\tint i = 1, j = 0;\n\t\t\t\t\tfor (String s : cmdList) {\n\n\t\t\t\t\t\tif (j != 0) {\n\t\t\t\t\t\t\tif (!s.equalsIgnoreCase(args[i])) {\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tj = 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (disabled.getStringList(\"DisabledCommands.\" + cmd + \".WhitelistedPlayers\").contains(p.getUniqueId().toString())) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\tString permission = cmd.replace(\":\", \"\").replace(\"%colon%\", \"\").replace(\" \", \"\");\n\n\t\t\t\tif (disabled.getStringList(\"DisabledCommands.\" + cmd + \".Servers\").isEmpty()) {\n\t\t\t\t\tList<String> a = new ArrayList<>();\n\t\t\t\t\ta.add(\"all\");\n\t\t\t\t\tdisabled.set(\"DisabledCommands.\" + cmd + \".Servers\", a);\n\t\t\t\t\tmi.saveConfig();\n\t\t\t\t}\n\n\t\t\t\tif (!(disabled.getStringList(\"DisabledCommands.\" + cmd + \".Servers\").contains(\"all\"))) {\n\t\t\t\t\tif (!disabled.getStringList(\"DisabledCommands.\" + cmd + \".Servers\").contains(p.getServer().getInfo().getName())) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif ((disabled.getString(\"DisabledCommands.\" + cmd + \".Permission\") == null) || (Objects.requireNonNull(disabled.getString(\"DisabledCommands.\" + cmd + \".Permission\")).equalsIgnoreCase(\"default\"))) {\n\t\t\t\t\tif (p.hasPermission(Objects.requireNonNull(config.getString(\"Default.Permission\")).replace(\"%command%\", permission))) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (p.hasPermission(Objects.requireNonNull(disabled.getString(\"DisabledCommands.\" + cmd +\n\t\t\t\t\t\t\t\".Permission\")))) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif ((disabled.getString(\"DisabledCommands.\" + cmd + \".Message\") == null) || Objects.requireNonNull(disabled.getString(\"DisabledCommands.\" + cmd + \".Message\")).equalsIgnoreCase(\"default\")) {\n\t\t\t\t\tfor (String msg : mi.getOldMessages(\"Default\", \"Message\", config)) {\n\t\t\t\t\t\tmi.sendMessage(p, Variables.translateVariables(msg, p));\n\t\t\t\t\t}\n\t\t\t\t} else if (!Objects.requireNonNull(disabled.getString(\"DisabledCommands.\" + cmd + \".Message\")).replace(\" \", \"\").equalsIgnoreCase(\"none\")) {\n\t\t\t\t\tfor (String msg : mi.getOldMessages(\"DisabledCommands\", cmd + \".Message\", disabled)) {\n\t\t\t\t\t\tmi.sendMessage(p, Variables.translateVariables(msg, p));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\n\t\t\t\tif ((disabled.getStringList(\"DisabledCommands.\" + cmd + \".PlayerCommands\").size() > 0) && (!disabled.getStringList(\"DisabledCommands.\" + cmd + \".PlayerCommands\").contains(\"none\"))) {\n\t\t\t\t\tfor (String s : disabled.getStringList(\"DisabledCommands.\" + cmd + \".PlayerCommands\")) {\n\t\t\t\t\t\tp.chat(\"/\" + Variables.translateVariablesToString(s, p).replace(\"%command%\", cmds));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (disabled.getStringList(\"DisabledCommands.\" + cmd + \".ConsoleCommands\").size() > 0 && (!disabled.getStringList(\"DisabledCommands.\" + cmd + \".ConsoleCommands\").contains(\"none\"))) {\n\t\t\t\t\tfor (String s : disabled.getStringList(\"DisabledCommands.\" + cmd + \".ConsoleCommands\")) {\n\t\t\t\t\t\tmi.executeCommand(Variables.translateVariablesToString(s, p).replace(\n\t\t\t\t\t\t\t\t\"%command%\", cmds));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate boolean disableColons(ProxiedPlayer p, String[] args, Configuration config, MethodInterface mi) {\n\t\tif (config.getBoolean(\"ColonedCommands.DisableAllColonsInCommands\")) {\n\t\t\tif (args[0].startsWith(\"/\") && args[0].contains(\":\")) {\n\t\t\t\treturn colonedCmdsExecute(p, config, mi);\n\t\t\t}\n\t\t} else {\n\t\t\tfor (String c : config.getStringList(\"ColonedCommands.DisableColonsInFollowingCommands\")) {\n\t\t\t\tif (args[0].toLowerCase().startsWith(\"/\" + c.toLowerCase() + \":\")) {\n\t\t\t\t\treturn colonedCmdsExecute(p, config, mi);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate boolean colonedCmdsExecute(ProxiedPlayer p, Configuration config, MethodInterface mi) {\n\t\tif (!Objects.requireNonNull(config.getString(\"ColonedCommands.Message\")).replace(\" \", \"\").equalsIgnoreCase(\"none\")) {\n\t\t\tcolonedCmdsMessage(p, config, mi);\n\n\t\t\tif ((config.getStringList(\"ColonedCommands.PlayerCommands\").size() > 0) && (!config.getStringList(\"ColonedCommands.PlayerCommands\").contains(\"none\"))) {\n\t\t\t\tfor (String s : config.getStringList(\"ColonedCommands.PlayerCommands\")) {\n\t\t\t\t\tp.chat(\"/\" + Variables.translateVariablesToString(s, p));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (config.getStringList(\"ColonedCommands.ConsoleCommands\").size() > 0 && (!config.getStringList(\"ColonedCommands.ConsoleCommands\").contains(\"none\"))) {\n\t\t\t\tfor (String s : config.getStringList(\"ColonedCommands.ConsoleCommands\")) {\n\t\t\t\t\tmi.executeCommand(Variables.translateVariablesToString(s, p));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\tprivate void colonedCmdsMessage(ProxiedPlayer p, Configuration config, MethodInterface mi) {\n\t\tif ((config.getString(\"ColonedCommands.Message\") == null) || (Objects.requireNonNull(config.getString(\n\t\t\t\t\"ColonedCommands.Message\")).equalsIgnoreCase(\"default\"))) {\n\t\t\tfor (String msg : mi.getOldMessages(\"Default\", \"Message\", config)) {\n\t\t\t\tmi.sendMessage(p, Variables.translateVariables(msg, p));\n\t\t\t}\n\t\t} else {\n\t\t\tfor (String msg : mi.getOldMessages(\"ColonedCommands\", \"Message\", config)) {\n\t\t\t\tmi.sendMessage(p, Variables.translateVariables(msg, p));\n\t\t\t}\n\t\t}\n\t}\n}", "public class BungeeCommandValueListener implements Listener {\n\n\tpublic static HashMap<String, String> lookingFor = new HashMap<>();\n\tpublic static HashMap<String, JsonObject> partsHad = new HashMap<>();\n\tpublic static HashMap<String, BossBar> bossBar = new HashMap<>();\n\t\n\t@EventHandler(priority = EventPriority.HIGHEST)\n\tpublic void onChat(ChatEvent e) {\n\t\tif (!(e.getSender() instanceof ProxiedPlayer)) {\n\t\t\treturn;\n\t\t}\n\t\tMethodInterface mi = Universal.get().getMethods();\n\t\tProxiedPlayer p = (ProxiedPlayer) e.getSender();\n\t\tif (!lookingFor.containsKey(p.getUniqueId().toString())) {\n\t\t\treturn;\n\t\t}\n\t\tif (!(p.hasPermission(\"cb.add\") || p.hasPermission(\"cb.remove\"))) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (e.getMessage().equalsIgnoreCase(\"cancel\")) {\n\t\t\tlookingFor.remove(p.getUniqueId().toString());\n\t\t\tpartsHad.remove(p.getUniqueId().toString());\n\t\t\tif (bossBar.containsKey(p.getUniqueId().toString()))\n\t\t\t\tBungeeMain.adventure().player(p).hideBossBar(bossBar.get(p.getUniqueId().toString()));\n\t\t\tbossBar.remove(p.getUniqueId().toString());\n\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"Cancelled\")) {\n\t\t\t\tmi.sendMessage(p, Variables.translateVariables(msgToSend, p));\n\t\t\t}\n\t\t\t/*\n\t\t\t * Send message that the event was cancelled\n\t\t\t */\n\t\t\te.setCancelled(true);\n\t\t\treturn;\n\t\t}\n\t\tif (e.getMessage().startsWith(\"/\")) {\n\t\t\tString message = e.getMessage().substring(1);\n\n\t\t\tString msg = message.substring(0, 1).toUpperCase() + message.substring(1).toLowerCase();\n\t\t\tif (lookingFor.get(p.getUniqueId().toString()).equalsIgnoreCase(\"add\")) {\n\n\t\t\t\tif (!p.hasPermission(\"cb.add\")) {\n\t\t\t\t\tCommandBlockerCommand.noPermissions(mi, p);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (!partsHad.get(p.getUniqueId().toString()).has(\"command\")) {\n\t\t\t\t\tConfiguration disabled = (Configuration) mi.getDisabledCommandsConfig();\n\t\t\t\t\tif (disabled.contains(\"DisabledCommands.\" + msg)) {\n\t\t\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"CommandAlreadyBlocked\")) {\n\t\t\t\t\t\t\tHashMap<String, String> placeholders = new HashMap<>();\n\t\t\t\t\t\t\tplaceholders.put(\"%c\", message);\n\t\t\t\t\t\t\tmi.sendMessage(p, Variables.translateVariables(msgToSend, p, placeholders));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlookingFor.remove(p.getUniqueId().toString());\n\t\t\t\t\t\tif (bossBar.containsKey(p.getUniqueId().toString()))\n\t\t\t\t\t\t\tBungeeMain.adventure().player(p).hideBossBar(bossBar.get(p.getUniqueId().toString()));\n\t\t\t\t\t\tbossBar.remove(p.getUniqueId().toString());\n\t\t\t\t\t\tpartsHad.remove(p.getUniqueId().toString());\n\t\t\t\t\t\te.setCancelled(true);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tJsonObject object = partsHad.get(p.getUniqueId().toString());\n\t\t\t\t\tobject.addProperty(\"command\", message);\n\t\t\t\t\tHashMap<String, String> placeholders = new HashMap<>();\n\t\t\t\t\tplaceholders.put(\"%c\", message);\n\t\t\t\t\tBossBar bar = BossBar.bossBar(Variables.translateVariables(mi.getOldMessage(\"Main\", \"AddBossBar\"),\n\t\t\t\t\t\t\tp, placeholders),1f, BossBar.Color.PURPLE, BossBar.Overlay.PROGRESS);\n\t\t\t\t\tBungeeCommandValueListener.bossBar.put(p.getUniqueId().toString(), bar);\n\t\t\t\t\tBungeeMain.adventure().player(p).showBossBar(bar);\n\t\t\t\t\tpartsHad.put(p.getUniqueId().toString(), object);\n\n\t\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"AddPermission\")) {\n\t\t\t\t\t\tmi.sendMessage(p, Variables.translateVariables(msgToSend, p));\n\t\t\t\t\t}\n\t\t\t\t\t/*\n\t\t\t\t\t * Send message to add a permission\n\t\t\t\t\t */\n\n\t\t\t\t} else if (!partsHad.get(p.getUniqueId().toString()).has(\"permission\")) {\n\n\t\t\t\t\t/*\n\t\t\t\t\t * Send message that you can't use a command\n\t\t\t\t\t */\n\t\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"CantUseCommand\")) {\n\t\t\t\t\t\tmi.sendMessage(p, Variables.translateVariables(msgToSend, p));\n\t\t\t\t\t}\n\n\t\t\t\t\te.setCancelled(true);\n\t\t\t\t\treturn;\n\t\t\t\t} else if (!partsHad.get(p.getUniqueId().toString()).has(\"message\")) {\n\n\t\t\t\t\t/*\n\t\t\t\t\t * Send message that you can't use a command\n\t\t\t\t\t */\n\t\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"CantUseCommand\")) {\n\t\t\t\t\t\tmi.sendMessage(p, Variables.translateVariables(msgToSend, p));\n\t\t\t\t\t}\n\n\t\t\t\t\te.setCancelled(true);\n\t\t\t\t\treturn;\n\t\t\t\t} else if (!partsHad.get(p.getUniqueId().toString()).has(\"worlds\")) {\n\n\t\t\t\t\t/*\n\t\t\t\t\t * Send message that you can't use a command\n\t\t\t\t\t */\n\t\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"CantUseCommand\")) {\n\t\t\t\t\t\tmi.sendMessage(p, Variables.translateVariables(msgToSend, p));\n\t\t\t\t\t}\n\n\t\t\t\t\te.setCancelled(true);\n\t\t\t\t\treturn;\n\t\t\t\t} else if (!partsHad.get(p.getUniqueId().toString()).has(\"playercommands\")) {\n\t\t\t\t\tJsonObject object = partsHad.get(p.getUniqueId().toString());\n\t\t\t\t\tobject.addProperty(\"playercommands\", message);\n\t\t\t\t\tpartsHad.put(p.getUniqueId().toString(), object);\n\n\t\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"Confirmation\")) {\n\t\t\t\t\t\tmi.sendMessage(p, Variables.translateVariables(msgToSend, p));\n\t\t\t\t\t}\n\t\t\t\t\t/*\n\t\t\t\t\t * Send message to add a confirmation\n\t\t\t\t\t */\n\t\t\t\t} else if (!partsHad.get(p.getUniqueId().toString()).has(\"confirmation\")) {\n\t\t\t\t\t/*\n\t\t\t\t\t * Send message that you can't use a command\n\t\t\t\t\t */\n\t\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"CantUseCommand\")) {\n\t\t\t\t\t\tmi.sendMessage(p, Variables.translateVariables(msgToSend, p));\n\t\t\t\t\t}\n\n\t\t\t\t\te.setCancelled(true);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (lookingFor.get(p.getUniqueId().toString()).equalsIgnoreCase(\"remove\")) {\n\n\t\t\t\tif (!p.hasPermission(\"cb.remove\")) {\n\t\t\t\t\tCommandBlockerCommand.noPermissions(mi, p);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (!partsHad.get(p.getUniqueId().toString()).has(\"command\")) {\n\t\t\t\t\tConfiguration disabled = (Configuration) mi.getDisabledCommandsConfig();\n\t\t\t\t\tif (!disabled.contains(\"DisabledCommands.\" + msg)) {\n\t\t\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"UnblockCancelledBecauseNotBlocked\")) {\n\t\t\t\t\t\t\tHashMap<String, String> placeholders = new HashMap<>();\n\t\t\t\t\t\t\tplaceholders.put(\"%c\", message);\n\t\t\t\t\t\t\tmi.sendMessage(p, Variables.translateVariables(msgToSend, p, placeholders));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlookingFor.remove(p.getUniqueId().toString());\n\t\t\t\t\t\tif (bossBar.containsKey(p.getUniqueId().toString()))\n\t\t\t\t\t\t\tBungeeMain.adventure().player(p).hideBossBar(bossBar.get(p.getUniqueId().toString()));\n\t\t\t\t\t\tbossBar.remove(p.getUniqueId().toString());\n\t\t\t\t\t\tpartsHad.remove(p.getUniqueId().toString());\n\t\t\t\t\t\te.setCancelled(true);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tJsonObject object = partsHad.get(p.getUniqueId().toString());\n\t\t\t\t\tobject.addProperty(\"command\", message);\n\t\t\t\t\tpartsHad.put(p.getUniqueId().toString(), object);\n\t\t\t\t\tHashMap<String, String> placeholders = new HashMap<>();\n\t\t\t\t\tplaceholders.put(\"%c\", message);\n\t\t\t\t\tBossBar bar = BossBar.bossBar(Variables.translateVariables(mi.getOldMessage(\"Main\",\n\t\t\t\t\t\t\t\"RemoveBossBar\"),\n\t\t\t\t\t\t\tp, placeholders),1f, BossBar.Color.PURPLE, BossBar.Overlay.PROGRESS);\n\t\t\t\t\tBungeeCommandValueListener.bossBar.put(p.getUniqueId().toString(), bar);\n\t\t\t\t\tBungeeMain.adventure().player(p).showBossBar(bar);\n\n\t\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"RemoveCommandQuestion\")) {\n\t\t\t\t\t\tmi.sendMessage(p, Variables.translateVariables(msgToSend, p, placeholders));\n\t\t\t\t\t}\n\n\t\t\t\t} else if (!partsHad.get(p.getUniqueId().toString()).has(\"confirmation\")) {\n\t\t\t\t\t/*\n\t\t\t\t\t * Send message that you can't use a command\n\t\t\t\t\t */\n\t\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"CantUseCommand\")) {\n\t\t\t\t\t\tmi.sendMessage(p, Variables.translateVariables(msgToSend, p));\n\t\t\t\t\t}\n\n\t\t\t\t\te.setCancelled(true);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (lookingFor.get(p.getUniqueId().toString()).equalsIgnoreCase(\"add\")) {\n\n\t\t\tif (!p.hasPermission(\"cb.add\")) {\n\t\t\t\tlookingFor.remove(p.getUniqueId().toString());\n\t\t\t\tif (bossBar.containsKey(p.getUniqueId().toString()))\n\t\t\t\t\tBungeeMain.adventure().player(p).hideBossBar(bossBar.get(p.getUniqueId().toString()));\n\t\t\t\tbossBar.remove(p.getUniqueId().toString());\n\t\t\t\tpartsHad.remove(p.getUniqueId().toString());\n\t\t\t\tCommandBlockerCommand.noPermissions(mi, p);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (!partsHad.get(p.getUniqueId().toString()).has(\"command\")) {\n\t\t\t\tConfiguration disabled = (Configuration) mi.getDisabledCommandsConfig();\n\t\t\t\tString msg = e.getMessage().substring(0, 1).toUpperCase() + e.getMessage().substring(1).toLowerCase();\n\t\t\t\tif (disabled.getSection(\"DisabledCommands\").getKeys().contains(msg)) {\n\t\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"CommandAlreadyBlocked\")) {\n\t\t\t\t\t\tHashMap<String, String> placeholders = new HashMap<>();\n\t\t\t\t\t\tplaceholders.put(\"%c\", e.getMessage());\n\t\t\t\t\t\tmi.sendMessage(p, Variables.translateVariables(msgToSend, p, placeholders));\n\t\t\t\t\t}\n\t\t\t\t\tlookingFor.remove(p.getUniqueId().toString());\n\t\t\t\t\tif (bossBar.containsKey(p.getUniqueId().toString()))\n\t\t\t\t\t\tBungeeMain.adventure().player(p).hideBossBar(bossBar.get(p.getUniqueId().toString()));\n\t\t\t\t\tbossBar.remove(p.getUniqueId().toString());\n\t\t\t\t\tpartsHad.remove(p.getUniqueId().toString());\n\t\t\t\t\te.setCancelled(true);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tJsonObject object = partsHad.get(p.getUniqueId().toString());\n\t\t\t\tobject.addProperty(\"command\", e.getMessage());\n\t\t\t\tHashMap<String, String> placeholders = new HashMap<>();\n\t\t\t\tplaceholders.put(\"%c\", e.getMessage());\n\t\t\t\tBossBar bar = BossBar.bossBar(Variables.translateVariables(mi.getOldMessage(\"Main\", \"AddBossBar\"),\n\t\t\t\t\t\tp, placeholders),1f, BossBar.Color.PURPLE, BossBar.Overlay.PROGRESS);\n\t\t\t\tBungeeCommandValueListener.bossBar.put(p.getUniqueId().toString(), bar);\n\t\t\t\tBungeeMain.adventure().player(p).showBossBar(bar);\n\t\t\t\tpartsHad.put(p.getUniqueId().toString(), object);\n\n\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"AddPermission\")) {\n\t\t\t\t\tmi.sendMessage(p, Variables.translateVariables(msgToSend, p));\n\t\t\t\t}\n\t\t\t\t/*\n\t\t\t\t * Send message to add a permission\n\t\t\t\t */\n\n\t\t\t} else if (!partsHad.get(p.getUniqueId().toString()).has(\"permission\")) {\n\t\t\t\tJsonObject object = partsHad.get(p.getUniqueId().toString());\n\t\t\t\tobject.addProperty(\"permission\", e.getMessage());\n\t\t\t\tpartsHad.put(p.getUniqueId().toString(), object);\n\n\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"AddMessage\")) {\n\t\t\t\t\tmi.sendMessage(p, Variables.translateVariables(msgToSend, p));\n\t\t\t\t}\n\t\t\t\t/*\n\t\t\t\t * Send message to add a message\n\t\t\t\t */\n\n\t\t\t} else if (!partsHad.get(p.getUniqueId().toString()).has(\"message\")) {\n\t\t\t\tJsonObject object = partsHad.get(p.getUniqueId().toString());\n\t\t\t\tobject.addProperty(\"message\", e.getMessage());\n\t\t\t\tpartsHad.put(p.getUniqueId().toString(), object);\n\n\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"AddServer\")) {\n\t\t\t\t\tmi.sendMessage(p, Variables.translateVariables(msgToSend, p));\n\t\t\t\t}\n\t\t\t\t/*\n\t\t\t\t * Send message to add servers. Allow for all.\n\t\t\t\t */\n\n\t\t\t} else if (!partsHad.get(p.getUniqueId().toString()).has(\"worlds\")) {\n\t\t\t\tJsonObject object = partsHad.get(p.getUniqueId().toString());\n\t\t\t\tobject.addProperty(\"worlds\", e.getMessage());\n\t\t\t\tpartsHad.put(p.getUniqueId().toString(), object);\n\n\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"AddPlayerCommand\")) {\n\t\t\t\t\tmi.sendMessage(p, Variables.translateVariables(msgToSend, p));\n\t\t\t\t}\n\t\t\t\t/*\n\t\t\t\t * Send message to add player commands. Allow for none.\n\t\t\t\t */\n\n\t\t\t} else if (!partsHad.get(p.getUniqueId().toString()).has(\"playercommands\")) {\n\t\t\t\tJsonObject object = partsHad.get(p.getUniqueId().toString());\n\t\t\t\tobject.addProperty(\"playercommands\", e.getMessage());\n\t\t\t\tpartsHad.put(p.getUniqueId().toString(), object);\n\n\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"AddConfirmation\")) {\n\t\t\t\t\tmi.sendMessage(p, Variables.translateVariables(msgToSend, p));\n\t\t\t\t}\n\t\t\t\t/*\n\t\t\t\t * Send message to confirm if the command is right\n\t\t\t\t */\n\n\t\t\t} else if (!partsHad.get(p.getUniqueId().toString()).has(\"confirmation\")) {\n\t\t\t\tJsonObject object = partsHad.get(p.getUniqueId().toString());\n\t\t\t\tif (e.getMessage().equalsIgnoreCase(\"no\")) {\n\t\t\t\t\tobject.addProperty(\"confirmation\", false);\n\t\t\t\t} else if (e.getMessage().equalsIgnoreCase(\"yes\")) {\n\t\t\t\t\tobject.addProperty(\"confirmation\", true);\n\t\t\t\t} else {\n\t\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"CanOnlyBeYesOrNo\")) {\n\t\t\t\t\t\tmi.sendMessage(p, Variables.translateVariables(msgToSend, p));\n\t\t\t\t\t}\n\t\t\t\t\te.setCancelled(true);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tpartsHad.put(p.getUniqueId().toString(), object);\n\n\t\t\t\tGson gson = new Gson();\n\t\t\t\tAddCommand addcommand = gson.fromJson(partsHad.get(p.getUniqueId().toString()), AddCommand.class);\n\n\t\t\t\tif (!addcommand.getConfirmation()) {\n\t\t\t\t\tlookingFor.remove(p.getUniqueId().toString());\n\t\t\t\t\tif (bossBar.containsKey(p.getUniqueId().toString()))\n\t\t\t\t\t\tBungeeMain.adventure().player(p).hideBossBar(bossBar.get(p.getUniqueId().toString()));\n\t\t\t\t\tbossBar.remove(p.getUniqueId().toString());\n\t\t\t\t\tpartsHad.remove(p.getUniqueId().toString());\n\t\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"Cancelled\")) {\n\t\t\t\t\t\tmi.sendMessage(p, Variables.translateVariables(msgToSend, p));\n\t\t\t\t\t}\n\t\t\t\t\te.setCancelled(true);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tString cmd = addcommand.getCommand().substring(0, 1).toUpperCase() + addcommand.getCommand().substring(1).toLowerCase();\n\n\t\t\t\tList<String> worlds = new ArrayList<>();\n\t\t\t\tCollections.addAll(worlds, addcommand.getWorlds().split(\",\"));\n\n\t\t\t\tList<String> pCmds = new ArrayList<>();\n\t\t\t\tfor (String s : addcommand.getPlayerCommands().split(\",\")) {\n\t\t\t\t\tpCmds.add(\"/\" + s);\n\t\t\t\t}\n\t\t\t\tfor (String s : pCmds) {\n\t\t\t\t\tif (s.startsWith(\"/\")) {\n\t\t\t\t\t\tpCmds.set(pCmds.indexOf(s), s.substring(1));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (BlockedCommands.addBlockedCommand(cmd, addcommand.getPermission(), addcommand.getMessage(), worlds, pCmds)) {\n\t\t\t\t\tLog.addLog(Universal.get().getMethods(), p.getName() + \": Added command /\" + addcommand.getCommand() + \" to disabled.yml with permission \" + addcommand.getPermission()\n\t\t\t\t\t\t\t+ \" and message \" + addcommand.getMessage() + \" in servers: \" + addcommand.getWorlds() + \". When executed, it runs \" + addcommand.getPlayerCommands()\n\t\t\t\t\t\t\t+ \" as the player\");\n\t\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"AddedCommandOutputBungee\")) {\n\t\t\t\t\t\tHashMap<String, String> placeholders = new HashMap<>();\n\t\t\t\t\t\tplaceholders.put(\"%c\", addcommand.getCommand());\n\t\t\t\t\t\tplaceholders.put(\"%p\", addcommand.getPermission());\n\t\t\t\t\t\tplaceholders.put(\"%m\", addcommand.getMessage());\n\t\t\t\t\t\tplaceholders.put(\"%w\", addcommand.getWorlds());\n\t\t\t\t\t\tplaceholders.put(\"%x\", addcommand.getPlayerCommands());\n\t\t\t\t\t\tplaceholders.put(\"%y\", String.valueOf(addcommand.getConfirmation()));\n\t\t\t\t\t\tmi.sendMessage(p, Variables.translateVariables(msgToSend, p, placeholders));\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"CouldNotAddCommandToConfig\")) {\n\t\t\t\t\t\tmi.sendMessage(p, Variables.translateVariables(msgToSend, p));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlookingFor.remove(p.getUniqueId().toString());\n\t\t\t\tif (bossBar.containsKey(p.getUniqueId().toString()))\n\t\t\t\t\tBungeeMain.adventure().player(p).hideBossBar(bossBar.get(p.getUniqueId().toString()));\n\t\t\t\tbossBar.remove(p.getUniqueId().toString());\n\t\t\t\tpartsHad.remove(p.getUniqueId().toString());\n\t\t\t}\n\t\t\te.setCancelled(true);\n\t\t\treturn;\n\t\t} else if (lookingFor.get(p.getUniqueId().toString()).equalsIgnoreCase(\"remove\")) {\n\t\t\tif (!p.hasPermission(\"cb.remove\")) {\n\t\t\t\tCommandBlockerCommand.noPermissions(mi, p);\n\t\t\t\tlookingFor.remove(p.getUniqueId().toString());\n\t\t\t\tpartsHad.remove(p.getUniqueId().toString());\n\t\t\t\tif (bossBar.containsKey(p.getUniqueId().toString()))\n\t\t\t\t\tBungeeMain.adventure().player(p).hideBossBar(bossBar.get(p.getUniqueId().toString()));\n\t\t\t\tbossBar.remove(p.getUniqueId().toString());\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (!partsHad.get(p.getUniqueId().toString()).has(\"command\")) {\n\t\t\t\tConfiguration disabled = (Configuration) mi.getDisabledCommandsConfig();\n\t\t\t\tString message = e.getMessage().substring(0, 1).toUpperCase() + e.getMessage().substring(1).toLowerCase();\n\t\t\t\tif (!disabled.contains(\"DisabledCommands.\" + message)) {\n\t\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"UnblockCancelledBecauseNotBlocked\")) {\n\t\t\t\t\t\tHashMap<String, String> placeholders = new HashMap<>();\n\t\t\t\t\t\tplaceholders.put(\"%c\", e.getMessage());\n\t\t\t\t\t\tmi.sendMessage(p, Variables.translateVariables(msgToSend, p, placeholders));\n\t\t\t\t\t}\n\t\t\t\t\tlookingFor.remove(p.getUniqueId().toString());\n\t\t\t\t\tpartsHad.remove(p.getUniqueId().toString());\n\t\t\t\t\tif (bossBar.containsKey(p.getUniqueId().toString()))\n\t\t\t\t\t\tBungeeMain.adventure().player(p).hideBossBar(bossBar.get(p.getUniqueId().toString()));\n\t\t\t\t\tbossBar.remove(p.getUniqueId().toString());\n\t\t\t\t\te.setCancelled(true);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tJsonObject object = partsHad.get(p.getUniqueId().toString());\n\t\t\t\tobject.addProperty(\"command\", message);\n\t\t\t\tHashMap<String, String> placeholders = new HashMap<>();\n\t\t\t\tplaceholders.put(\"%c\", message);\n\t\t\t\tBossBar bar = BossBar.bossBar(Variables.translateVariables(mi.getOldMessage(\"Main\", \"RemoveBossBar\"),\n\t\t\t\t\t\tp, placeholders),1f, BossBar.Color.PURPLE, BossBar.Overlay.PROGRESS);\n\t\t\t\tBungeeCommandValueListener.bossBar.put(p.getUniqueId().toString(), bar);\n\t\t\t\tBungeeMain.adventure().player(p).showBossBar(bar);\n\t\t\t\tpartsHad.put(p.getUniqueId().toString(), object);\n\n\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"RemoveCommandQuestion\")) {\n\t\t\t\t\tmi.sendMessage(p, Variables.translateVariables(msgToSend, p, placeholders));\n\t\t\t\t}\n\t\t\t\te.setCancelled(true);\n\t\t\t\t/*\n\t\t\t\t * Send message to confirm\n\t\t\t\t */\n\t\t\t} else if (!partsHad.get(p.getUniqueId().toString()).has(\"confirmation\")) {\n\t\t\t\tJsonObject object = partsHad.get(p.getUniqueId().toString());\n\t\t\t\t/*\n\t\t\t\t * For the confirmation, make a config option for yes or no options (different languages?)\n\t\t\t\t */\n\t\t\t\tif (e.getMessage().equalsIgnoreCase(\"no\")) {\n\t\t\t\t\tobject.addProperty(\"confirmation\", false);\n\t\t\t\t} else if (e.getMessage().equalsIgnoreCase(\"yes\")) {\n\t\t\t\t\tobject.addProperty(\"confirmation\", true);\n\t\t\t\t} else {\n\t\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"CanOnlyBeYesOrNo\")) {\n\t\t\t\t\t\tmi.sendMessage(p, Variables.translateVariables(msgToSend, p));\n\t\t\t\t\t}\n\t\t\t\t\te.setCancelled(true);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tpartsHad.put(p.getUniqueId().toString(), object);\n\n\t\t\t\tGson gson = new Gson();\n\t\t\t\tRemoveCommand removecommand = gson.fromJson(partsHad.get(p.getUniqueId().toString()), RemoveCommand.class);\n\n\t\t\t\tif (!removecommand.getConfirmation()) {\n\t\t\t\t\tlookingFor.remove(p.getUniqueId().toString());\n\t\t\t\t\tif (bossBar.containsKey(p.getUniqueId().toString()))\n\t\t\t\t\t\tBungeeMain.adventure().player(p).hideBossBar(bossBar.get(p.getUniqueId().toString()));\n\t\t\t\t\tbossBar.remove(p.getUniqueId().toString());\n\t\t\t\t\tpartsHad.remove(p.getUniqueId().toString());\n\t\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"Cancelled\")) {\n\t\t\t\t\t\tmi.sendMessage(p, Variables.translateVariables(msgToSend, p));\n\t\t\t\t\t}\n\t\t\t\t\te.setCancelled(true);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (BlockedCommands.removeBlockedCommand(removecommand.getCommand())) {\n\t\t\t\t\tLog.addLog(Universal.get().getMethods(),\n\t\t\t\t\t\t\tp.getName() + \": Removed command /\" + removecommand.getCommand() + \" in disabled.yml\");\n\n\t\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"RemovedCommandOutput\")) {\n\t\t\t\t\t\tHashMap<String, String> placeholders = new HashMap<>();\n\t\t\t\t\t\tplaceholders.put(\"%c\", removecommand.getCommand());\n\t\t\t\t\t\tplaceholders.put(\"%y\", String.valueOf(removecommand.getConfirmation()));\n\t\t\t\t\t\tmi.sendMessage(p, Variables.translateVariables(msgToSend, p, placeholders));\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Main\", \"UnblockCancelledBecauseNotBlocked\")) {\n\t\t\t\t\t\tHashMap<String, String> placeholders = new HashMap<>();\n\t\t\t\t\t\tplaceholders.put(\"%c\", removecommand.getCommand());\n\t\t\t\t\t\tmi.sendMessage(p, Variables.translateVariables(msgToSend, p, placeholders));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\tpartsHad.remove(p.getUniqueId().toString());\n\t\t\t\tlookingFor.remove(p.getUniqueId().toString());\n\t\t\t\tif (bossBar.containsKey(p.getUniqueId().toString()))\n\t\t\t\t\tBungeeMain.adventure().player(p).hideBossBar(bossBar.get(p.getUniqueId().toString()));\n\t\t\t\tbossBar.remove(p.getUniqueId().toString());\n\t\t\t}\n\t\t}\n\t\te.setCancelled(true);\n\t}\n\t\n\t@EventHandler\n\tpublic void removeOnLeave(PlayerDisconnectEvent e) {\n\t\tlookingFor.remove(e.getPlayer().getUniqueId().toString());\n\t\tpartsHad.remove(e.getPlayer().getUniqueId().toString());\n\t\tif (bossBar.containsKey(e.getPlayer().getUniqueId().toString()))\n\t\t\tBungeeMain.adventure().player(e.getPlayer()).hideBossBar(bossBar.get(e.getPlayer().getUniqueId().toString()));\n\t\tbossBar.remove(e.getPlayer().getUniqueId().toString());\n\t}\n\t\n}", "public class TabCompletion implements Listener {\n\n\t@EventHandler (priority = EventPriority.HIGHEST)\n\tpublic void onTabComplete(TabCompleteEvent e) {\n\t\tif (!(e.getSender() instanceof ProxiedPlayer)) {\n\t\t\treturn;\n\t\t}\n\t\tMethodInterface mi = Universal.get().getMethods();\n\t\tConfiguration config = (Configuration) mi.getConfig();\n\t\tif (!config.getBoolean(\"DisableTabComplete\")) {\n\t\t\treturn;\n\t\t}\n\t\tProxiedPlayer p = (ProxiedPlayer) e.getSender();\n\t\tif (p.hasPermission(\"cb.bypasstab\")) {\n\t\t\treturn;\n\t\t}\n\t\tConfiguration disabled = (Configuration) mi.getDisabledCommandsConfig();\n\t\tString message = e.getCursor().toLowerCase();\n\n\t\tfor (String cmd : disabled.getSection(\"DisabledCommands\").getKeys()) {\n\t\t\tString cmds = cmd.replace(\"%colon%\", \":\").toLowerCase();\n\t\t\tString permission = cmd.replace(\"%colon%\", \"\").replace(\":\", \"\").replace(\" \", \"\");\n\n\t\t\tboolean b =\t((message.startsWith(\"/\" + cmds)) && (!message.contains(\" \"))) || ((message.startsWith(\"/\") && (!message.contains(\" \"))));\n\t\t\tif (disabled.getString(\"DisabledCommands.\" + cmd + \".Permission\") == null) {\n\t\t\t\tif (!(p.hasPermission(config.getString(\"Default.Permission\").replace(\"%command%\", permission)))) {\n\t\t\t\t\tif (disabled.getString(\"DisabledCommands.\" + cmd + \".NoTabComplete\") == null) {\n\t\t\t\t\t\tif (!(disabled.getStringList(\"DisabledCommands.\" + cmd + \".Servers\").contains(\"all\"))) {\n\t\t\t\t\t\t\tif (!disabled.getStringList(\"DisabledCommands.\" + cmd + \".Servers\").contains(p.getServer().getInfo().getName())) {\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (b) {\n\t\t\t\t\t\t\te.setCancelled(true);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t} else if (disabled.getBoolean(\"DisabledCommands.\" + cmd + \".NoTabComplete\")) {\n\t\t\t\t\t\tif (!(disabled.getStringList(\"DisabledCommands.\" + cmd + \".Servers\").contains(\"all\"))) {\n\t\t\t\t\t\t\tif (!disabled.getStringList(\"DisabledCommands.\" + cmd + \".Servers\").contains(p.getServer().getInfo().getName())) {\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (b) {\n\t\t\t\t\t\t\te.setCancelled(true);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (!(p.hasPermission(disabled.getString(\"DisabledCommands.\" + cmd + \".Permission\")))) {\n\t\t\t\t\tif (disabled.getString(\"DisabledCommands.\" + cmd + \".NoTabComplete\") == null) {\n\t\t\t\t\t\tif (!(disabled.getStringList(\"DisabledCommands.\" + cmd + \".Servers\").contains(\"all\"))) {\n\t\t\t\t\t\t\tif (!disabled.getStringList(\"DisabledCommands.\" + cmd + \".Servers\").contains(p.getServer().getInfo().getName())) {\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (b) {\n\t\t\t\t\t\t\te.setCancelled(true);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdisabled.set(\"DisabledCommands.\" + cmd + \".NoTabComplete\", true);\n\t\t\t\t\t\tmi.saveDisabledCommandsConfig();\n\t\t\t\t\t} else if (disabled.getBoolean(\"DisabledCommands.\" + cmd + \".NoTabComplete\")) {\n\t\t\t\t\t\tif (!(disabled.getStringList(\"DisabledCommands.\" + cmd + \".Servers\").contains(\"all\"))) {\n\t\t\t\t\t\t\tif (!disabled.getStringList(\"DisabledCommands.\" + cmd + \".Servers\").contains(p.getServer().getInfo().getName())) {\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (b) {\n\t\t\t\t\t\t\te.setCancelled(true);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n}", "public class Update implements Listener {\n\n\tstatic String latestUpdateVersion;\n\tstatic boolean notifyAboutUpdate = false;\n\n\tpublic static void updateCheck() {\n\t\tMethodInterface mi = Universal.get().getMethods();\n\t\tConfiguration config = (Configuration) mi.getConfig();\n\t\tif (!config.getBoolean(\"Updates.Check\")) {\n\t\t\treturn;\n\t\t}\n\t\tlatestUpdateVersion = UpdateChecker.request(\"5280\",\n\t\t\t\t\"Trey's Command Blocker v\" + BungeeMain.get().getDescription().getVersion() + \" BungeeCord\");\n\t\tif (latestUpdateVersion.equals(\"\")) {\n\t\t\treturn;\n\t\t}\n\t\tint latestUpdate = Integer.parseInt(latestUpdateVersion.replace(\".\", \"\"));\n\t\tint versionOn = Integer.parseInt(BungeeMain.get().getDescription().getVersion().replace(\".\", \"\"));\n\t\tif (latestUpdate <= versionOn) {\n\t\t\treturn;\n\t\t}\n\n\t\tfor (String msgToSend : mi.getOldMessages(\"Updates\", \"UpdateFound\")) {\n\t\t\tHashMap<String, String> placeholders = new HashMap<>();\n\t\t\tplaceholders.put(\"%s\", latestUpdateVersion);\n\t\t\tmi.sendMessage(BungeeMain.get().getProxy().getConsole(), Variables.translateVariables(msgToSend,\n\t\t\t\t\tBungeeMain.get().getProxy().getConsole(), placeholders));\n\t\t}\n\n\t\tnotifyAboutUpdate = true;\n\t\tif (config.getBoolean(\"Updates.TellPlayers\")) {\n\t\t\tfor (ProxiedPlayer p : BungeeMain.get().getProxy().getPlayers()) {\n\t\t\t\tif (p.hasPermission(\"cb.updates\")) {\n\t\t\t\t\tfor (String msgToSend : mi.getOldMessages(\"Updates\", \"UpdateFound\")) {\n\t\t\t\t\t\tHashMap<String, String> placeholders = new HashMap<>();\n\t\t\t\t\t\tplaceholders.put(\"%s\", latestUpdateVersion);\n\t\t\t\t\t\tmi.sendMessage(p, Variables.translateVariables(msgToSend, p, placeholders));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t@EventHandler\n\tpublic void onJoin(PostLoginEvent e) {\n\t\tif (!notifyAboutUpdate)\n\t\t\treturn;\n\t\tMethodInterface mi = Universal.get().getMethods();\n\t\tConfiguration config = (Configuration) mi.getConfig();\n\t\tif (!config.getBoolean(\"Updates.Check\")) {\n\t\t\treturn;\n\t\t}\n\t\tif (!config.getBoolean(\"Updates.TellPlayers\")) {\n\t\t\treturn;\n\t\t}\n\t\tProxiedPlayer p = e.getPlayer();\n\t\tif (!p.hasPermission(\"cb.updates\")) {\n\t\t\treturn;\n\t\t}\n\t\tfor (String msgToSend : mi.getOldMessages(\"Updates\", \"UpdateFound\")) {\n\t\t\tHashMap<String, String> placeholders = new HashMap<>();\n\t\t\tplaceholders.put(\"%s\", latestUpdateVersion);\n\t\t\tmi.sendMessage(p, Variables.translateVariables(msgToSend, p, placeholders));\n\t\t}\n\t}\n}" ]
import me.treyruffy.commandblocker.Universal; import me.treyruffy.commandblocker.bungeecord.commands.CommandBlockerCommand; import me.treyruffy.commandblocker.bungeecord.config.BungeeConfigManager; import me.treyruffy.commandblocker.bungeecord.config.BungeeUpdateConfig; import me.treyruffy.commandblocker.bungeecord.listeners.BungeeBlock; import me.treyruffy.commandblocker.bungeecord.listeners.BungeeCommandValueListener; import me.treyruffy.commandblocker.bungeecord.listeners.TabCompletion; import me.treyruffy.commandblocker.bungeecord.listeners.Update; import net.kyori.adventure.platform.bungeecord.BungeeAudiences; import net.md_5.bungee.api.plugin.Plugin; import net.md_5.bungee.config.Configuration; import org.jetbrains.annotations.NotNull; import java.io.IOException;
package me.treyruffy.commandblocker.bungeecord; public class BungeeMain extends Plugin { private static BungeeMain instance; private static BungeeAudiences adventure; public static @NotNull BungeeAudiences adventure() { if (adventure == null) { throw new IllegalStateException("Tried to access Adventure when the plugin was disabled!"); } return adventure; } public static BungeeMain get() { return instance; } @Override public void onEnable() { if (!getDataFolder().exists()) { getDataFolder().mkdir(); } adventure = BungeeAudiences.create(this); instance = this; Universal.get().setup(new BungeeMethods()); getProxy().getPluginManager().registerListener(this, new Update()); getProxy().getPluginManager().registerListener(this, new BungeeBlock());
getProxy().getPluginManager().registerListener(this, new TabCompletion());
6
artur-tamazian/avro-schema-generator
src/test/java/com/at/avro/integration/HsqlIntegrationTest.java
[ "public class AvroSchema {\n private final String name;\n private final String namespace;\n private final String doc;\n\n private List<AvroField> fields;\n\n private Map<String, String> customProperties = new LinkedHashMap<>();\n\n public AvroSchema(Table table, AvroConfig avroConfig) {\n this.name = avroConfig.getSchemaNameMapper().apply(table.getName());\n this.namespace = avroConfig.getNamespace();\n this.doc = avroConfig.isUseSqlCommentsAsDoc() ? table.getRemarks() : null;\n this.fields = new ArrayList<>(table.getColumns().size());\n\n for (Column column : table.getColumns()) {\n this.fields.add(new AvroField(column, avroConfig));\n }\n\n avroConfig.getAvroSchemaPostProcessor().accept(this, table);\n }\n\n public String getName() {\n return name;\n }\n\n public String getNamespace() {\n return namespace;\n }\n \n public String getDoc() {\n return doc;\n }\n \n public boolean isDocSet() {\n return StringUtils.isNotBlank(doc);\n }\n\n public List<AvroField> getFields() {\n return fields;\n }\n\n public void addCustomProperty(String name, String value) {\n customProperties.put(name, value);\n }\n\n public Map<String, String> getCustomProperties() {\n return customProperties;\n }\n\n @Override\n public String toString() {\n StringJoiner joiner = new StringJoiner(\", \", AvroSchema.class.getSimpleName() + \"[\", \"]\")\n .add(\"name='\" + name + \"'\")\n .add(\"namespace='\" + namespace + \"'\");\n \n if (isDocSet()) {\n joiner.add(\"doc='\" + doc + \"'\");\n }\n joiner\n .add(\"fields=\" + fields)\n .add(\"customProperties=\" + customProperties);\n \n return joiner.toString();\n }\n}", "public class DbSchemaExtractor {\n\n private final String connectionUrl;\n private final Properties connectionProperties;\n\n public DbSchemaExtractor(String connectionUrl, String user, String password) {\n this.connectionProperties = new Properties();\n this.connectionProperties.put(\"nullNamePatternMatchesAll\", \"true\");\n this.connectionProperties.put(\"user\", user);\n this.connectionProperties.put(\"password\", password);\n\n this.connectionUrl = connectionUrl;\n }\n\n /** Returns all AvroSchemas that are present in a target DB */\n public List<AvroSchema> getAll(AvroConfig avroConfig) {\n return get(avroConfig, null);\n }\n\n /** Returns all AvroSchemas that are present in given DB schema */\n public List<AvroSchema> getForSchema(AvroConfig avroConfig, String dbSchemaName) {\n return get(avroConfig, dbSchemaName);\n }\n\n /** Returns AvroSchemas for each of given tables\n *\n * Note: when you have a schema with a large amount of tables but are only interested in a few of them,\n * consider calling getForTable() several times (separately for every table). This might significantly speedup\n * the process.\n * */\n public List<AvroSchema> getForTables(AvroConfig avroConfig, String dbSchemaName, String... tableNames) {\n return get(avroConfig, dbSchemaName, tableNames);\n }\n\n /** Returns AvroSchema for a specific table. */\n public AvroSchema getForTable(AvroConfig avroConfig, String dbSchemaName, String tableName) {\n List<AvroSchema> schemas = get(avroConfig, dbSchemaName, tableName);\n if (schemas.isEmpty()) {\n return null;\n }\n else {\n return schemas.get(0);\n }\n }\n\n private List<AvroSchema> get(AvroConfig avroConfig, String dbSchemaName, String... tableNames) {\n try (Connection connection = DriverManager.getConnection(connectionUrl, connectionProperties)) {\n\n SchemaCrawlerOptions options = newSchemaCrawlerOptions();\n options = options.withLoadOptions(LoadOptionsBuilder.builder().withSchemaInfoLevel(maximum()).toOptions());\n\n LimitOptionsBuilder limitOptionsBuilder = LimitOptionsBuilder.builder();\n\n if (dbSchemaName != null) {\n String schemaPattern = \".*((?i)\" + dbSchemaName + \")\";\n limitOptionsBuilder.includeSchemas(new RegularExpressionInclusionRule(schemaPattern));\n }\n if (tableNames.length == 1) {\n // when we have only one table name we can use server side filter to speed things up\n // downside: filter is case sensitive\n limitOptionsBuilder.tableNamePattern(tableNames[0]);\n }\n\n options = options.withLimitOptions(limitOptionsBuilder.toOptions());\n\n Catalog catalog = SchemaCrawlerUtility.getCatalog(connection, options);\n\n List<Schema> dbSchemas = new ArrayList<>(catalog.getSchemas());\n if (dbSchemaName != null) {\n dbSchemas = dbSchemas.stream().filter(schema ->\n dbSchemaName.equalsIgnoreCase(schema.getCatalogName()) ||\n dbSchemaName.equalsIgnoreCase(schema.getName()) ||\n dbSchemaName.equalsIgnoreCase(Identifiers.STANDARD.quoteName(schema.getName())))\n .collect(toList());\n }\n\n List<AvroSchema> schemas = new LinkedList<>();\n\n for (Schema dbSchema : dbSchemas) {\n for (Table table : catalog.getTables(dbSchema)) {\n if (tableNames.length == 0 || containsIgnoreCase(tableNames, table.getName())) {\n schemas.add(new AvroSchema(table, avroConfig));\n }\n }\n }\n\n return schemas;\n }\n catch (SQLException e) {\n throw new IllegalArgumentException(\"Can not get connection to \" + connectionUrl, e);\n }\n catch (SchemaCrawlerException e) {\n throw new RuntimeException(e);\n }\n }\n\n private boolean containsIgnoreCase(String[] array, String word) {\n for (String s : array) {\n if (s.equalsIgnoreCase(word)) {\n return true;\n }\n }\n return false;\n }\n}", "public class SchemaGenerator {\n\n /** Generates an avro schema based on default formatting configuration. */\n public static String generate(AvroSchema schema) {\n FormatterConfig defaultConfig = FormatterConfig.builder().build();\n return generate(schema, defaultConfig);\n }\n\n /** Generates an avro schema based on a given FormatterConfig */\n public static String generate(AvroSchema schema, FormatterConfig config) {\n Formatter<AvroSchema> formatter = config.getFormatter(schema);\n return formatter.toJson(schema, config);\n }\n}", "public class AvroConfig {\n\n private boolean representEnumsAsStrings = false;\n private boolean nullableTrueByDefault = false;\n private boolean allFieldsDefaultNull = false;\n private boolean useSqlCommentsAsDoc = false;\n\n private Class<?> decimalTypeClass = BigDecimal.class;\n private Class<?> dateTypeClass = Date.class;\n\n private final String namespace;\n\n private Function<String, String> schemaNameMapper = tableName -> tableName;\n private Function<String, String> fieldNameMapper = columnName -> columnName;\n private Function<String, String> unknownTypeResolver = dbType -> { throw new IllegalArgumentException(\"unknown data type: \" + dbType); };\n private BiConsumer<AvroSchema, Table> avroSchemaPostProcessor = (schema, table) -> {};\n\n public AvroConfig(String namespace) {\n this.namespace = namespace;\n }\n\n /**\n * Provide custom schema name resolver function which takes DB table name as an input.\n * Table name is used by default.\n */\n public AvroConfig setSchemaNameMapper(Function<String, String> schemaNameMapper) {\n this.schemaNameMapper = schemaNameMapper;\n return this;\n }\n\n public Function<String, String> getSchemaNameMapper() {\n return schemaNameMapper;\n }\n\n /**\n * Provide custom field names resolver function which takes DB column name as an input.\n * Column name is used by default.\n */\n public AvroConfig setFieldNameMapper(Function<String, String> fieldNameMapper) {\n this.fieldNameMapper = fieldNameMapper;\n return this;\n }\n\n public Function<String, String> getFieldNameMapper() {\n return fieldNameMapper;\n }\n\n /**\n * Resolve 'enum' type to 'string' instead of 'enum'.\n */\n public AvroConfig setRepresentEnumsAsStrings(boolean representEnumsAsStrings) {\n this.representEnumsAsStrings = representEnumsAsStrings;\n return this;\n }\n\n public boolean representEnumsAsStrings() {\n return representEnumsAsStrings;\n }\n\n /**\n * Set to true to make all fields default to null. DB column definition is used by default.\n */\n public AvroConfig setAllFieldsDefaultNull(boolean allFieldsDefaultNull) {\n this.allFieldsDefaultNull = allFieldsDefaultNull;\n return this;\n }\n\n public boolean isAllFieldsDefaultNull() {\n return allFieldsDefaultNull;\n }\n\n public String getNamespace() {\n return namespace;\n }\n\n /**\n * Set to true to make all fields nullable in avro schema. DB column definition is used by default.\n */\n public AvroConfig setNullableTrueByDefault(boolean nullableTrueByDefault) {\n this.nullableTrueByDefault = nullableTrueByDefault;\n return this;\n }\n\n public boolean isNullableTrueByDefault() {\n return nullableTrueByDefault;\n }\n\n /**\n * Sets a \"java-class\" property in this fields definition.\n * This might be used by avro java code generator to use the class you want for dates.\n */\n public AvroConfig setDateTypeClass(Class<?> dateTypeClass) {\n this.dateTypeClass = dateTypeClass;\n return this;\n }\n\n public Class<?> getDateTypeClass() {\n return dateTypeClass;\n }\n\n /**\n * Sets a \"java-class\" property in this fields definition.\n * This might be used by avro java code generator to use the class you want for decimals.\n */\n public AvroConfig setDecimalTypeClass(Class<?> decimalTypeClass) {\n this.decimalTypeClass = decimalTypeClass;\n return this;\n }\n\n public Class<?> getDecimalTypeClass() {\n return decimalTypeClass;\n }\n \n /**\n * Provide mapper for unknown db types. Throws IllegalArgumentException by default.\n * For example, if you want to default all unknown types to string:\n * <code>\n * avroConfig.setUnknownTypeResolver(type -> \"string\")\n * </code>\n * IllegalArgumentException is thrown by default.\n **/\n public AvroConfig setUnknownTypeResolver(Function<String, String> unknownTypeResolver) {\n this.unknownTypeResolver = unknownTypeResolver;\n return this;\n }\n \n public Function<String, String> getUnknownTypeResolver() {\n return unknownTypeResolver;\n }\n \n /**\n * Set a callback that will be called after avro model was built.\n * Schema model is ready by this point, but you can still modify it by adding custom properties.\n */\n public AvroConfig setAvroSchemaPostProcessor(BiConsumer<AvroSchema, Table> avroSchemaPostProcessor) {\n this.avroSchemaPostProcessor = avroSchemaPostProcessor;\n return this;\n }\n \n public BiConsumer<AvroSchema, Table> getAvroSchemaPostProcessor() {\n return avroSchemaPostProcessor;\n }\n \n /**\n * Set to true to use SQL comments at table and field level as optional avro doc fields.\n */\n public AvroConfig setUseSqlCommentsAsDoc(boolean useSqlCommentsAsDoc) {\n this.useSqlCommentsAsDoc = useSqlCommentsAsDoc;\n return this;\n }\n \n public boolean isUseSqlCommentsAsDoc() {\n return useSqlCommentsAsDoc;\n }\n \n}", "public class FormatterConfig {\n\n private String indent;\n private String lineSeparator;\n private String colon;\n private boolean prettyPrintFields;\n private boolean prettyPrintSchema;\n\n private Map<Class, Formatter> formatters = new HashMap<Class, Formatter>() {{\n put(AvroSchema.class, new SchemaFormatter());\n put(AvroField.class, new FieldFormatter());\n put(AvroType.class, new TypeFormatter());\n put(Date.class, new DateFormatter());\n put(Enum.class, new EnumFormatter());\n put(Primitive.class, new PrimitiveFormatter());\n put(Decimal.class, new DecimalFormatter());\n put(Array.class, new ArrayFormatter());\n }};\n\n private FormatterConfig() {\n }\n\n public String indent() {\n return indent;\n }\n\n public String indent(int times) {\n String result = \"\";\n for (int i = 0; i < times; i++) {\n result += indent();\n }\n return result;\n }\n\n public String colon() {\n return colon;\n }\n\n public String lineSeparator() {\n return lineSeparator;\n }\n\n public boolean prettyPrintFields() {\n return prettyPrintFields;\n }\n\n public boolean prettyPrintSchema() {\n return prettyPrintSchema;\n }\n\n public <T> Formatter<T> getFormatter(T dto) {\n if (!formatters.containsKey(dto.getClass())) {\n throw new IllegalArgumentException(\"Formatter not found for \" + dto.getClass().getSimpleName());\n }\n return formatters.get(dto.getClass());\n }\n\n public static Builder builder() {\n return new Builder();\n }\n\n public static class Builder {\n private Map<Class, Formatter> formatters = new HashMap<>();\n private boolean prettyPrintSchema = true;\n private boolean prettyPrintFields = false;\n private boolean addSpaceAfterColon = true;\n private String indent = \" \";\n\n public <T> Builder setFormatter(Class<T> dtoClass, Formatter<T> formatter) {\n formatters.put(dtoClass, formatter);\n return this;\n }\n\n /** False - to print schema in one line, true - to print it nicely formatted. */\n public Builder setPrettyPrintSchema(boolean prettyPrintSchema) {\n this.prettyPrintSchema = prettyPrintSchema;\n return this;\n }\n\n /**\n * When false - each field will be written as one line, even if pretty printing of schema is set to true.\n * if prettyPrintSchema is false, prettyPrintFields is ignored.\n */\n public Builder setPrettyPrintFields(boolean prettyPrintFields) {\n this.prettyPrintFields = prettyPrintFields;\n return this;\n }\n\n /** Set indent value for pretty printing. */\n public Builder setIndent(String indent) {\n this.indent = indent;\n return this;\n }\n\n public FormatterConfig build() {\n FormatterConfig config = new FormatterConfig();\n config.formatters.putAll(this.formatters);\n config.lineSeparator = prettyPrintSchema ? \"\\n\" : \"\";\n config.colon = addSpaceAfterColon ? \": \" : \":\";\n config.prettyPrintFields = prettyPrintFields && prettyPrintSchema;\n config.prettyPrintSchema = prettyPrintSchema;\n config.indent = prettyPrintSchema ? indent : \"\";\n return config;\n }\n }\n}", "public class SchemaFormatter implements Formatter<AvroSchema> {\n\n @Override\n public String toJson(AvroSchema avroSchema, FormatterConfig config) {\n StringBuilder builder = new StringBuilder();\n\n builder\n .append(\"{\").append(config.prettyPrintSchema()? \"\" : \" \").append(config.lineSeparator())\n .append(formatLine(config, \"type\", \"record\"))\n .append(formatLine(config, \"name\", avroSchema.getName()))\n .append(formatLine(config, \"namespace\", avroSchema.getNamespace()));\n \n if (avroSchema.isDocSet()) {\n builder.append(formatLine(config, \"doc\", avroSchema.getDoc()));\n }\n\n avroSchema.getCustomProperties().forEach((key, value) -> {\n builder.append(formatLine(config, key, value));\n });\n\n builder.append(config.lineSeparator())\n .append(config.indent()).append(\"\\\"fields\\\"\").append(config.colon()).append(\"[\").append(config.lineSeparator())\n .append(formatFields(config, avroSchema)).append(config.lineSeparator())\n .append(config.indent()).append(\"]\").append(config.lineSeparator())\n .append(\"}\");\n\n return builder.toString();\n }\n\n public String formatLine(FormatterConfig config, String name, String value) {\n return config.indent() + \"\\\"\" + name + \"\\\"\" + config.colon() + \"\\\"\" + value + \"\\\",\" + (config.prettyPrintSchema()? \"\" : \" \") + config.lineSeparator();\n }\n\n public String formatFields(FormatterConfig config, AvroSchema schema) {\n StringBuilder fieldsJson = new StringBuilder();\n for (AvroField field : schema.getFields()) {\n Formatter<AvroField> formatter = config.getFormatter(field);\n String json = formatter.toJson(field, config);\n fieldsJson.append(config.indent()).append(config.indent()).append(json).append(\",\").append(config.lineSeparator());\n }\n fieldsJson.setLength(fieldsJson.length()-2);\n return fieldsJson.toString();\n }\n}", "public class RemovePlural implements Function<String, String> {\n\n private final Inflector inflector = new Inflector();\n\n @Override\n public String apply(String name) {\n return inflector.singularize(name);\n }\n}", "public class ToCamelCase implements Function<String, String> {\n\n private final Inflector inflector = new Inflector();\n\n @Override\n public String apply(String name) {\n while (name.startsWith(\"_\")) {\n name = name.substring(1);\n }\n return inflector.upperCamelCase(name, '_');\n }\n}", "public static String classPathResourceContent(String resourceName) {\n try {\n return IOUtils.toString(Utils.class.getResource(resourceName), UTF_8);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n}" ]
import com.at.avro.AvroSchema; import com.at.avro.DbSchemaExtractor; import com.at.avro.SchemaGenerator; import com.at.avro.config.AvroConfig; import com.at.avro.config.FormatterConfig; import com.at.avro.formatters.SchemaFormatter; import com.at.avro.mappers.RemovePlural; import com.at.avro.mappers.ToCamelCase; import org.flywaydb.core.Flyway; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.List; import java.util.function.Function; import static helper.Utils.classPathResourceContent; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat;
package com.at.avro.integration; /** * @author artur@callfire.com */ public class HsqlIntegrationTest { private static final String CONNECTION_URL = "jdbc:hsqldb:mem:testcase;shutdown=true"; private static Connection CONNECTION; private AvroConfig avroConfig = new AvroConfig("test.namespace"); private DbSchemaExtractor extractor; @BeforeClass public static void setupClass() throws SQLException { CONNECTION = DriverManager.getConnection(CONNECTION_URL, "sa", ""); Flyway.configure() .dataSource(CONNECTION_URL, "sa", "") .locations("classpath:hsql/db/migration") .load().migrate(); } @AfterClass public static void teardownClass() throws Exception { CONNECTION.close(); } @Before public void setup() throws SQLException { extractor = new DbSchemaExtractor(CONNECTION_URL, "sa", ""); } @Test public void testGenerationWithDefaultSettings() { AvroSchema avroSchema = extractor.getForTable(avroConfig, "public", "test_records"); assertThat(SchemaGenerator.generate(avroSchema), is(classPathResourceContent("/hsql/avro/default.avsc"))); } @Test public void testGenerationWithAllNullableFields() { avroConfig.setNullableTrueByDefault(true); AvroSchema avroSchema = extractor.getForTable(avroConfig, "public", "test_records"); assertThat(SchemaGenerator.generate(avroSchema), is(classPathResourceContent("/hsql/avro/all_nullable.avsc"))); } @Test public void testGenerationAllFieldsDefaultNull() { avroConfig.setAllFieldsDefaultNull(true); AvroSchema avroSchema = extractor.getForTable(avroConfig, "public", "test_records"); assertThat(SchemaGenerator.generate(avroSchema), is(classPathResourceContent("/hsql/avro/all_fields_default_null.avsc"))); } @Test public void testSpecificFormatterConfig() { FormatterConfig formatterConfig = FormatterConfig.builder() .setIndent(" ") .setPrettyPrintFields(true) .build(); AvroSchema avroSchema = extractor.getForTable(avroConfig, "public", "test_records"); assertThat(SchemaGenerator.generate(avroSchema, formatterConfig), is(classPathResourceContent("/hsql/avro/pretty_print_bigger_indent.avsc"))); } @Test public void testNonPrettyPrint() { FormatterConfig formatterConfig = FormatterConfig.builder() .setPrettyPrintSchema(false) .build(); AvroSchema avroSchema = extractor.getForTable(avroConfig, "public", "test_records"); assertThat(SchemaGenerator.generate(avroSchema, formatterConfig), is(classPathResourceContent("/hsql/avro/non_pretty_print.avsc"))); } @Test public void testNameMappers() {
Function<String, String> nameMapper = new ToCamelCase().andThen(new RemovePlural());
7
azinik/ADRMine
release/v1/java_src/ADRMine/src/main/java/edu/asu/diego/loader/DocumentAnalyzer.java
[ "@Entity\n@Table( name = \"Artifact\" )\npublic class Artifact {\n\tString content;\n\tString generalized_content;\n\tList<Artifact> childsArtifact;\n\tArtifact parentArtifact;\n\tArtifact nextArtifact;\n\tArtifact previousArtifact;\n\tType artifactType;\n\tprivate boolean forTrain;\n\tprivate boolean forDemo=false;\n\t\n\t\n\t\n\t@Transient\n\tboolean isNew;\n\t@Transient\n//\tList<ArtifactFeature> features = new ArrayList<ArtifactFeature>();\n\t\n\tString POS;\n\t\n\t// These two variable are lazy and will be initialized in getter\n\tInteger startIndex = null;\n\tInteger endIndex = null;\n\n\tInteger lineOffset = null;\n\tInteger wordOffset = null;\n\t\n\tString stanDependency =null;\n\tprivate String stanPennTree = null;\n\t\n\tint artifactId = -1;\n\t/*\n\t * Physical address of file which artifact loaded from that\n\t */\n\tString associatedFilePath;\n\tString corpusName;\n\n\tpublic enum Type {\n\t\tDocument, Sentence, Phrase, Word\n\t}\n\n\t\n\tpublic Artifact()\n\t{\n\t\t\n\t}\n\t/**\n\t * Loads Artifact by id\n\t * @param pArtifactID\n\t * @return\n\t */\n\tpublic static Artifact getInstance(int pArtifactID) {\n\t\tString hql = \"from Artifact where artifactId = \"+pArtifactID;\n\t\tArtifact artifact_obj = \n\t\t\t(Artifact)HibernateUtil.executeReader(hql).get(0);\n\t\treturn artifact_obj;\n\t}\n\t/**\n\t * Creates completely empty Artifact object\n\t * @return\n\t */\n\tpublic static Artifact getInstance(Type pArtifactType) {\n\t\tArtifact artifact_obj = new Artifact();\n\t\tartifact_obj.setArtifactType(pArtifactType);\n\t\tHibernateUtil.save(artifact_obj);\n\t\treturn artifact_obj;\n\t}\n\t\n\t/**\n\t * Loads or creates the Artifact\n\t * @param pArtifactType\n\t * @param pFilePath\n\t * @param pStartIndex\n\t * @return\n\t */\n\tpublic static Artifact getInstance(Type pArtifactType, String pFilePath, \n\t\t\tint pStartIndex){\n\t\tString hql = \"from Artifact where artifactType = \"+\n\t\t\tpArtifactType.ordinal()+\" and associatedFilePath ='\" +\n\t\t\tpFilePath + \"' and startIndex=\"+pStartIndex;\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql);\n\t \n\t \n\t Artifact artifact_obj;\n\t if(artifact_objects.size()==0)\n\t {\n\t \tartifact_obj = new Artifact();\n\t \tartifact_obj.setStartIndex(pStartIndex);\n\t \tartifact_obj.setAssociatedFilePath(pFilePath);\n\t \tartifact_obj.setArtifactType(pArtifactType);\n\t \tartifact_obj.setForTrain(Setting.TrainingMode);\n\t \tHibernateUtil.save(artifact_obj);\n\t }else\n\t {\n\t \tartifact_obj = \n\t\t\t\tartifact_objects.get(0);\n\t }\n\t return artifact_obj;\n\t}\n\tpublic static Artifact getInstance(Type pArtifactType, String pFilePath, \n\t\t\tint pStartIndex,String corpusName){\n\t\tString hql = \"from Artifact where artifactType = \"+\n\t\t\tpArtifactType.ordinal()+\" and associatedFilePath ='\" +\n\t\t\tpFilePath + \"' and corpusName= '\"+corpusName+\"' and startIndex=\"+pStartIndex;\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql);\n\t \n\t \n\t Artifact artifact_obj;\n\t if(artifact_objects.size()==0)\n\t {\n\t \tartifact_obj = new Artifact();\n\t \tartifact_obj.setStartIndex(pStartIndex);\n\t \tartifact_obj.setAssociatedFilePath(pFilePath);\n\t \tartifact_obj.setArtifactType(pArtifactType);\n\t \tartifact_obj.setForTrain(Setting.TrainingMode);\n\t \tartifact_obj.setCorpusName(corpusName);\n\t \tHibernateUtil.save(artifact_obj);\n\t }else\n\t {\n\t \tartifact_obj = \n\t\t\t\tartifact_objects.get(0);\n\t }\n\t return artifact_obj;\n\t}\n\tpublic static Artifact getInstance(Type pArtifactType, String pFilePath, \n\t\t\tint pStartIndex,boolean forDemo){\n\t\tString hql = \"from Artifact where artifactType = \"+\n\t\t\tpArtifactType.ordinal()+\" and associatedFilePath ='\" +\n\t\t\tpFilePath + \"' and startIndex=\"+pStartIndex+\" and forDemo=\"+forDemo;\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql);\n\t \n\t \n\t Artifact artifact_obj;\n\t if(artifact_objects.size()==0)\n\t {\n\t \tartifact_obj = new Artifact();\n\t \tartifact_obj.setStartIndex(pStartIndex);\n\t \tartifact_obj.setAssociatedFilePath(pFilePath);\n\t \tartifact_obj.setArtifactType(pArtifactType);\n\t \tHibernateUtil.save(artifact_obj);\n\t }else\n\t {\n\t \tartifact_obj = \n\t\t\t\tartifact_objects.get(0);\n\t }\n\t return artifact_obj;\n\t}\n\tpublic static Artifact getInstance(int pWordIndex,Type pArtifactType, String pFilePath\n\t\t\t){\n\t\tString hql = \"from Artifact where artifactType = \"+\n\t\t\tpArtifactType.ordinal()+\" and associatedFilePath ='\" +\n\t\t\tpFilePath + \"' and wordIndex=\"+pWordIndex;\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql);\n\t \n\t \n\t Artifact artifact_obj;\n\t if(artifact_objects.size()==0)\n\t {\n\t \tartifact_obj = new Artifact();\n\t \tartifact_obj.setWordIndex(pWordIndex);\n\t \tartifact_obj.setAssociatedFilePath(pFilePath);\n\t \tartifact_obj.setArtifactType(pArtifactType);\n\t \tHibernateUtil.save(artifact_obj);\n\t }else\n\t {\n\t \tartifact_obj = \n\t\t\t\tartifact_objects.get(0);\n\t }\n\t return artifact_obj;\n\t}\n\tpublic static Artifact getInstance(Type pArtifactType, String unique_id, \n\t\t\tString content){\n\t\tString hql = \"from Artifact where artifactType = \"+\n\t\t\tpArtifactType.ordinal()+\" and associatedFilePath ='\" +\n\t\t\tunique_id+\"'\";\n\t\t\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql);\n\t \n\t \n\t Artifact artifact_obj;\n\t if(artifact_objects.size()==0)\n\t {\n\t \tartifact_obj = new Artifact();\n\t \t\n\t \tartifact_obj.setAssociatedFilePath(unique_id);\n\t \tartifact_obj.setContent(content);\n\t \tartifact_obj.setArtifactType(pArtifactType);\n\t \t\n\t \tHibernateUtil.save(artifact_obj);\n\t }else\n\t {\n\t \tartifact_obj = \n\t\t\t\tartifact_objects.get(0);\n\t }\n\t return artifact_obj;\n\t}\n\tpublic static Artifact getInstanceByEndChar(Type pArtifactType, String pFilePath, \n\t\t\tint pEndIndex){\n\t\tString hql = \"from Artifact where artifactType = \"+\n\t\t\tpArtifactType.ordinal()+\" and associatedFilePath ='\" +\n\t\t\tpFilePath + \"' and endIndex=\"+pEndIndex;\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql);\n\t \n\t \n\t Artifact artifact_obj;\n\t if(artifact_objects.size()==0)\n\t {\n\t \tartifact_obj = new Artifact();\n\t \tartifact_obj.setEndIndex(pEndIndex);\n\t \tartifact_obj.setAssociatedFilePath(pFilePath);\n\t \tartifact_obj.setArtifactType(pArtifactType);\n\t \tHibernateUtil.save(artifact_obj);\n\t }else\n\t {\n\t \tartifact_obj = \n\t\t\t\tartifact_objects.get(0);\n\t }\n\t return artifact_obj;\n\t}\n\tpublic static Artifact getMadeUpInstance(String content){\n\t\tString hql = \"from Artifact where content = '\"+content+\"'\";\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql);\n\t \n\t \n\t Artifact artifact_obj;\n\t if(artifact_objects.size()==0)\n\t {\n\t \tartifact_obj = new Artifact();\n\t \tartifact_obj.setContent(content);\n\t \tHibernateUtil.save(artifact_obj);\n\t }else\n\t {\n\t \tartifact_obj = \n\t\t\t\tartifact_objects.get(0);\n\t }\n\t return artifact_obj;\n\t}\n\t@ManyToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE})\n//\t@ManyToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch=FetchType.LAZY )\n//\t@ManyToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE} )\n @JoinColumn(name=\"parentArtifact\")\n\tpublic Artifact getParentArtifact() {\n\t\treturn parentArtifact;\n\t}\n\tpublic void setParentArtifact(Artifact _parentArtifact) {\n\t\tparentArtifact = _parentArtifact;\n\t}\n\t\n//\t@OneToMany(mappedBy=\"parentArtifact\")\n// @OrderBy(\"startIndex\")\n\t@Transient\n\tpublic List<Artifact> getChildsArtifact() {\n\t\tif(childsArtifact==null && artifactType != Type.Word)\n\t\t\tchildsArtifact = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader( \"from Artifact where parentArtifact = \"+artifactId+\" order by artifactId\");\n\n\t\treturn childsArtifact;\n\t}\n\t\n\n\t\n\t\n//\t@OneToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch=FetchType.LAZY )\n\t@OneToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE} )\n\t@JoinColumn(name=\"nextArtifact\")\n public Artifact getNextArtifact() {\n\t\treturn nextArtifact;\n\t}\n\tpublic void setNextArtifact(Artifact pNextArtifact){\n\t\tnextArtifact = pNextArtifact;\n\t}\n\t\n\n//\t@OneToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch=FetchType.LAZY )\n\t@OneToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE} )\n\t@JoinColumn(name=\"previousArtifact\")\n public Artifact getPreviousArtifact() {\n\t\treturn previousArtifact;\n\t}\n\tpublic void setPreviousArtifact(Artifact pPreviousArtifact){\n\t\tpreviousArtifact = pPreviousArtifact;\n\t}\n\t/**\n\t * Return oldest parent of this Artifact which is usually a Document\n\t */\n\t@Transient\n\tpublic Artifact grandFather() throws SQLException {\n\t\tArtifact grandFather = this;\n\n\t\twhile (grandFather.getParentArtifact() != null) {\n\t\t\tgrandFather = grandFather.getParentArtifact();\n\t\t}\n\n\t\treturn grandFather;\n\t}\n\n\t@Index(name = \"index_start_index\")\n\tpublic Integer getStartIndex() {\n\t\tif (this.getArtifactType() == Type.Document) {\n\t\t\tstartIndex = 0;\n\t\t} else if (startIndex == null) {\n\t\t\tint _previousArtifactsLength = 0;\n\t\t\tArtifact previous = this.getPreviousArtifact();\n\t\t\twhile (previous != null) {\n\t\t\t\t_previousArtifactsLength += previous.getContent().length() + 1;\n\t\t\t\tprevious = previous.getPreviousArtifact();\n\t\t\t}\n\t\t\tif(getParentArtifact()!=null)\n\t\t\t\tstartIndex = parentArtifact.getStartIndex()\n\t\t\t\t\t\t+ _previousArtifactsLength + 1;\n\t\t\t\n\t\t}\n\t\treturn startIndex;\n\t}\n\n\tpublic void setEndIndex(Integer _endIndex) {\n\t\tif (_endIndex == null && !this.getContent().isEmpty()) {\n\t\t\t_endIndex = startIndex + this.getContent().length();\n\t\t}\n\t\tendIndex = _endIndex;\n\t}\n\n\t@Index(name = \"index_end_index\")\n\tpublic Integer getEndIndex() {\n\t\tif (endIndex == null)\n\t\t{\n\t\t\tif(getStartIndex()!=null)\n\t\t\t\tendIndex = startIndex + getContent().length();\n\t\t}\n\t\t\n\t\treturn endIndex;\n\t}\n\n\t\n\n\tpublic String getPOS()\n\t{\n//\t\tif(POS==null){\n////\t\t\ttry {\n////\t\t\t\tPOS = \n////\t\t\t\t\tArtifactAttributeTable.getAttributeValue(artifactId, \n////\t\t\t\t\t\t\tAttributeValuePair.AttributeType.POS.name());\n////\t\t\t} catch (SQLException e) {\n////\t\t\t\t// TODO Auto-generated catch block\n////\t\t\t\te.printStackTrace();\n////\t\t\t}\n//\t\t\tif(POS==null && artifactType == Type.Word){\n//\t\t\t\tString contentRegexCasted = StringUtil.castForRegex(getContent());\n//\t\t\t\tlineOffset = getLineIndex();\n//\t\t\t\tif(lineOffset==null) return \"\";\n//\t\t\t\tString tagged = \n//\t\t\t\t\tStanfordParser.getTagged(associatedFilePath, lineOffset);\n//\t\t\t\tString[] taggedTokens = \n//\t\t\t\t\ttagged.split(\" \");\n//\t\t\t\twordOffset = getWordIndex();\n//\t\t\t\tboolean index_invalid = false;\n//\t\t\t\tif(wordOffset!=null && \n//\t\t\t\t\t\ttaggedTokens.length>wordOffset)\n//\t\t\t\t{\n//\t\t\t\t\tString[] parts = taggedTokens[wordOffset].replace(\"\\\\/\", \"/\"). // '/' is tagger splitter; decast to match\t\t\t\t\t\n//\t\t\t\t\t\t\tsplit(contentRegexCasted+\"/\");\n//\t\t\t\t\tif(parts.length==2)\n//\t\t\t\t\t\tPOS = parts[1];\n//\t\t\t\t\telse\n//\t\t\t\t\t\tindex_invalid = true;\n//\t\t\t\t}\n//\t\t\t\telse\n//\t\t\t\t\tindex_invalid= true;\n//\n//\t\t\t\tif(index_invalid)\n//\t\t\t\t{\n//\t\t\t\t\t\n//\t\t\t\t\tnextArtifact = getNextArtifact();\n//\t\t\t\t\tpreviousArtifact = getPreviousArtifact();\n//\t\t\t\t\tif(previousArtifact != null && nextArtifact!=null)\n//\t\t\t\t\t{\n//\t\t\t\t\t\tString preContent=previousArtifact.getContent();\n//\t\t\t\t\t\tString nextContent=nextArtifact.getContent();\n//\t\t\t\t\t\tif(nextContent.equals(\"-\"))\n//\t\t\t\t\t\t{\n//\t\t\t\t\t\t\tArtifact nextnext = nextArtifact.getNextArtifact();\n//\t\t\t\t\t\t\tif(nextnext!=null)\n//\t\t\t\t\t\t\t{\n//\t\t\t\t\t\t\t\tcontentRegexCasted = \n//\t\t\t\t\t\t\t\t\tcontentRegexCasted+\n//\t\t\t\t\t\t\t\t\tnextContent+\n//\t\t\t\t\t\t\t\t\tnextnext.getContent();\n//\t\t\t\t\t\t\t}\n//\t\t\t\t\t\t}\n//\t\t\t\t\t\t// to make sure not casted before\n////\t\t\t\t\t\t\tcontentRegexCasted = \n////\t\t\t\t\t\t\t\tUtil.castForRegex(Util.decastRegex(contentRegexCasted));\n//\t\t\t\t\t\t\n//\t\t\t\t\t\tPattern p = Pattern.compile(\"(.* )?\"+contentRegexCasted+\"/(\\\\S+)( .*)?\");\n//\t\t\t\t\t\tPattern p2 = Pattern.compile(\"(.* )?\\\\S*\"+contentRegexCasted+\"\\\\S*/(\\\\S+)( .*)?\");\n//\t\t\t\t\t\tMatcher m = p.matcher(tagged);\n//\t\t\t\t\t\tif(m.matches())\n//\t\t\t\t\t\t{\n//\t\t\t\t\t\t\tPOS=m.group(2);\n////\t\t\t\t\t\t\t\tUtil.log(\"_POS found: \"+_POS+\n////\t\t\t\t\t\t\t\t\t\t\" for \"+contentRegexCasted, Level.INFO);\n//\t\t\t\t\t\t}else\n//\t\t\t\t\t\t{\n//\t\t\t\t\t\t\tm = p2.matcher(tagged);\n//\t\t\t\t\t\t\tif(m.matches())\n//\t\t\t\t\t\t\t{\n//\t\t\t\t\t\t\t\tPOS=m.group(2);\n////\t\t\t\t\t\t\t\t\tUtil.log(\"_POS found: \"+_POS+\n////\t\t\t\t\t\t\t\t\t\t\t\" for \"+contentRegexCasted, Level.INFO);\n//\t\t\t\t\t\t\t}\n//\t\t\t\t\t\t}\n//\t\t\t\t\t\t\n//\t\t\t\t\t}\n//\t\t\t\t\t\n//\t\t\t\t\tif(POS==null && previousArtifact != null)\n//\t\t\t\t\t{\n//\t\t\t\t\t\tPOS = previousArtifact.getPOS();\n//\t\t\t\t\t}\n//\t\t\t\t\tif(POS==null)\n//\t\t\t\t\t{\n//\t\t\t\t\t\tPOS = getContent();\n////\t\t\t\t\t\tUtil.log(\"Error in _POS: word index = \"+_wordOffset+\n////\t\t\t\t\t\t\t\", tagged:\"+tagged+\", tagged token:\"+\n////\t\t\t\t\t\t\t\" \"+contentRegexCasted+\" -> \" \n////\t\t\t\t\t\t\t+getContent(), Level.WARNING);\n//\t\t\t\t\t}\n//\t\t\t\t}\n//\t\t\t}\n//\t\t}\n//\t\tif(getContent().equals(\"-\"))\n//\t\t\tPOS = \"-\";\n\n\t\t\n\t\treturn POS;\n\t}\n\tpublic void setPOS(String pPOS) {\n\t\tPOS = pPOS;\n\t}\n\t/**\n\t * starts from 0\n\t * @return\n\t */\n\t@Index(name = \"index_word_index\")\n\tpublic Integer getWordIndex() {\n\t\t\n\t\t\n\t\tif(wordOffset==null)\n\t\t{\n\t\t\t\n\t\t\tif(artifactType==Type.Word)\n\t\t\t{\n\t\t\t\n\t\t\t\twordOffset=0;\n\t\t\t\tArtifact preWord = getPreviousArtifact();\n\t\t\t\twhile(preWord!=null)\n\t\t\t\t{\n\t\t\t\t\twordOffset++;\n\t\t\t\t\tpreWord = preWord.getPreviousArtifact();\n\t\t\t\t\tpreviousArtifact = null;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t}\n\t\treturn wordOffset;\n\t}\n\t\n\tpublic void setWordIndex(Integer _wordOffset) {\n\t\twordOffset = _wordOffset;\n\t}\n\tpublic void setLineIndex(Integer _lineIndex) {\n\t\tlineOffset = _lineIndex;\n\t}\n\tpublic void setStartIndex(Integer _startIndex) {\n\t\tstartIndex = _startIndex;\n\t}\n\t\n\t/**\n\t * sentence index, starts from 1\n\t * @return\n\t */\n\t@Index(name = \"index_line_index\")\n\tpublic Integer getLineIndex() {\n\t\tif(lineOffset==null)\n\t\t{\n\t\t\tif(artifactType==Type.Word)\n\t\t\t{\n\t\t\t\tArtifact sentence = getParentArtifact();\n\t\t\t\tif(sentence==null) \n\t\t\t\t{\n\t\t\t\t\tnextArtifact = getNextArtifact();\n\t\t\t\t\tif(nextArtifact!=null)\n\t\t\t\t\t\tsentence = nextArtifact.getParentArtifact();\n\t\t\t\t}\n\t\t\t\tif(sentence==null) \n\t\t\t\t{\n\t\t\t\t\tpreviousArtifact = getPreviousArtifact();\n\t\t\t\t\tif(previousArtifact!=null)\n\t\t\t\t\t\tsentence = previousArtifact.getParentArtifact();\n\t\t\t\t}\n\t\t\t\tif(sentence==null) \n\t\t\t\t{\n//\t\t\t\t\t\tUtil.log(\"Error in getLineIndex: word '\"+ _artifactId \n//\t\t\t\t\t\t\t\t+\"' doesn't have parent!\", Level.SEVERE);\n\t\t\t\t\t\t\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tlineOffset = sentence.getLineIndex();\n\t\t\t}\n\t\t\tif(artifactType==Type.Sentence)\n\t\t\t{\n\t\t\t\tlineOffset=1;\n\t\t\t\tArtifact preSentence = getPreviousArtifact();\n\t\t\t\twhile(preSentence!=null)\n\t\t\t\t{\n\t\t\t\t\tlineOffset++;\n\t\t\t\t\tpreSentence = preSentence.getPreviousArtifact();\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t}\n\t\treturn lineOffset;\n\t}\n\n\tpublic void setContent(String _content) {\n\t\tthis.content = _content;\n\t}\n\t@Column(length = 2000)\n\t@Index(name = \"index_content\")\n\tpublic String getContent() {\n\t\tif(content==null) return \"\";\n\t\treturn content;\n\t}\n\n\tpublic void setAssociatedFilePath(String _associatedFilePath) {\n\t\tthis.associatedFilePath = _associatedFilePath;\n\t}\n\n\tpublic String getAssociatedFilePath() {\n\t\treturn associatedFilePath;\n\t}\n\t\n\t@Column(nullable = false)\n\tpublic void setArtifactType(Type _artifactType) {\n\t\tthis.artifactType = _artifactType;\n\t}\n\n\tpublic Type getArtifactType() {\n\t\treturn artifactType;\n\t}\n\n\tpublic void setArtifactId(int _artifactId) {\n\t\tthis.artifactId = _artifactId;\n\t}\n\t@Id\n\t@GeneratedValue(generator=\"increment\")\n\t@GenericGenerator(name=\"increment\", strategy = \"increment\")\n\tpublic int getArtifactId() {\n\t\treturn artifactId;\n\t}\n\t\n\t@Override public String toString()\n\t{\n\t\treturn associatedFilePath.substring(associatedFilePath.length()-15, \n\t\t\t\tassociatedFilePath.length()-1) + \":\"+\n\t\t\tartifactId+\"-\"+artifactType.toString()+\"-\"\n\t\t\t+parentArtifact.artifactId+\"-\"+\n\t\t\tnextArtifact.artifactId+\"-\"+\n\t\t\tpreviousArtifact.artifactId;\n\t}\n\t\n\t@Override public boolean equals(Object pArtifact)\n\t{\n\t\tif(!(pArtifact instanceof Artifact))\n\t\t\treturn false;\n\t\tArtifact a = (Artifact)pArtifact;\n\t\treturn (a.getArtifactId() == artifactId) ||\n\t\t\t\t(a.getStartIndex() == getStartIndex() &&\n\t\t\t\ta.getContent().equals(getContent()) &&\n\t\t\t\ta.getAssociatedFilePath().equals(getAssociatedFilePath()) &&\n\t\t\t\ta.getArtifactType().equals(getArtifactType()));\n\t}\n\t@Override public int hashCode()\n\t{\n\t\treturn artifactId;\n\t}\n\tpublic static Artifact findInstance(Type pArtifactType, String pFilePath, \n\t\t\tint pWordIndex, int pLineIndex){\n\t\tString hql = \"from Artifact where artifactType =:artifactType and\" +\n\t\t\t\t\" associatedFilePath like :associatedFilePath and wordIndex=:wordIndex \" +\n\t\t\t\t\" and lineIndex= :lineIndex\";\n\t\t\n\t\tHashMap<String, Object> params = new HashMap<String, Object>();\n\t\tparams.put(\"associatedFilePath\", '%'+pFilePath);\n\t\tparams.put(\"wordIndex\", pWordIndex);\n\t\tparams.put(\"artifactType\", pArtifactType.ordinal());\n\t\tparams.put(\"lineIndex\",pLineIndex);\n\t\t\n\t\t\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql,params);\n\t \n\t \n\t Artifact artifact_obj=null;\n\t if(artifact_objects.size()!=0)\n\t {\n\t \tartifact_obj = \n\t\t\t\tartifact_objects.get(0);\n\t }\n\t return artifact_obj;\n\t}\n\tpublic static Artifact findInstance(Artifact pSentence,int pWordIndex){\n\t\tString hql = \"from Artifact where parentArtifact = \"+pSentence.getArtifactId()+\" and wordIndex =\" +\n\t\tpWordIndex;\n\t\t\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql);\n\t \n\t \n\t Artifact artifact_obj=null;\n\t if(artifact_objects.size()!=0)\n\t {\n\t \tartifact_obj = \n\t\t\t\tartifact_objects.get(0);\n\t }\n\t return artifact_obj;\n\t}\n\tpublic static Artifact findInstance(Type pArtifactType, String pFilePath, \n\t\t\tint pLine, int pWordIndex, String pContent, String pSecondWord){\n\t\t\n\t\tHashMap<String, Object> params = new HashMap<String, Object>();\n\t\tString hql = \"from Artifact where artifactType =:artifactType and\" +\n\t\t\t\t\" associatedFilePath like :associatedFilePath and content like:content \" +\n\t\t\t\t\" and lineIndex= :lineIndex \";\n\t\tif (pSecondWord != null)\n\t\t{\n\t\t\thql += \"and nextArtifact.content = :nextContent\";\n\t\t\tparams.put(\"nextContent\", pSecondWord);\n\t\t}\n\t\telse\n\t\t{\n\t\t\thql += \" and ABS(wordIndex - :pWordIndex) <=5\";\n\t\t\tparams.put(\"pWordIndex\",pWordIndex);\n\t\t}\n\t\t\n\t\tparams.put(\"associatedFilePath\", '%'+pFilePath);\n\t\tparams.put(\"content\", pContent+'%');\n\t\tparams.put(\"artifactType\", pArtifactType.ordinal());\n\t\tparams.put(\"lineIndex\",pLine);\n\t\t\n\t\t\n\t\t\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql,params);\n\t \n\t \n\t Artifact artifact_obj=null;\n\t if(artifact_objects.size()!=0)\n\t {\n\t \tartifact_obj = \n\t\t\t\tartifact_objects.get(0);\n\t }\n\t return artifact_obj;\n\t}\n\tpublic static Artifact findInstanceByContent(Type pArtifactType, String pFilePath, \n\t\t\tString pContent ){\n\t\t\n\t\tHashMap<String, Object> params = new HashMap<String, Object>();\n\t\tString hql = \"from Artifact where artifactType =:artifactType and\" +\n\t\t\t\t\" associatedFilePath like :associatedFilePath and content like:content \";\n\t\t\n\t\t\n\t\tparams.put(\"associatedFilePath\", '%'+pFilePath+'%');\n\t\tparams.put(\"content\", '%'+pContent+'%');\n\t\tparams.put(\"artifactType\", pArtifactType.ordinal());\n\t\t\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql,params);\n\t \n\t \n\t Artifact artifact_obj=null;\n\t if(artifact_objects.size()!=0)\n\t {\n\t \tartifact_obj = \n\t\t\t\tartifact_objects.get(0);\n\t }\n\t return artifact_obj;\n\t}\n\tpublic static Artifact findInstanceByContentEnd(Type pArtifactType, String pFilePath, \n\t\t\tString pContent ){\n\t\tHashMap<String, Object> params = new HashMap<String, Object>();\n\t\tString hql = \"from Artifact where artifactType =:artifactType and\" +\n\t\t\t\t\" associatedFilePath like :associatedFilePath and content like:content \";\n\t\t\n\t\tparams.put(\"associatedFilePath\", '%'+pFilePath+'%');\n\t\tparams.put(\"content\", '%'+pContent);\n\t\tparams.put(\"artifactType\", pArtifactType.ordinal());\n\t\t\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql,params);\n\t Artifact artifact_obj=null;\n\t if(artifact_objects.size()!=0)\n\t {\n\t \tartifact_obj = \n\t\t\t\tartifact_objects.get(0);\n\t }\n\t return artifact_obj;\n\t}\n\tpublic static Artifact findInstanceByExactContent(Type pArtifactType, String pFilePath, \n\t\t\tString pContent ){\n\t\tHashMap<String, Object> params = new HashMap<String, Object>();\n\t\tString hql = \"from Artifact where artifactType =:artifactType and\" +\n\t\t\t\t\" associatedFilePath like :associatedFilePath and content like:content \";\n\t\t\n\t\tparams.put(\"associatedFilePath\", '%'+pFilePath+'%');\n\t\tparams.put(\"content\", pContent);\n\t\tparams.put(\"artifactType\", pArtifactType.ordinal());\n\t\t\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql,params);\n\t Artifact artifact_obj=null;\n\t if(artifact_objects.size()!=0)\n\t {\n\t \tartifact_obj = \n\t\t\t\tartifact_objects.get(0);\n\t }\n\t return artifact_obj;\n\t}\n\tpublic static Artifact findInstance(Type pArtifactType, String pFilePath, \n\t\t\tint pStartChar, String pContent, String pSecondWord){\n\t\t\n\t\tHashMap<String, Object> params = new HashMap<String, Object>();\n\t\tString hql = \"from Artifact where artifactType =:artifactType and\" +\n\t\t\t\t\" associatedFilePath like :associatedFilePath and content like:content \" +\n\t\t\t\t\" and ABS(startIndex - :pStartIndex) <45\";\n\t\tif (pSecondWord != null)\n\t\t{\n\t\t\thql += \"and nextArtifact.content = :nextContent\";\n\t\t\tparams.put(\"nextContent\", pSecondWord);\n\t\t}\n\t\n\t\t\n\t\tparams.put(\"associatedFilePath\", '%'+pFilePath);\n\t\tparams.put(\"content\", pContent+'%');\n\t\tparams.put(\"artifactType\", pArtifactType.ordinal());\n\t\tparams.put(\"pStartIndex\",pStartChar);\n\t\t\n\t\t\n\t\t\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql,params);\n\t \n\t \n\t Artifact artifact_obj=null;\n\t if(artifact_objects.size()!=0)\n\t {\n\t \tartifact_obj = \n\t\t\t\tartifact_objects.get(0);\n\t }\n\t return artifact_obj;\n\t}\n\tpublic static Artifact findInstanceByStartIndex(String pFilePath,int pStartIndex){\n\t\tString hql = \"from Artifact where associatedFilePath like :associatedFilePath and artifactType=:artifactType and startIndex=:startIndex \";\n\n\t\tHashMap<String, Object> params = new HashMap<String, Object>();\n\t\tparams.put(\"associatedFilePath\", '%'+pFilePath);\n\t\tparams.put(\"startIndex\", pStartIndex);\n\t\tparams.put(\"artifactType\", 3);\n\t\t\n\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql, params);\n\n\n\t Artifact artifact_obj=null;\n\t if(artifact_objects.size()!=0)\n\t {\n\t \tartifact_obj = \n\t\t\t\tartifact_objects.get(0);\n\t }\n\t return artifact_obj;\n\t}\n\tpublic static Artifact findInstanceByEndIndex(String pFilePath,int pEndIndex){\n\t\tString hql = \"from Artifact where associatedFilePath like :associatedFilePath and artifactType=:artifactType and endIndex=:endIndex \";\n\n\t\tHashMap<String, Object> params = new HashMap<String, Object>();\n\t\tparams.put(\"associatedFilePath\", '%'+pFilePath);\n\t\tparams.put(\"endIndex\", pEndIndex);\n\t\tparams.put(\"artifactType\", 3);\n\t\t\n\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql, params);\n\n\n\t Artifact artifact_obj=null;\n\t if(artifact_objects.size()!=0)\n\t {\n\t \tartifact_obj = \n\t\t\t\tartifact_objects.get(0);\n\t }\n\t return artifact_obj;\n\t}\n\tpublic static List<Artifact> listByType(Type pSentenceType) {\n\t\tString hql = \"from Artifact where artifactType = \"+pSentenceType.ordinal()\n\t\t\t\t+\" order by associatedFilePath\";\n\t\t\t\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql);\n\t\treturn artifact_objects;\n\t}\n\t//TODO: move this method to the right class\n\tpublic static List<Artifact> listTweets(Type pSentenceType) {\n\t\tString hql = \"from Artifact where artifactType = \"+pSentenceType.ordinal()\n\t\t\t\t+\" and associatedFilePath not like '%host%' order by associatedFilePath\";\n\t\t\t\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql);\n\t\treturn artifact_objects;\n\t}\n\tpublic static List<Artifact> listByTypeByForTrain(Type pSentenceType, boolean forTrain) {\n\t\tString hql = \"from Artifact where artifactType = \"+pSentenceType.ordinal()\n\t\t\t\t+\" and forTrain= \"+forTrain+\" order by associatedFilePath\";\n\t\t\t\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql);\n\t\treturn artifact_objects;\n\t}\n\tpublic static List<Artifact> listByTypeByForTrainByCorpus(Type pSentenceType, boolean forTrain,String corpusName) {\n\t\tString hql = \"from Artifact where artifactType = \"+pSentenceType.ordinal()\n\t\t\t\t+\" and forTrain= \"+forTrain+\" and corpusName= '\"+corpusName+\"' order by associatedFilePath\";\n\t\t\t\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql);\n\t\treturn artifact_objects;\n\t}\n\n\tpublic static List<Artifact> listByTypeLimited(Type pSentenceType,boolean for_train, Integer count) {\n\t\t\n\t\tString hql = \"from Artifact where artifactType = \"+pSentenceType.ordinal()\n\t\t\t\t+\" and forTrain = \"+for_train+\" order by rand()\";\n\t\tHashMap<String, Object> params = new HashMap<String, Object>();\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql,params,count);\n\t\treturn artifact_objects;\n\t}\n\tpublic static List<Artifact> listByType(Type pSentenceType,boolean for_train) {\n\t\tString file_path_pattern = \"/train/\";\n\t\tif (!for_train)\n\t\t{\n\t\t\tfile_path_pattern = \"/test/\";\n\t\t}\n\t\tString hql = \"from Artifact where artifactType = \"+pSentenceType.ordinal()\n\t\t\t\t+\" and associatedFilePath like :pPattern order by associatedFilePath\";\n\t\tHashMap<String, Object> params = new HashMap<String, Object>();\n\t\tparams.put(\"pPattern\", '%'+file_path_pattern+'%');\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql,params);\n\t\treturn artifact_objects;\n\t}\n\n\tpublic void setStanDependency(String stanDependency) {\n\t\tthis.stanDependency = stanDependency;\n\t}\n\t@Column(length = 2000)\n\tpublic String getStanDependency() {\n\t\treturn stanDependency;\n\t}\n\t\n\tpublic void setStanPennTree(String stanPennTree) {\n\t\tthis.stanPennTree = stanPennTree;\n\t}\n\t@Column(length = 2000)\n\tpublic String getStanPennTree() {\n\t\treturn stanPennTree;\n\t}\n\t@Transient\n\tList<Artifact> children = null;\n\t@Transient\n\tpublic Artifact getChildByWordIndex(int word_index) {\n\t\tif(children==null)\n\t\t\tloadChildren();\n\t\tArtifact foundArtifact = null;\n\t\tfor(Artifact art : children)\n\t\t\tif(art.getWordIndex() == word_index)\n\t\t\t{\n\t\t\t\tfoundArtifact = art;\n\t\t\t\tbreak;\n\t\t\t}\n\t\treturn foundArtifact;\n\t}\n\tprivate void loadChildren() {\n\t\tString hql = \"from Artifact where parentArtifact = \"+getArtifactId();\n\t\t\n\t\tchildren = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql);\n\t}\n\t\n\tpublic static List<Artifact> listByTypeAndForTrain(Type pSentenceType,boolean for_train) {\n\n\t\tString hql = \"from Artifact where forTrain =\"+for_train+\" and artifactType = \"+pSentenceType.ordinal()\n\t\t\t\t+\" order by associatedFilePath\";\n\t\tHashMap<String, Object> params = new HashMap<String, Object>();\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql);\n\t\treturn artifact_objects;\n\t}\n\tpublic static List<Artifact> listByTypeAndForTrain(Type pSentenceType,boolean for_train,String corpus) {\n\n\t\tString hql = \"from Artifact where forTrain =\"+for_train+\" and artifactType = \"+pSentenceType.ordinal()\n\t\t\t\t+\" and corpusName='\"+corpus+\"' order by associatedFilePath\";\n\t\tHashMap<String, Object> params = new HashMap<String, Object>();\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql);\n\t\treturn artifact_objects;\n\t}\n\tpublic boolean isForTrain() {\n\t\treturn forTrain;\n\t}\n\tpublic void setForTrain(boolean forTrain) {\n\t\tthis.forTrain = forTrain;\n\t}\n\tpublic boolean isForDemo() {\n\t\treturn forDemo;\n\t}\n\tpublic void setForDemo(boolean forDemo) {\n\t\tthis.forDemo = forDemo;\n\t}\n\tpublic String getCorpusName() {\n\t\treturn corpusName;\n\t}\n\tpublic void setCorpusName(String name) {\n\t\tthis.corpusName = name;\n\t}\n\t\n}", "public class Setting {\n\tpublic static final String RuleSureCorpus = \"RuleSure\";\n\tpublic static boolean SaveInGetInstance = true;\n\tstatic Properties configFile;\n\tpublic enum OperationMode\n\t{\n\t\tTRIGGER,\n\t\tEDGE,\n\t\tARTIFACT\n\t}\n\tpublic static OperationMode Mode = OperationMode.TRIGGER;\n\tpublic static boolean TrainingMode = true;\n\t// This switch between using Development set or Test set for evaluation, set to true if you want to generate test submission files\n\tpublic static boolean ReleaseMode = false;\n\tpublic static int NotTriggerNumericValue = 10;\n\tpublic static int NotEdgeNumericValue = 9;\n\tpublic static int MinInstancePerLeaf;\n\tpublic static Double SVMCostParameter;\n\tpublic static Double SVMPolyCParameter;\n\tpublic static enum SVMKernels {\n\t\t Linear, //0: linear (default)\n Polynomial, //1: polynomial (s a*b+c)^d\n Radial, //2: radial basis function exp(-gamma ||a-b||^2)\n SigmoidTanh //3: sigmoid tanh(s a*b + c)\n\t};\n\tpublic static SVMKernels SVMKernel;\n\n\tpublic static boolean batchMode = false;\n\tpublic static int crossValidationFold;\n\tpublic static int crossFoldCurrent = 0;\n\t\n//\tpublic static String[] getClasses()\n//\t{\n//\t\tString[] classes = getValue(\"classes\").split(\"|\");\n//\t\treturn classes;\n//\t}\n\tpublic static void init()\n\t{\n\t\tif(configFile == null){\n\t\t\t configFile = new Properties();\n\t\t\ttry {\n\t\t\t\t//File currentDirectory = new File(new File(\".\").getAbsolutePath());\n\t\t\t\t\n//\t\t\t\tInputStream config_file = new FileInputStream(currentDirectory.getCanonicalPath()+\n//\t\t\t\t\t\t\"/examples/adrmineevaluation/src/main/resources/configuration.conf\");//\n//\t\t\t\tInputStream config_file = new FileInputStream(currentDirectory.getCanonicalPath()+\n//\t\t\t\t\t\t\"/configuration.conf\");\n\t\t\t\tInputStream config_file =Setting.class.getClassLoader()\n\t\t\t\t\t\t.getResourceAsStream(\"configuration.conf\");\n\t\t\t\tconfigFile.load(config_file);\n\t\t\t} catch (IOException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t\tMinInstancePerLeaf = Integer.parseInt(configFile.getProperty(\"MinInstancePerLeaf\"));\n\t\t\tSVMCostParameter = Double.parseDouble(configFile.getProperty(\"SVMCostParameter\"));\n\t\t\tSVMPolyCParameter = Double.parseDouble(configFile.getProperty(\"SVMPolyCParameter\"));\n\t\t\tReleaseMode = Boolean.parseBoolean(configFile.getProperty(\"ReleaseMode\"));\n\t\t\tSVMKernel = SVMKernels.values()[Integer.parseInt(configFile.getProperty(\"SVMKernel\"))];\n\t\t}\n\t}\n\t\n\tpublic static String getValue(String key){\n\t\tinit();\n\t\treturn configFile.getProperty(key);\n\t}\n\n\tpublic static int getValueInteger(String key) {\n\t\tint result = Integer.parseInt(getValue(key));\n\t\treturn result;\n\t}\n\t\n\n\t\n\t\n}", "public class FileUtil {\n\t/**\n\t * Create new file if not exists\n\t * @param path\n\t * @return true if new file created\n\t */\n\tpublic static boolean createFileIfNotExists(String path) {\n\t\tboolean result = false;\n\t\tFile modelFile = new File(path);\n\t\tif (!modelFile.exists()) {\n\t\t\ttry {\n\t\t\t\tresult = modelFile.createNewFile();\n\t\t\t} catch (IOException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\t \n\t public static void appendLine(String path, String line) throws UnsupportedEncodingException, FileNotFoundException\n\t {\n\t\t File file = new File(path);\n\t\t Writer writer = new BufferedWriter(new OutputStreamWriter(\n\t\t\t new FileOutputStream(file, true), \"UTF-8\"));\n\t\t\t\n\t\t\ttry {\n\t\t\t\twriter.write(line+\"\\n\");\n\t\t\t\twriter.flush();\n\t\t\t\twriter.close();\n\t\t\t} catch (IOException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t }\n\tpublic static void createFilewithFormat(String path,\n\t\t\t\tList<String> contentLines,String format) throws UnsupportedEncodingException, FileNotFoundException {\n\n\t\t\tFile file = new File(path);\n\t\t\tWriter out = new BufferedWriter(new OutputStreamWriter(\n\t\t\t\t\tnew FileOutputStream(file), format));\n\t\t\t\n\t\t\ttry {\n\t\t\t\t\n\t\t\t\tfor(int i=0;i<contentLines.size();i++)\n\t\t\t\t{\n\t\t\t\t\tString line = contentLines.get(i);\n\t\t\t\t\tout.write(line+\"\\n\");\n\t\t\t\t}\n\t\t\t\tout.flush();\n\t\t\t\tout.close();\n\t\t\t} catch (IOException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t}\n\n\t\n\tpublic static void createFileIfNotExists(String path,\n\t\t\tList<String> contentLines) {\n\n\t\tFile file = new File(path);\n\t\tif (!file.exists()) {\n\t\t\ttry {\n\t\t\t\tfile.createNewFile();\n\t\t\t\tBufferedWriter writer = new BufferedWriter(new FileWriter(file));\n\t\t\t\tfor(int i=0;i<contentLines.size();i++)\n\t\t\t\t{\n\t\t\t\t\tString line = contentLines.get(i);\n\t\t\t\t\twriter.write(line+\"\\n\");\n\t\t\t\t}\n\t\t\t\twriter.flush();\n\t\t\t\twriter.close();\n\t\t\t} catch (IOException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n\tpublic static void createFile(String path,\n\t\t\tList<String> contentLines) {\n\n\t\tFile file = new File(path);\n\t\t\n\t\ttry {\n\t\t\tfile.createNewFile();\n\t\t\tBufferedWriter writer = new BufferedWriter(new FileWriter(file));\n\t\t\tfor(int i=0;i<contentLines.size();i++)\n\t\t\t{\n\t\t\t\tString line = contentLines.get(i);\n\t\t\t\twriter.write(line+\"\\n\");\n\t\t\t}\n\t\t\twriter.flush();\n\t\t\twriter.close();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\t\n\t\t\n\t}\n\tpublic static void writeToExistingFile(File file,\n\t\t\tList<String> contentLines) {\n\n\t\t\n\t\ttry {\n\t\t\tBufferedWriter writer = new BufferedWriter(new FileWriter(file));\n\t\t\tfor(int i=0;i<contentLines.size();i++)\n\t\t\t{\n\t\t\t\tString line = contentLines.get(i);\n\t\t\t\twriter.write(line+\"\\n\");\n\t\t\t}\n\t\t\twriter.flush();\n\t\t\twriter.close();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\t\n\t\t\n\t}\n\tpublic static void writeToFile(File file,\n\t\t\tList<String> contentLines) {\n\t\t\n\t\ttry {\n\t\t\tfile.createNewFile();\n\t\t\tBufferedWriter writer = new BufferedWriter(new FileWriter(file));\n\t\t\tfor(int i=0;i<contentLines.size();i++)\n\t\t\t{\n\t\t\t\tString line = contentLines.get(i);\n\t\t\t\twriter.write(line+\"\\n\");\n\t\t\t}\n\t\t\twriter.flush();\n\t\t\twriter.close();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\t\n\t\t\n\t}\n\tpublic static void createFile(String path,\n\t\t\tString content) {\n\n\t\tFile file = new File(path);\n\t\t\n\t\ttry {\n\t\t\tfile.createNewFile();\n\t\t\tBufferedWriter writer = new BufferedWriter(new FileWriter(file));\n\t\t\twriter.write(content+\"\\n\");\n\t\t\twriter.flush();\n\t\t\twriter.close();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\t\n\t\t\n\t}\n\t\n\t/**\n\t * \n\t * @param path\n\t * @return true if created\n\t */\n\tpublic static boolean createFolderIfNotExists(String path) {\n\t\tboolean result = false;\n\t\tFile modelFolder = new File(path);\n\t\tif (!modelFolder.exists() || !modelFolder.isDirectory()) {\n\t\t\tresult = modelFolder.mkdir();\n\t\t}\n\n\t\treturn result;\n\t}\n\tpublic static String createFolderAndGetPath(String path) {\n\t\tboolean result = false;\n\t\tFile modelFolder = new File(path);\n\t\tif (!modelFolder.exists() || !modelFolder.isDirectory()) {\n\t\t\tresult = modelFolder.mkdir();\n\t\t}\n\t\tif (result == true || modelFolder.exists())\n\t\t\treturn path;\n\t\telse\n\t\t\treturn null;\n\t}\n\n\tpublic static String deleteAndCreateFolder(String path) throws IOException {\n\t\t\n\t\tboolean success_del;\n\t\tFile modelFolder = new File(path);\n\t\tsuccess_del = deleteDirectory(modelFolder);\n\t\tif (!success_del) {\n\t\t // Deletion failed\n\t\t\tthrow new IOException();\n\t\t}\n\t\tFile new_modelFolder = new File(path);\n\n\t\tif (new_modelFolder.mkdir()==true)\n\t\t{\n\t\t\treturn path;\n\t\t}\n\t\telse{\n\t\t\tthrow new IOException();\n\t\t}\n\n\t}\n static boolean deleteDirectory(File path) {\n\t if( path.exists() ) {\n\t File[] files = path.listFiles();\n\t for(int i=0; i<files.length; i++) {\n\t if(files[i].isDirectory()) {\n\t deleteDirectory(files[i]);\n\t }\n\t else {\n\t files[i].delete();\n\t }\n\t }\n\t }\n\t return( path.delete() );\n\t }\n\t\n\tpublic static void CopyFileToDirectory(String file_name, String from_directory, String to_directory)\n\t{\n\t \tInputStream inStream = null;\n\t\tOutputStream outStream = null;\n\t \n \ttry{\n \n \t File afile =new File(from_directory+\"/\"+file_name);\n \t File bfile =new File(to_directory+\"/\"+file_name);\n \n \t inStream = new FileInputStream(afile);\n \t outStream = new FileOutputStream(bfile);\n \n \t byte[] buffer = new byte[1024];\n \n \t int length;\n \t //copy the file content in bytes \n \t while ((length = inStream.read(buffer)) > 0){\n \n \t \toutStream.write(buffer, 0, length);\n \n \t }\n \n \t inStream.close();\n \t outStream.close();\n \n \t System.out.println(\"File is copied successful!\");\n \n \t}catch(IOException e){\n \t e.printStackTrace();\n \t}\n\t \n\t}\n\t\n\t/**\n\t * Read whole file content into a string\n\t * @param filePath\n\t * @return The File content\n\t * @throws IOException\n\t */\n\tpublic static String readWholeFile(String filePath) throws IOException\n\t{\n\t\tStringBuffer fileData = new StringBuffer(1000);\n\t\tFileReader fr = new FileReader(filePath);\n BufferedReader reader = new BufferedReader(fr);\n char[] buf = new char[1024];\n int numRead=0;\n while((numRead=reader.read(buf)) != -1){\n String readData = String.valueOf(buf, 0, numRead);\n fileData.append(readData);\n buf = new char[1024];\n }\n reader.close();\n fr.close();\n return fileData.toString();\n\t}\n\t\n\tpublic static FileIterator getFilesInDirectory(String root)\n\t{\n\t\tExtensionFilter filter = new ExtensionFilter(\".txt\");\n\t\tFileIterator file_iterator = new FileIterator(new File(root),\n\t\t\t\tfilter, FileIterator.LAST_DIRECTORY);\n\t\treturn file_iterator;\n\t}\n\tpublic static FileIterator getallFilesInDirectory(String root)\n\t{\n\t\tFileIterator file_iterator = new FileIterator(new File(root),\n\t\t\t\tnull, FileIterator.LAST_DIRECTORY);\n\t\treturn file_iterator;\n\t}\n\tpublic static FileIterator getFilesInDirectory(String root,String extension)\n\t{\n\t\tExtensionFilter filter = new ExtensionFilter(\".\"+extension);\n\t\tFileIterator file_iterator = new FileIterator(new File(root),\n\t\t\t\tfilter, FileIterator.LAST_DIRECTORY);\n\t\treturn file_iterator;\n\t}\n\t\n\tpublic static List<String> loadLineByLine(String file_path) {\n\t\tList<String> lines = new ArrayList<String>();\n\t\ttry {\n\t\t\tFile f = new File(file_path);\n\t\t\tif(!f.exists()) return lines;\n\t\t\tBufferedReader br1 = new BufferedReader(\n\t\t\t\t\tnew FileReader(f));\n\t\t\twhile (br1.ready()) {\n\t\t\t\tString line = br1.readLine();\n\t\t\t\tlines.add(line);\n\t\t\t}\n\t\t\tbr1.close();\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn lines;\n\t}\n\tpublic static List<String> loadLineByLineAndTrim(String file_path) {\n\t\tList<String> lines = new ArrayList<String>();\n\t\ttry {\n\t\t\tFile f = new File(file_path);\n\t\t\tif(!f.exists()) return lines;\n\t\t\tBufferedReader br1 = new BufferedReader(\n\t\t\t\t\tnew FileReader(f));\n\t\t\twhile (br1.ready()) {\n\t\t\t\tString line = br1.readLine();\n\t\t\t\tlines.add(line.trim());\n\t\t\t}\n\t\t\tbr1.close();\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn lines;\n\t}\n\n\n\tpublic static boolean fileExists(String path) {\n\t\tFile modelFile = new File(path);\n\t\treturn modelFile.exists();\n\t}\n\tpublic static String getFilePathInDirectory(String directory, String fileName)\n\t{\n\t\tString file_path = directory;\n\t\tfile_path += \"/\"+fileName;\n\t\treturn file_path;\n\t}\n\tpublic static void logLine(String filePath, String line)\n\t{\n\t\tif(filePath==null)\n\t\t{\n\t\t\tString log = (new Date())+\" : \"+line+\"\\n\";\n\t\t\tSystem.out.print(log);\n\t\t}else\n\t\t{\n\t\t\ttry {\n\t\t\t\t\n\t\t\t\tBufferedWriter writer = new BufferedWriter( new FileWriter( filePath , true ) );\n//\t\t\t\twriter.write((new Date())+\" : \"+line+\"\\n\");\n\t\t\t\twriter.write(line+\"\\n\");\n\t\t\t\twriter.flush();\n\t\t\t\twriter.close();\n\t\t\t} catch (IOException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t}\n\tpublic static String ReadFileInToString(String filePath) throws IOException {\n\t \n //create file object\n File file = new File(filePath);\n BufferedInputStream bin = null;\n String strFileContents = null;\n StringBuffer fileData = new StringBuffer();\n BufferedReader reader = new BufferedReader(\n new FileReader(filePath));\n char[] buf = new char[1024];\n int numRead=0;\n while((numRead=reader.read(buf)) != -1){\n String readData = String.valueOf(buf, 0, numRead);\n fileData.append(readData);\n }\n reader.close();\n return fileData.toString();\n\t}\n\t\n\t\n\n \n\n}", "public class HibernateUtil {\n\t//private static SessionFactory sessionFactory;\n\tprivate static ServiceRegistry serviceRegistry;\n\t// configures settings from hibernate.cfg.xml\n\tpublic static SessionFactory sessionFactory; \n\tpublic static Session loaderSession;\n\tpublic static Session saverSession;\n\tpublic static boolean changeDB=true;\n\tpublic static String db;\n\tpublic static String user;\n\tpublic static String pass;\n\t\n\tstatic{\n\t\t\n\t\tsessionFactory = configureSessionFactory();\n\t\tloaderSession = sessionFactory.openSession();\n\t\tsaverSession = sessionFactory.openSession();\n\t}\n\tstatic boolean inTransaction = false;\n\t\n\t\n\tprivate static SessionFactory configureSessionFactory() throws HibernateException {\n\t\tConfiguration configuration = new Configuration();\n\t configuration.configure();\n\t serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); \n\t sessionFactory = configuration.buildSessionFactory(serviceRegistry);\n\t \n\t return sessionFactory;\n\t}\n\n\tpublic static void changeConfigurationDatabase(String databaseURL, String user, String pass){\n\t \t \n\t Configuration configuration = new Configuration();\n\t\tconfiguration.configure();\n//\t\tserviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); \n//\t\tconfiguration.setProperty(\"hibernate.connection.url\", databaseURL);\n//\t\tconfiguration.setProperty(\"hibernate.connection.username\", user);\n//\t\tconfiguration.setProperty(\"hibernate.connection.password\", pass);\n//\t configuration.configure();\n\t\tconfiguration.setProperty(\"connection.url\", databaseURL);\n\t\tconfiguration.setProperty(\"hibernate.connection.url\", databaseURL);\n\t\tconfiguration.setProperty(\"hibernate.connection.username\", user);\n\t\tconfiguration.setProperty(\"hibernate.connection.password\", pass);\n\t\t\n\t\tconfiguration.getProperty(\"hibernate.connection.url\");\n\t serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); \n\t\t\n\t \n\t sessionFactory = configuration.buildSessionFactory(serviceRegistry);\n\t loaderSession = sessionFactory.openSession();\n\t\tsaverSession = sessionFactory.openSession();\n\t\tMLExample.hibernateSession=loaderSession;\n\t}\n\t/**\n\t * save object status\n\t */\n\tpublic static void save(Object _object, Session session) {\n\t\ttry {\n\t\t\tsession.beginTransaction();\n\t\t\tsession.saveOrUpdate(_object);\n\t\t\tsession.flush();\n\t\t\tsession.getTransaction().commit();\n\t\t} catch (HibernateException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\tpublic static void save(Object _object) {\n\t\tsave(_object, loaderSession);\n\t}\n\t\n\tpublic static List<?> executeReader(String hql)\n\t{\n\t\treturn executeReader(hql, null, null, loaderSession);\n\t}\n\t\n\tpublic static List<?> executeReader(String hql, HashMap<String, Object> params)\n\t{\n\t\treturn executeReader(hql, params, null, loaderSession);\n\t}\n\t\n\tpublic static List<?> executeReader(String hql, HashMap<String, Object> params, Integer limit)\n\t{\n\t\treturn executeReader(hql, params, limit, loaderSession);\n\t}\n\tpublic static List<?> executeReader(String hql, HashMap<String, Object> params, Integer limit, Session session)\n\t{\n\t\tQuery q = session.createQuery(hql);\n\t\t\n\t\tif(params!=null)\n\t\t\tfor(String key :params.keySet())\n\t\t\t{\n\t\t\t\tObject val = params.get(key);\n\t\t\t\tif(val instanceof String)\n\t\t\t\t\tq.setString(key, (String)val);\n\t\t\t\telse\n\t\t\t\t\tq.setInteger(key, (Integer)val);\n\t\t\t}\n\t\tif(limit!=null)\n\t\t\tq.setMaxResults(limit);\n\t\t\n\t\tList<?> result_list = \n\t\t\tq.list();\n\t\t\n\t\treturn result_list;\n\t}\n\t\n\t\n\t\n\tpublic static void executeNonReader(String hql, HashMap<String, Object> params)\n\t{\n\t\tif(!inTransaction)\n\t\t{\n//\t\t\tsession = sessionFactory.openSession();\n\t\t\tsaverSession = clearSession(saverSession);\n\t\t\tsaverSession.beginTransaction();\n\t\t}\n\t\t\n\t\tQuery qr = saverSession.createQuery(hql);\n\t\tif (params!=null)\n\t\tfor(String key :params.keySet())\n\t\t{\n\t\t\tObject val = params.get(key);\n\t\t\tqr.setParameter(key, val);\n\t\t}\n\t\t\n\t\tqr.executeUpdate();\n\t\t\n\t\tif(!inTransaction)\n\t\t{\n\t\t\tsaverSession.flush();\n\t\t\tsaverSession.getTransaction().commit();\n//\t\t\tsession.close();\n\t\t\t\n\t\t}\n\t}\n\t\n\t\n\tpublic static Object getHibernateTemplate() {\n\t\t// TODO Auto-generated method stub\n\t\treturn null;\n\t}\n\tpublic static void executeNonReader(String hql) {\n\t\texecuteNonReader(hql, null);\n\t\t\n\t}\n\tpublic static void startTransaction() {\n\t\tsaverSession = sessionFactory.openSession();\n\t\tsaverSession.beginTransaction();\n\t\tinTransaction = true;\n\t}\n\t\n\t\t \n\t\t\n\tpublic static void endTransaction() {\n\t\tsaverSession.flush();\n\t\tif(!saverSession.getTransaction().wasCommitted())\n\t\t\tsaverSession.getTransaction().commit();\n\t\tsaverSession.close();\n\t\tinTransaction = false;\n\t}\n\tpublic static void clearLoaderSession()\n\t{\n\t\tloaderSession = clearSession(loaderSession);\n\t}\n\tpublic static Session clearSession(Session session)\n\t{\n\t\tif(session!=null && session.isOpen()){\n\t\t\tsession.clear();\n\t\t\tsession.close();\n\t\t}\n\t\tsession= sessionFactory.openSession();\n\t\treturn session;\n\t}\n\t\n\t\n\tpublic static void flushTransaction() {\n\t\tsaverSession.flush();\n\t\tsaverSession.getTransaction().commit();\n\t\t\n\t}\n\tpublic static Object executeGetOneValue(String sql,\n\t\t\tHashMap<String, Object> params) {\n\t\tSession session = sessionFactory.openSession();\n\t\tQuery query = session.createSQLQuery(sql);\n\t\tif (params!=null)\n\t\t\tfor(String key :params.keySet())\n\t\t\t{\n\t\t\t\tObject val = params.get(key);\n\t\t\t\tquery.setParameter(key, val);\n\t\t\t}\n\t\tObject oneVal = query.uniqueResult();\n\t\tsession.clear();\n\t\tsession.close();\n\t\treturn oneVal;\n\t}\n}", "public class StringUtil {\n\tstatic String lemmatizerResourceFolder =\"lemmatiser\";\n\tstatic EngLemmatiser lemmatiser = null;\n\tstatic{\n\t\tinitialize();\n\t}\n\tpublic static void initialize()\n\t{\t\n\t\ttry {\n\t\t\tSystem.out.println(\"start loading the lemmatiser...\");\n\t\t\tSystem.out.println(System.getProperty(\"user.dir\"));\n\t\t\tlemmatiser = new EngLemmatiser(System.getProperty(\"user.dir\")+\"/lemmatiser\", true, false);\n\t\t\tSystem.out.println(\"Lemmatizer loaded\");\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n//\tstatic EngLemmatiser lemmatiser = new EngLemmatiser(\"/rnlp-stb/nlpdata/lemmatiser\",\ttrue, false);\n\n\t/**\n\t * \n\t * @param inputString\n\t * @return MD5 hash of given string\n\t * @throws UnsupportedEncodingException\n\t * @throws NoSuchAlgorithmException\n\t */\n\tpublic static String getStringDigest(String inputString)\n\t\t\tthrows UnsupportedEncodingException, NoSuchAlgorithmException {\n\t\tMessageDigest md = MessageDigest.getInstance(\"MD5\");\n\t\tmd.update(inputString.getBytes(), 0, inputString.length());\n\n\t\treturn new BigInteger(1, md.digest()).toString(16);\n\t}\n\n\t/**\n\t * Customized definition of stop words for word\n\t * @param word\n\t * @return\n\t */\n\tpublic static List<String> customGoogleCommonWord = FileUtil.loadLineByLine\n\t\t\t(\"/home/azadeh/projects/drug-effect-ext/data/abbvie-experiments/google-comon-words.txt\");\n\tpublic static boolean isStopWord(String word){\n\t\tboolean isStopWord = false;\n\t\t\n\t\tif(word.length() < 2\n\t\t\t\t||\tStopwords.isStopword(word)\n\t\t\t\t|| customGoogleCommonWord.contains(word)\n\t\t\t\t|| word.matches(\"\\\\W+\")\n\t\t\t\t)\n\t\t\tisStopWord = true;\n\t\t\n\t\treturn isStopWord;\n\t}\n\tpublic static String removeStopWords(String text){\n\t\tboolean isStopWord = false;\n\t\tString[] tokens = text.split(\" \");\n\t\tString new_text = \"\";\n\t\t\n\t\tfor (String token:tokens)\n\t\t{\n\t\t\tif(token.length() < 2\n\t\t\t\t\t||\tStopwords.isStopword(token)\n\t\t\t\t\t|| customGoogleCommonWord.contains(token)\n\t\t\t\t\t|| token.matches(\"\\\\W+\")\n\t\t\t\t\t)\n\t\t\t\tcontinue;\n\t\t\telse\n\t\t\t\tnew_text=new_text+\" \"+token;\n\t\t\t\n\t\t}\n\t\t\n\t\treturn new_text.trim();\n\t}\n\t\n\n\t\n\t/**\n\t * Porter stem\n\t * @param word\n\t * @return stemmed word\n\t */\n\tpublic static String getWordPorterStem(String word)\n\t{\n\t\tPorterStemmer stemmer = new PorterStemmer();\n\t\tString stemmed_word = stemmer.stem(word).toLowerCase();\n\t\treturn stemmed_word;\n\t}\n\tpublic static String prepareSQLString(String sqlString) {\n\t\tsqlString = sqlString.replace(\"\\\\\", \"\\\\\\\\\").\n\t\t\treplace(\"'\", \"''\").\n\t\t\treplace(\"%\", \"\\\\%\").\n\t\t\treplace(\"_\", \"\\\\_\");\n\t\treturn sqlString;\n\t}\n\npublic static String castForRegex(String textContent) {\n\t\t\n\t\treturn textContent.replace(\"\\\\\",\"\\\\\\\\\").replace(\"/\",\"\\\\/\").replace(\"*\", \"\\\\*\").replace(\"+\", \"\\\\+\").replace(\".\", \"\\\\.\").replace(\"?\", \"\\\\?\")\n\t\t\t.replace(\")\", \"\\\\)\").replace(\"{\", \"\\\\{\").replace(\"}\", \"\\\\}\")\n\t\t\t.replace(\"(\", \"\\\\(\").replace(\"[\", \"\\\\[\").replace(\"]\", \"\\\\]\").replace(\"%\", \"\\\\%\");\n\t}\npublic static String decastRegex(String textContent) {\n\t\t\n\t\treturn textContent.replace(\"\\\\\\\\\",\"\\\\\").replace(\"\\\\/\",\"/\").replace(\"\\\\*\", \"*\").replace(\"\\\\+\", \"+\").replace(\"\\\\.\", \".\").replace(\"\\\\?\", \"?\")\n\t\t\t.replace(\"\\\\)\", \")\").replace(\"\\\\_\", \"_\")\n\t\t\t.replace(\"\\\\{\", \"{\").replace(\"\\\\}\", \"}\").replace(\"\\\\(\", \"(\").\n\t\t\treplace(\"\\\\[\", \"[\").replace(\"\\\\]\", \"]\").replace(\"\\\\%\", \"%\");\n\t}\n\t\n\tpublic static String getTermByTermPorter(String phrase)\n\t{\n\t\tString[] words = phrase.split(\" \");\n\t\tString rootString = \"\";\n\t\tfor(int i=0;i<words.length;i++){\n\t\t\trootString += StringUtil.getWordPorterStem(words[i])+\" \";\n\t\t}\n\t\treturn rootString.trim();\n\t}\n\t\n\tpublic static String compress(String text) {\n\t\treturn text.replace(\" \", \"\").replace(\" \", \"\");\n\t}\n\tstatic HashMap<String, String> lemmaCache = new HashMap<String, String>();\n\n\tpublic static String getTermByTermWordnet(String phrase)\n\t{\n\t\tString[] words = phrase.split(\" \");\n\t\tString rootString = \"\";\n\t\tfor(int i=0;i<words.length;i++)\n\t\t{\n\t\t\tString lemma = lemmaCache.get(words[i]);\n\t\t\tif (words[i].equals(lemma)\n\t\t\t\t\t&& lemma.matches(\".*ioning$\"))\n\t\t\t{\n\t\t\t\tlemma=lemma.replaceAll(\"ioning$\", \"ion\");\n\t\t\t}\n\t\t\tif(lemma == null)\n\t\t\t{\n\t\t\t\tlemma = lemmatiser.stem(words[i]);\n\t\t\t\tlemmaCache.put(words[i], lemma);\n\t\t\t}\n\t\t\trootString = rootString.concat(lemma+\" \");\n\t\t}\n\t\t\n\t\treturn rootString.trim();\n\t}\n\tpublic static String getWordLemma(String word)\n\t{\n\t\tString word_lemma= word;\n\n\t\tword_lemma= lemmatiser.stem(word);\n\t\treturn word_lemma;\n\t}\n\n\tpublic static String orderStringAlphabetically(String text) {\n\t\tString words[] =text.split(\" \");\n String t;\n int n = words.length;\n int i,j,c;\n for (i=0; i<n-1; i++) \n {\n for (j=i+1; j<n; j++) \n {\n c = words[i].compareTo(words[j]);\n if (c >0) \n {\n t = words[i];\n words[i] = words[j];\n words[j] = t; \n } \n }\n }\n String ordered_words = \"\";\n for (i=0; i<n ;i++) \n {\n \tordered_words +=words[i]+\" \";\n }\n\t\treturn ordered_words.trim();\n\t}\n\n\tpublic static String cleanString(String text) {\n\t\tString clean = text.replaceAll(\"[\\\\d[^\\\\w\\\\s]]+\", \" \").replaceAll(\"(\\\\s{2,})\", \" \").toLowerCase();\n\t\treturn clean.trim();\n\t}\n}", "public interface IDocumentAnalyzer {\n\t\n\t/**\n\t * Process given documents and load them into Artifact table\n\t * @param rootPath root of all documents to be processed\n\t * @return number of processed documents\n\t * @throws Exception\n\t */\n\tpublic int processDocuments(String rootPath) throws Exception;\n\n\tpublic int processDocuments(String rootPath, String corpusName);\n}", "public class Tokenizer {\n\tString txt_file_path;\n\tString tokenization_file;\n\tString original_txt_content = \"\";\n\tString compressedText;\n\tpublic static void main(String[] args) throws SQLException\n\t{\n\t\tfixDashSplitted();\n\t}\n\tstatic TokenizerFactory<Word> tf;\n\t\n\tpublic static List<Word> getTokens(String sentence)\n\t{\n\t\tif(tf == null)\n\t\t\ttf = PTBTokenizer.factory(false, new WordTokenFactory());\n\t\t\n\t\tList<Word> tokens_words = tf.getTokenizer(new StringReader(sentence)).tokenize();\n\t\t\n\t\t\n\t\treturn tokens_words;\n\t}\n\t\n\tpublic static void fixDashSplitted() throws SQLException\n\t{\n//\t\tString q = \"SELECT * from Artifact where text_content like '%-%' and artifact_type = 'Word'\";\n//\t\tResultSet artifacts = Util.db.executeReader(q);\n//\t\twhile(artifacts.next())\n//\t\t{\n//\t\t\tint artifact_id = artifacts.getInt(\"artifact_id\");\n//\t\t\tArtifact curArti = new Artifact(artifact_id);\n//\t\t\tfixMergedNameEntity(curArti);\n//\t\t}\n\t}\n\tpublic ArrayList<String> paragraphs = new ArrayList<String>();\n\tpublic HashMap<Integer, String> sentences = new HashMap<Integer, String>();\n\tpublic HashMap<Integer,List<Integer>> sentences_tokens_indexes = new HashMap<Integer, List<Integer>>();\n\tpublic HashMap<Integer,List<Word>> sentences_tokens = new HashMap<Integer,List<Word>>();\n\t\n\tpublic static void fixMergedNameEntity(Artifact curArtifact) throws SQLException\n\t{\n//\t\tString originalContent = curArtifact.getTextContent();\n//\t\tString[] parts = originalContent.split(\"-\");\n//\t\tString previousContent = \"\";\n//\t\tfor(int i=0;i<parts.length;i++)\n//\t\t{\n//\t\t\tString content = parts[i];\n//\t\t\tint j=i;\n//\t\t\tdo\n//\t\t\t{\n//\t\t\t\tif((NameEntityTable.possibleNameEntity(content)||\n//\t\t\t\t\t\tEventTriggers.isPossibleTrigger(content))\n//\t\t\t\t\t\t&& !content.equals(originalContent) &&\n//\t\t\t\t\t\tcontent.length()>1)\n//\t\t\t\t{\n//\t\t\t\t\tUtil.log(\"Fixing:\"+originalContent, Level.INFO);\n//\t\t\t\t\tif(i==0)\n//\t\t\t\t\t{//NE is at the beginning\n//\t\t\t\t\t\t//shorten current artifact\n//\t\t\t\t\t\tcurArtifact.setTextContent(content);\n//\t\t\t\t\t\t//add a new artifact at the end \n//\t\t\t\t\t\tString remainingContent = \"\";\n//\t\t\t\t\t\tfor(int k=j+1;k<parts.length;k++){\n//\t\t\t\t\t\t\tif(!remainingContent.equals(\"\"))\n//\t\t\t\t\t\t\t\tremainingContent+= \"-\";\n//\t\t\t\t\t\t\tremainingContent+=parts[k];\n//\t\t\t\t\t\t}\n//\t\t\t\t\t\t\n//\t\t\t\t\t\tArtifact dashArtifact = new Artifact(\"-\",\n//\t\t\t\t\t\t\t\tType.Word, curArtifact.associatedFilePath,\n//\t\t\t\t\t\t\t\tcurArtifact.getStartIndex()+content.length(),\n//\t\t\t\t\t\t\t\tcurArtifact.getParentArtifact());\n//\t\t\t\t\t\tif(remainingContent.equals(\"\"))\n//\t\t\t\t\t\t{\n//\t\t\t\t\t\t\tdashArtifact.setNextArtifact(curArtifact.getNextArtifact());\n//\t\t\t\t\t\t\tcurArtifact.setNextArtifact(dashArtifact);\n//\t\t\t\t\t\t}else{\n//\t\t\t\t\t\t\tArtifact neArtifact = new Artifact(remainingContent,\n//\t\t\t\t\t\t\t\t\tType.Word, curArtifact.associatedFilePath,\n//\t\t\t\t\t\t\t\t\tcurArtifact.getStartIndex()+content.length()+1,\n//\t\t\t\t\t\t\t\t\tcurArtifact.getParentArtifact());\n//\t\t\t\t\t\t\tneArtifact.setNextArtifact(curArtifact.getNextArtifact());\n//\t\t\t\t\t\t\tcurArtifact.setNextArtifact(dashArtifact);\n//\t\t\t\t\t\t\tdashArtifact.setNextArtifact(neArtifact);\n//\t\t\t\t\t\t}\n//\t\t\t\t\t\t\n//\t\t\t\t\t\t\n//\t\t\t\t\t}\n//\t\t\t\t\tif(parts.length>1 && \n//\t\t\t\t\t\t\ti==(parts.length-1))\n//\t\t\t\t\t{//NE is at the end\n//\t\t\t\t\t\t//shorten current artifact\n//\t\t\t\t\t\tArtifact neArtifact = new Artifact(content,\n//\t\t\t\t\t\t\t\tType.Word, curArtifact.associatedFilePath,\n//\t\t\t\t\t\t\t\tcurArtifact.getStartIndex()+previousContent.length()+1,\n//\t\t\t\t\t\t\t\tcurArtifact.getParentArtifact());\n//\t\t\t\t\t\t\n//\t\t\t\t\t\tif(previousContent.equals(\"\"))\n//\t\t\t\t\t\t{\n//\t\t\t\t\t\t\tcurArtifact.setTextContent(\"-\");\n//\t\t\t\t\t\t\tneArtifact.setNextArtifact(curArtifact.getNextArtifact());\n//\t\t\t\t\t\t\tcurArtifact.setNextArtifact(neArtifact);\n//\t\t\t\t\t\t}else{\n//\t\t\t\t\t\t\tcurArtifact.setTextContent(previousContent);\n//\t\t\t\t\t\t\t//add a new artifact at the end \n//\t\t\t\t\t\t\t\n//\t\t\t\t\t\t\tArtifact dashArtifact = \n//\t\t\t\t\t\t\t\tnew Artifact(\"-\", Type.Word, curArtifact.associatedFilePath,\n//\t\t\t\t\t\t\t\t\tcurArtifact.getStartIndex()+previousContent.length(),\n//\t\t\t\t\t\t\t\t\tcurArtifact.getParentArtifact());\n//\t\t\t\t\t\t\t\n//\t\t\t\t\t\t\tneArtifact.setNextArtifact(curArtifact.getNextArtifact());\n//\t\t\t\t\t\t\tcurArtifact.setNextArtifact(dashArtifact);\n//\t\t\t\t\t\t\tdashArtifact.setNextArtifact(neArtifact);\n//\t\t\t\t\t\t}\n//\t\t\t\t\t}\n//\t\t\t\t\treturn;\n//\t\t\t\t}\n//\t\t\t\tj++;\n//\t\t\t\tif(j<parts.length)\n//\t\t\t\t\tcontent+=\"-\"+parts[j];\n//\t\t\t}while(j<parts.length);\n//\t\t\tif(!previousContent.equals(\"\"))\n//\t\t\t\tpreviousContent+=\"-\";\n//\t\t\tpreviousContent += parts[i];\n//\t\t}\n\t}\n\tpublic Tokenizer(String associatedFilePath) throws IOException {\n\t\ttxt_file_path = associatedFilePath;\n\t\ttokenization_file = txt_file_path.replace(\".txt\", \".tok\");\n\t\tif(FileUtil.fileExists(tokenization_file))\n\t\t\tprocessFileWithTokenization(tokenization_file);\n\t\telse\n\t\t\tprocessFile();\n\t}\n\t\n\t\n\tpublic void processFile() throws IOException{\n\t\tList<String> lines = FileUtil.loadLineByLine(txt_file_path);\n\t\t\n\t\tint sentence_start=0;\n\t\tfor(int line_number = 0;line_number<lines.size();line_number++){\n\t\t\tString line = lines.get(line_number);\n\t\t\tList<Word> tokensInSentence = getTokens(line);\n\t\t\tArrayList<Integer> tokens_indexes = new ArrayList<Integer>();\n\t\t\t\n\t\t\tfor(int token_index = 0;token_index<tokensInSentence.size();token_index++)\n\t\t\t{\n\t\t\t\ttokens_indexes.add(tokensInSentence.get(token_index).beginPosition()+sentence_start+line_number+1);\n\t\t\t}\n\t\t\t\n\t\t\tsentences_tokens_indexes.put(line_number, tokens_indexes);\n\t\t\tsentences_tokens.put(line_number, tokensInSentence);\n\t\t\tsentences.put(line_number, line);\n\t\t\tsentence_start+= line.length();\n\t\t}\n\t\t\n\t}\n\t\n\tpublic void processFileWithTokenization(String tokenizationFilePath) throws IOException{\n\t\tList<String> lines_tokenized = \n\t\t\tFileUtil.loadLineByLine(tokenizationFilePath);\n\t\t\n\t\toriginal_txt_content = \n\t\t\tFileUtil.readWholeFile(txt_file_path).replaceAll(\"\\\\s+\", \" \");\n\t\tcompressedText = \n\t\t\toriginal_txt_content.replaceAll(\" |\\\\n\", \"\");\n\t\tif(compressedText.equals(\"\")) return;\n\t\t\n\t\tint curIndex = 0;\n\t\tString compressed_original_sofar = \"\"+original_txt_content.charAt(curIndex);\n\t\tString compressed_tokenized_sofar = \"\";\n\t\tint sentence_start=0;\n\t\tfor(int line_number = 0;line_number<lines_tokenized.size();line_number++){\n\t\t\tString line = lines_tokenized.get(line_number);\n\t\t\tList<Word> tokensInSentence = new ArrayList<Word>();\n\t\t\tString[] tokensInSentence_str = line.split(\" \");\n\t\t\tArrayList<Integer> tokens_indexes = new ArrayList<Integer>();\n\t\t\t\n\t\t\tfor(int token_index = 0;token_index<tokensInSentence_str.length;token_index++)\n\t\t\t{\n\t\t\t\tif(!tokensInSentence_str[token_index].equals(\"\")) \n\t\t\t\t{\n\t\t\t\t\tString tmp_compressed_tokenized_sofar = \n\t\t\t\t\t\tcompressed_tokenized_sofar + \n\t\t\t\t\t\ttokensInSentence_str[token_index].charAt(0);\n\t\t\t\t\twhile(!compressed_original_sofar.equals(\n\t\t\t\t\t\t\ttmp_compressed_tokenized_sofar))\n\t\t\t\t\t{\n\t\t\t\t\t\tdo{\n\t\t\t\t\t\t\tcurIndex++;\n\t\t\t\t\t\t\tcompressed_original_sofar += \n\t\t\t\t\t\t\t\toriginal_txt_content.charAt(curIndex);\n\t\t\t\t\t\t}while(original_txt_content.charAt(curIndex) == ' ');\n\t\t\t\t\t\tcompressed_original_sofar = \n\t\t\t\t\t\t\tcompressed_original_sofar.replaceAll(\" |\\\\n\", \"\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\ttokens_indexes.add(curIndex);\n\t\t\t\ttokensInSentence.add(new \n\t\t\t\t\t\tWord(tokensInSentence_str[token_index], curIndex, \n\t\t\t\t\t\t\t\tcurIndex+tokensInSentence_str[token_index].length()));\n\t\t\t\tcompressed_tokenized_sofar += tokensInSentence_str[token_index];\n\t\t\t}\n\t\t\t\n\t\t\tsentences_tokens_indexes.put(line_number, tokens_indexes);\n\t\t\tsentences_tokens.put(line_number, tokensInSentence);\n\t\t\tsentences.put(line_number, line);\n\t\t\tsentence_start+= line.length();\n\t\t}\n\t\t\n\t}\n\tpublic HashMap<Integer, String> getSentences() {\n\t\t\n\t\treturn sentences;\n\t}\n\n}", "public class Preprocess {\r\n\t\r\n\tprivate HashMap<Integer, String> sentenceIndexMap;\r\n\t\r\n\tprivate String tokenizedText=\"\";\r\n private HashMap<Integer, List<HasWord>> sentTokensMap = \r\n \t\tnew HashMap<Integer, List<HasWord>>();\r\n \r\n private HashMap<Integer, HashMap<Integer, Integer>> tokenStartCharMap = \r\n \t\tnew HashMap<Integer, HashMap<Integer,Integer>>();\r\n\t\r\n private HashMap<Integer, HashMap<Integer, Integer>> tokenEndtCharMap = \r\n \t\tnew HashMap<Integer, HashMap<Integer,Integer>>();\r\n\tpublic Preprocess(String text)\r\n\t{\r\n\t\tpreprocessText(text);\r\n\t}\r\n\r\n\tpublic void preprocessText(String text)\r\n\t{\t\t\t\r\n\t\tReader reader = new StringReader(text);\r\n\t\t\r\n\t DocumentPreprocessor dp = new DocumentPreprocessor(reader);\r\n\t \r\n\t HashMap<Integer, String> sentences = new HashMap<Integer, String>();\r\n\t \t \r\n \t Iterator<List<HasWord>> it = dp.iterator();\r\n \t Integer sent_index = 0;\r\n \t \r\n \t HashMap<Integer, List<HasWord>> sent_tokens = \r\n \t \t\tnew HashMap<Integer, List<HasWord>>();\r\n \t \r\n\t while (it.hasNext()) {\r\n\t StringBuilder sentenceSb = new StringBuilder();\r\n\t \r\n\t List<HasWord> sentence = it.next();\r\n\t for (HasWord token : sentence) {\r\n\t \t \r\n\t if(sentenceSb.length()>=1) {\r\n\t sentenceSb.append(\" \");\r\n\t }\r\n\t sentenceSb.append(token);\r\n\t \r\n\t }\r\n\t sentences.put(sent_index,sentenceSb.toString());\r\n\t sent_tokens.put(sent_index, sentence);\r\n\t sent_index++;\r\n\t \r\n\t }\r\n\t setSentenceIndexMap(sentences);\r\n\t for(String sentence:sentences.values()) {\r\n\r\n\t setTokenizedText(getTokenizedText() + sentence +\" \");\r\n\t }\r\n\t setTokenizedText(getTokenizedText().replace(\" $\", \"\").trim());\r\n\t setSentTokensMap(sent_tokens);\r\n\t setTokensCharIndex();\r\n\t}\r\n\r\n\tpublic void setTokenizedText(String tokenizedText) {\r\n\t\tthis.tokenizedText = tokenizedText;\r\n\t}\r\n\tpublic String getTokenizedText() {\r\n\t\treturn tokenizedText;\r\n\t}\r\n\r\n\tpublic void setSentTokensMap(HashMap<Integer, List<HasWord>> sentTokensMap) {\r\n\t\tthis.sentTokensMap = sentTokensMap;\r\n\t}\r\n\tpublic HashMap<Integer, List<HasWord>> getSentTokensMap() {\r\n\t\treturn sentTokensMap;\r\n\t}\r\n\t\r\n\tpublic void setTokensCharIndex()\r\n\t{\r\n\r\n\t\tHashMap<Integer, HashMap<Integer, Integer>> startCharOffsets = \r\n\t\t\tnew HashMap<Integer, HashMap<Integer,Integer>>();\r\n\t\t\r\n\t\tHashMap<Integer, HashMap<Integer, Integer>> endCharOffsets = \r\n\t\t\tnew HashMap<Integer, HashMap<Integer,Integer>>();\r\n\t\t\r\n\t\tint currentCharOffset=0;\r\n\t\tfor (Integer sent_index:sentTokensMap.keySet())\r\n\t\t{\r\n\t\t\tList<HasWord> tokens = sentTokensMap.get(sent_index);\r\n\t\t\t\r\n\t\t\tHashMap<Integer, Integer> token_start_char_map = new HashMap<Integer, Integer>();\r\n\t\t\tHashMap<Integer, Integer> token_end_char_map = new HashMap<Integer, Integer>();\r\n\t\t\t\r\n\t\t\tfor(int i=0;i<tokens.size();i++)\r\n\t\t\t{\r\n\t\t\t\tString token = tokens.get(i).toString();\r\n\t\t\t\ttoken_start_char_map.put(i, currentCharOffset);\r\n\t\t\t\ttoken_end_char_map.put(i, currentCharOffset+token.length()-1);\r\n\t\t\t\t\r\n\t\t\t\tcurrentCharOffset+=token.length()+1;\r\n\t\t\t}\r\n\t\t\tstartCharOffsets.put(sent_index, token_start_char_map);\r\n\t\t\tendCharOffsets.put(sent_index, token_end_char_map);\r\n\t\t\t\r\n\t\t}\r\n\t\tsetTokenStartCharMap(startCharOffsets);\r\n\t\tsetTokenEndtCharMap(endCharOffsets);\r\n\r\n\t}\r\n\tpublic int getTokenStartCharIndex(Integer sentOffset, Integer charIndex)\r\n\t{\r\n\t\tint startChar = \r\n\t\t tokenStartCharMap.get(sentOffset).get(charIndex);\r\n\t\treturn startChar;\r\n\t\t\r\n\t}\r\n\tpublic int getTokenEndCharIndex(Integer sentOffset, Integer charIndex)\r\n\t{\r\n\t\tint endChar = \r\n\t\t getTokenEndtCharMap().get(sentOffset).get(charIndex);\r\n\t\treturn endChar;\r\n\t\t\r\n\t}\r\n\tpublic void setTokenStartCharMap(HashMap<Integer, HashMap<Integer, Integer>> tokenStartCharMap) {\r\n\t\tthis.tokenStartCharMap = tokenStartCharMap;\r\n\t}\r\n\tpublic HashMap<Integer, HashMap<Integer, Integer>> getTokenStartCharMap() {\r\n\t\treturn tokenStartCharMap;\r\n\t}\r\n\tpublic void setTokenEndtCharMap(HashMap<Integer, HashMap<Integer, Integer>> tokenEndtCharMap) {\r\n\t\tthis.tokenEndtCharMap = tokenEndtCharMap;\r\n\t}\r\n\tpublic HashMap<Integer, HashMap<Integer, Integer>> getTokenEndtCharMap() {\r\n\t\treturn tokenEndtCharMap;\r\n\t}\r\n\tpublic void setSentenceIndexMap(HashMap<Integer, String> sentenceIndexMap) {\r\n\t\tthis.sentenceIndexMap = sentenceIndexMap;\r\n\t}\r\n\tpublic HashMap<Integer, String> getSentenceIndexMap() {\r\n\t\treturn sentenceIndexMap;\r\n\t}\r\n\r\n\r\n}\r", "public class TwitterPreprocessing {\n\tpublic static void main(String[] args)\n\t{\n\t\t\n\t}\n\n//\t@humarakausar hey humara! #smxchat\n\tpublic static String filterTweet(String origTweet)\n\t{\n\t\tString filtered = \"\";\n\t\t\n\t\torigTweet = origTweet.replaceAll(\"’\", \"'\");\n//\t\tfiltered = origTweet.replaceAll(\"@[\\\\w|\\\\d]+\", \"targetuser\").replaceAll(\"#\", \"\").replaceAll(\"\\\"\", \"\").replaceAll(\"\\\\*\", \"\").replaceAll(\"�\", \"\");\n\t\tfiltered = origTweet.replaceAll(\"@\\\\s?[\\\\w|\\\\d]+\", \"@ username\").replaceAll(\"\\\"\", \"\").replaceAll(\"\\\\*\", \"\").replaceAll(\"�\", \"\");\n\t\t\n\t\tfiltered = filtered.replaceAll(\"#\", \" # \").replaceAll(\"^\\\"\", \"\").replaceAll(\"\\\"$\", \"\").replaceAll(\" +\", \" \");\n\t\treturn filtered;\n\t}\n\n}" ]
import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.prefs.PreferenceChangeEvent; import rainbownlp.core.Artifact; import rainbownlp.core.Setting; import rainbownlp.util.FileUtil; import rainbownlp.util.HibernateUtil; import rainbownlp.util.StringUtil; import rainbownlp.analyzer.IDocumentAnalyzer; import rainbownlp.analyzer.Tokenizer; import edu.stanford.nlp.ling.HasWord; import edu.stanford.nlp.ling.Word; import edu.stanford.nlp.process.PTBTokenizer; import preprocessutils.Preprocess; import preprocessutils.TwitterPreprocessing;
package edu.asu.diego.loader; public class DocumentAnalyzer implements IDocumentAnalyzer{ public boolean isForDemo =false;
List<Artifact> loadedSentences = new ArrayList<>();
0
cattaka/AdapterToolbox
example/src/main/java/net/cattaka/android/adaptertoolbox/example/FizzBuzzExampleActivity.java
[ "public class ScrambleAdapter<T> extends AbsScrambleAdapter<\n ScrambleAdapter<T>,\n ScrambleAdapter<?>,\n RecyclerView.ViewHolder,\n ForwardingListener<ScrambleAdapter<?>, RecyclerView.ViewHolder>,\n T\n > {\n private Context mContext;\n private List<T> mItems;\n\n private ListenerRelay<ScrambleAdapter<?>, RecyclerView.ViewHolder> mListenerRelay;\n\n @SafeVarargs\n public ScrambleAdapter(\n @NonNull Context context,\n @NonNull List<T> items,\n @Nullable ListenerRelay<ScrambleAdapter<?>,\n RecyclerView.ViewHolder> listenerRelay,\n @NonNull IViewHolderFactory<ScrambleAdapter<?>,\n RecyclerView.ViewHolder,\n ForwardingListener<ScrambleAdapter<?>, RecyclerView.ViewHolder>,\n ?\n >... iViewHolderFactories\n ) {\n this(context, items, listenerRelay, Arrays.asList(iViewHolderFactories));\n }\n\n public ScrambleAdapter(\n @NonNull Context context,\n @NonNull List<T> items,\n @Nullable ListenerRelay<ScrambleAdapter<?>,\n RecyclerView.ViewHolder> listenerRelay,\n @NonNull List<? extends IViewHolderFactory<ScrambleAdapter<?>,\n RecyclerView.ViewHolder,\n ForwardingListener<ScrambleAdapter<?>, RecyclerView.ViewHolder>,\n ?\n >> iViewHolderFactories\n ) {\n super(iViewHolderFactories);\n this.mContext = context;\n this.mItems = items;\n this.mListenerRelay = listenerRelay;\n }\n\n public Context getContext() {\n return mContext;\n }\n\n @Override\n public ForwardingListener<ScrambleAdapter<?>, RecyclerView.ViewHolder> createForwardingListener(IViewHolderFactory<ScrambleAdapter<?>, RecyclerView.ViewHolder, ForwardingListener<ScrambleAdapter<?>, RecyclerView.ViewHolder>, ?> viewHolderFactory) {\n ForwardingListener<ScrambleAdapter<?>, RecyclerView.ViewHolder> forwardingListener = viewHolderFactory.createForwardingListener();\n if (forwardingListener != null) {\n forwardingListener.setListenerRelay(mListenerRelay);\n }\n return forwardingListener;\n }\n\n @NonNull\n @Override\n public RecyclerView.ViewHolder createNullViewHolder() {\n View view = new View(mContext);\n return new RecyclerView.ViewHolder(view) {\n };\n }\n\n @Override\n public T getItemAt(int position) {\n return mItems.get(position);\n }\n\n public List<T> getItems() {\n return mItems;\n }\n\n @Override\n public int getItemCount() {\n return mItems.size();\n }\n\n public static abstract class AbsViewHolderFactory<EVH extends RecyclerView.ViewHolder>\n implements IViewHolderFactory<\n ScrambleAdapter<?>,\n RecyclerView.ViewHolder,\n ForwardingListener<ScrambleAdapter<?>, RecyclerView.ViewHolder>,\n EVH\n > {\n\n @Override\n public boolean isAssignable(@NonNull ScrambleAdapter<?> adapter, Object object) {\n return isAssignable(object);\n }\n\n public abstract boolean isAssignable(Object object);\n\n @Override\n public void onBindViewHolder(@NonNull ScrambleAdapter<?> adapter, @NonNull EVH holder, int position, @Nullable Object object, List<Object> payloads) {\n this.onBindViewHolder(adapter, holder, position, object);\n }\n\n @Override\n public void onBindViewHolder(@NonNull ScrambleAdapter<?> adapter, @NonNull EVH holder, int position, @Nullable Object object) {\n // override me\n }\n\n @Override\n public ForwardingListener<ScrambleAdapter<?>, RecyclerView.ViewHolder> createForwardingListener() {\n return new ForwardingListener<>();\n }\n\n public ClassicForwardingListener<ScrambleAdapter<?>, RecyclerView.ViewHolder> createClassicForwardingListener() {\n return new ClassicForwardingListener<>();\n }\n\n @Override\n public boolean onFailedToRecycleView(@NonNull ScrambleAdapter<?> adapter, @NonNull RecyclerView.ViewHolder holder) {\n // no-op\n return false;\n }\n\n @Override\n public void onViewAttachedToWindow(@NonNull ScrambleAdapter<?> adapter, @NonNull RecyclerView.ViewHolder holder) {\n // no-op\n }\n\n @Override\n public void onViewDetachedFromWindow(@NonNull ScrambleAdapter<?> adapter, @NonNull RecyclerView.ViewHolder holder) {\n // no-op\n }\n\n @Override\n public void onViewRecycled(@NonNull ScrambleAdapter<?> adapter, @NonNull RecyclerView.ViewHolder holder) {\n // no-op\n }\n }\n}", "public class ListenerRelay<\n A extends RecyclerView.Adapter<? extends VH>,\n VH extends RecyclerView.ViewHolder\n > {\n\n /**\n * @see android.view.View.OnClickListener\n */\n public void onClick(@NonNull RecyclerView recyclerView, @NonNull A adapter, @NonNull VH vh, @NonNull View view) {\n }\n\n /**\n * @see android.view.View.OnLongClickListener\n */\n public boolean onLongClick(@NonNull RecyclerView recyclerView, @NonNull A adapter, @NonNull VH vh, @NonNull View view) {\n return false;\n }\n\n /**\n * @see RadioGroup.OnCheckedChangeListener\n */\n public void onCheckedChanged(@NonNull RecyclerView recyclerView, @NonNull A adapter, @NonNull VH vh, RadioGroup group, int checkedId) {\n }\n\n /**\n * @see android.widget.CompoundButton.OnCheckedChangeListener\n */\n public void onCheckedChanged(@NonNull RecyclerView recyclerView, @NonNull A adapter, @NonNull VH vh, @NonNull CompoundButton buttonView, boolean isChecked) {\n }\n\n /**\n * @see android.widget.SeekBar.OnSeekBarChangeListener\n */\n public void onProgressChanged(@NonNull RecyclerView recyclerView, @NonNull A adapter, @NonNull VH vh, @NonNull SeekBar seekBar, int progress, boolean fromUser) {\n }\n\n /**\n * @see android.widget.SeekBar.OnSeekBarChangeListener\n */\n public void onStartTrackingTouch(@NonNull RecyclerView recyclerView, @NonNull A adapter, @NonNull VH vh, @NonNull SeekBar seekBar) {\n }\n\n /**\n * @see android.widget.SeekBar.OnSeekBarChangeListener\n */\n public void onStopTrackingTouch(@NonNull RecyclerView recyclerView, @NonNull A adapter, @NonNull VH vh, @NonNull SeekBar seekBar) {\n }\n\n /**\n * @see android.widget.AdapterView.OnItemSelectedListener\n */\n public void onNothingSelected(@NonNull RecyclerView recyclerView, @NonNull A adapter, @NonNull VH vh, @NonNull AdapterView<?> parent) {\n\n }\n\n /**\n * @see android.widget.AdapterView.OnItemSelectedListener\n */\n public void onItemSelected(@NonNull RecyclerView recyclerView, @NonNull A adapter, @NonNull VH vh, @NonNull AdapterView<?> parent, @NonNull View view, int position, long id) {\n }\n\n /**\n * @see android.widget.TextView.OnEditorActionListener\n */\n public boolean onEditorAction(@NonNull RecyclerView recyclerView, @NonNull A adapter, @NonNull VH vh, @NonNull TextView v, int actionId, KeyEvent event) {\n return false;\n }\n\n /**\n * @see android.text.TextWatcher\n */\n public void beforeTextChanged(@NonNull RecyclerView recyclerView, @NonNull A adapter, @NonNull VH vh, @NonNull TextView v, @NonNull CharSequence s, int start, int count, int after) {\n }\n\n /**\n * @see android.text.TextWatcher\n */\n public void onTextChanged(@NonNull RecyclerView recyclerView, @NonNull A adapter, @NonNull VH vh, @NonNull TextView v, @NonNull CharSequence s, int start, int before, int count) {\n }\n\n /**\n * @see android.text.TextWatcher\n */\n public void afterTextChanged(@NonNull RecyclerView recyclerView, @NonNull A adapter, @NonNull VH vh, @NonNull TextView v, @NonNull Editable s) {\n }\n}", "public class BuzzViewHolderFactory extends ScrambleAdapter.AbsViewHolderFactory<BuzzViewHolderFactory.ViewHolder> {\n private boolean mEnabled = true;\n\n @NonNull\n @Override\n public ViewHolder onCreateViewHolder(@NonNull ScrambleAdapter<?> adapter, @NonNull ViewGroup parent, @NonNull ForwardingListener<ScrambleAdapter<?>, RecyclerView.ViewHolder> forwardingListener) {\n View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_buzz, parent, false);\n ViewHolder vh = new ViewHolder(view);\n view.setOnClickListener(forwardingListener);\n view.setOnLongClickListener(forwardingListener);\n return vh;\n }\n\n @Override\n public void onBindViewHolder(@NonNull ScrambleAdapter adapter, @NonNull ViewHolder holder, int position, Object object) {\n // no-op\n }\n\n @Override\n public boolean isAssignable(Object object) {\n return mEnabled && (object instanceof Integer) && ((Integer) object) % 5 == 0;\n }\n\n public boolean isEnabled() {\n return mEnabled;\n }\n\n public void setEnabled(boolean enabled) {\n mEnabled = enabled;\n }\n\n public static class ViewHolder extends RecyclerView.ViewHolder {\n public ViewHolder(View itemView) {\n super(itemView);\n }\n }\n}", "public class FizzBuzzViewHolderFactory extends ScrambleAdapter.AbsViewHolderFactory<FizzBuzzViewHolderFactory.ViewHolder> {\n private boolean mEnabled = true;\n\n @NonNull\n @Override\n public ViewHolder onCreateViewHolder(@NonNull ScrambleAdapter<?> adapter, @NonNull ViewGroup parent, @NonNull ForwardingListener<ScrambleAdapter<?>, RecyclerView.ViewHolder> forwardingListener) {\n View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_fizz_buzz, parent, false);\n ViewHolder vh = new ViewHolder(view);\n view.setOnClickListener(forwardingListener);\n view.setOnLongClickListener(forwardingListener);\n return vh;\n }\n\n @Override\n public void onBindViewHolder(@NonNull ScrambleAdapter adapter, @NonNull ViewHolder holder, int position, Object object) {\n // no-op\n }\n\n @Override\n public boolean isAssignable(Object object) {\n return mEnabled && (object instanceof Integer) && ((Integer) object) % 15 == 0;\n }\n\n public boolean isEnabled() {\n return mEnabled;\n }\n\n public void setEnabled(boolean enabled) {\n mEnabled = enabled;\n }\n\n public static class ViewHolder extends RecyclerView.ViewHolder {\n public ViewHolder(View itemView) {\n super(itemView);\n }\n }\n}", "public class FizzViewHolderFactory extends ScrambleAdapter.AbsViewHolderFactory<FizzViewHolderFactory.ViewHolder> {\n private boolean mEnabled = true;\n\n @NonNull\n @Override\n public ViewHolder onCreateViewHolder(@NonNull ScrambleAdapter<?> adapter, @NonNull ViewGroup parent, @NonNull ForwardingListener<ScrambleAdapter<?>, RecyclerView.ViewHolder> forwardingListener) {\n View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_fizz, parent, false);\n ViewHolder vh = new ViewHolder(view);\n view.setOnClickListener(forwardingListener);\n view.setOnLongClickListener(forwardingListener);\n return vh;\n }\n\n @Override\n public void onBindViewHolder(@NonNull ScrambleAdapter adapter, @NonNull ViewHolder holder, int position, Object object) {\n // no-op\n }\n\n @Override\n public boolean isAssignable(Object object) {\n return mEnabled && (object instanceof Integer) && ((Integer) object) % 3 == 0;\n }\n\n public boolean isEnabled() {\n return mEnabled;\n }\n\n public void setEnabled(boolean enabled) {\n mEnabled = enabled;\n }\n\n public static class ViewHolder extends RecyclerView.ViewHolder {\n public ViewHolder(View itemView) {\n super(itemView);\n }\n }\n}", "public class IntegerViewHolderFactory extends ScrambleAdapter.AbsViewHolderFactory<IntegerViewHolderFactory.ViewHolder> {\n @NonNull\n @Override\n public ViewHolder onCreateViewHolder(@NonNull ScrambleAdapter<?> adapter, @NonNull ViewGroup parent, @NonNull ForwardingListener<ScrambleAdapter<?>, RecyclerView.ViewHolder> forwardingListener) {\n View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_integer, parent, false);\n ViewHolder vh = new ViewHolder(view);\n view.setOnClickListener(forwardingListener);\n view.setOnLongClickListener(forwardingListener);\n return vh;\n }\n\n @Override\n public void onBindViewHolder(@NonNull ScrambleAdapter adapter, @NonNull ViewHolder holder, int position, Object object) {\n Integer item = (Integer) object;\n\n String str = String.valueOf(item);\n holder.text.setText(str);\n }\n\n @Override\n public boolean isAssignable(Object object) {\n return object instanceof Integer;\n }\n\n public static class ViewHolder extends RecyclerView.ViewHolder {\n TextView text;\n\n public ViewHolder(View itemView) {\n super(itemView);\n text = (TextView) itemView.findViewById(R.id.text);\n }\n }\n}", "public class SnackbarLogic {\n public SnackbarLogic() {\n }\n\n @NonNull\n public ISnackbarWrapper make(@NonNull View view, @NonNull CharSequence text, int duration) {\n return new SnackbarWrapperImpl(Snackbar.make(view, text, duration));\n }\n\n @NonNull\n public ISnackbarWrapper make(@NonNull View view, @StringRes int resId, int duration) {\n return new SnackbarWrapperImpl(Snackbar.make(view, resId, duration));\n }\n\n /**\n * For InstrumentationTest\n */\n public interface ISnackbarWrapper {\n void show();\n }\n\n private static class SnackbarWrapperImpl implements ISnackbarWrapper {\n private Snackbar orig;\n\n public SnackbarWrapperImpl(Snackbar orig) {\n this.orig = orig;\n }\n\n @Override\n public void show() {\n orig.show();\n }\n }\n}" ]
import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.view.View; import android.widget.CheckBox; import android.widget.CompoundButton; import net.cattaka.android.adaptertoolbox.adapter.ScrambleAdapter; import net.cattaka.android.adaptertoolbox.adapter.listener.ListenerRelay; import net.cattaka.android.adaptertoolbox.example.adapter.factory.BuzzViewHolderFactory; import net.cattaka.android.adaptertoolbox.example.adapter.factory.FizzBuzzViewHolderFactory; import net.cattaka.android.adaptertoolbox.example.adapter.factory.FizzViewHolderFactory; import net.cattaka.android.adaptertoolbox.example.adapter.factory.IntegerViewHolderFactory; import net.cattaka.android.adaptertoolbox.example.logic.SnackbarLogic; import java.util.ArrayList; import java.util.List;
package net.cattaka.android.adaptertoolbox.example; /** * Created by cattaka on 16/05/02. */ public class FizzBuzzExampleActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener { ListenerRelay<ScrambleAdapter<?>, RecyclerView.ViewHolder> mListenerRelay = new ListenerRelay<ScrambleAdapter<?>, RecyclerView.ViewHolder>() { @Override public void onClick(@NonNull RecyclerView recyclerView, @NonNull ScrambleAdapter adapter, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull View view) { if (recyclerView.getId() == R.id.recycler) { if (viewHolder instanceof FizzViewHolderFactory.ViewHolder) { Integer item = (Integer) adapter.getItemAt(viewHolder.getAdapterPosition()); mSnackbarLogic.make(viewHolder.itemView, "Fizz " + item + " is clicked.", Snackbar.LENGTH_SHORT).show();
} else if (viewHolder instanceof BuzzViewHolderFactory.ViewHolder) {
2
DorsetProject/dorset-framework
agents/web-api/src/test/java/edu/jhuapl/dorset/agents/StockAgentTest.java
[ "public interface Agent {\n\n /**\n * Get the name of the agent\n *\n * @return name\n */\n public String getName();\n\n /**\n * Override the default name of the agent\n *\n * @param name New name for the agent\n */\n public void setName(String name);\n\n /**\n * Get the description of the agent for human consumption\n *\n * @return Description of the agent\n */\n public Description getDescription();\n\n /**\n * Override the default description\n *\n * @param description Description of the agent\n * @see Description\n */\n public void setDescription(Description description);\n \n /**\n * Process a request\n *\n * @param request Request object\n * @return response to the request\n */\n public AgentResponse process(AgentRequest request);\n}", "public class AgentRequest {\n private String text;\n private User user;\n\n public AgentRequest() {}\n \n /**\n * Create an agent request\n *\n * @param request the request\n *\n */\n public AgentRequest(Request request) {\n this.text = request.getText();\n this.user = request.getUser();\n }\n\n /**\n * Create an agent request\n *\n * @param text the text of the request\n */\n public AgentRequest(String text) {\n this.text = text;\n }\n \n /**\n * Create an agent request\n *\n * @param text the text of the request\n * @param user the User information\n *\n */\n public AgentRequest(String text, User user) {\n this.text = text;\n this.user = user;\n }\n\n\n /**\n * Set the text of the request\n *\n * @param text the text of the request\n */\n public void setText(String text) {\n this.text = text;\n }\n\n /**\n * Get the text of the request\n *\n * @return the text of the request\n */\n public String getText() {\n return text;\n }\n \n /**\n * Get the user of the request\n *\n * @return the user of the request\n */\n public User getUser() {\n return user;\n }\n\n /**\n * Set the user of the request\n *\n * @param user the user of the request\n */\n public void setUser(User user) {\n this.user = user;\n }\n}", "public class AgentResponse {\n private final Response.Type type;\n private final String text;\n private final String payload;\n private final ResponseStatus status;\n\n /**\n * Create an agent response\n *\n * @param text the text of the response\n */\n public AgentResponse(String text) {\n this.type = Response.Type.TEXT;\n this.text = text;\n this.payload = null;\n this.status = ResponseStatus.createSuccess();\n }\n\n /**\n * Create an agent response with payload\n *\n * @param type the response type\n * @param text the text of the response\n * @param payload the payload of the response\n */\n public AgentResponse(Response.Type type, String text, String payload) {\n this.type = type;\n this.text = text;\n this.payload = payload;\n this.status = ResponseStatus.createSuccess();\n }\n\n /**\n * Create an agent response for an error\n *\n * @param code the status code\n */\n public AgentResponse(ResponseStatus.Code code) {\n this.type = Response.Type.ERROR;\n this.text = null;\n this.payload = null;\n this.status = new ResponseStatus(code);\n }\n\n /**\n * Create an agent response for an error with custom message\n *\n * @param status the status of the response\n */\n public AgentResponse(ResponseStatus status) {\n this.type = Response.Type.ERROR;\n this.text = null;\n this.payload = null;\n this.status = status;\n }\n\n /**\n * Get the response type\n *\n * @return the response type\n */\n public Response.Type getType() {\n return type;\n }\n\n /**\n * Get the text of the response\n *\n * @return text of the response\n */\n public String getText() {\n return text;\n }\n\n /**\n * Get the payload of the response\n * <p>\n * The payload data varies according to the response type\n *\n * @return payload string or null if no payload\n */\n public String getPayload() {\n return payload;\n }\n\n /**\n * Get the status\n *\n * @return the status code\n */\n public ResponseStatus getStatus() {\n return status;\n }\n\n /**\n * Is this a successful response?\n *\n * @return true if success\n */\n public boolean isSuccess() {\n return status.isSuccess();\n }\n\n /**\n * Is this a valid response?\n *\n * @return true if valid\n */\n public boolean isValid() {\n if (type == null || status == null) { \n return false;\n }\n if (Response.Type.usesPayload(type) && payload == null) {\n return false;\n }\n return !(isSuccess() && text == null);\n }\n}", "public interface HttpClient {\n /**\n * Execute an http request\n * \n * @param request A request object\n * @return a response object or null if a fatal error occurred with request \n */\n public HttpResponse execute(HttpRequest request);\n\n /**\n * Set the user agent\n *\n * @param agent user agent string\n */\n public void setUserAgent(String agent);\n\n /**\n * Get the user agent string\n *\n * @return the user agent string\n */\n public String getUserAgent();\n\n /**\n * Set the connect timeout (wait for connection to be established)\n *\n * @param timeout connect timeout in milliseconds (0 equals an infinite timeout)\n */\n public void setConnectTimeout(int timeout);\n\n /**\n * Get the connect timeout \n *\n * @return the connect timeout in milliseconds\n */\n public Integer getConnectTimeout();\n\n /**\n * Set the read timeout (wait for data during transfer)\n *\n * @param timeout read timeout in milliseconds (0 equals an infinite timeout)\n */\n public void setReadTimeout(int timeout);\n\n /**\n * Get the read timeout\n *\n * @return the read timeout\n */\n public Integer getReadTimeout();\n\n /**\n * Add a request header that will be used on every request\n *\n * Overrides any previous request header values with the same name.\n *\n * @param name the name of the header\n * @param value the value of the header\n */\n public void addDefaultRequestHeader(String name, String value);\n}", "public class HttpRequest {\n private final HttpMethod method;\n private final String url;\n private String body;\n private HttpParameter[] bodyForm;\n private ContentType contentType;\n\n public HttpRequest(HttpMethod method, String url) {\n this.method = method;\n this.url = url;\n }\n\n /**\n * Create a GET request\n * @param url the URL to get\n * @return http request object\n */\n public static HttpRequest get(String url) {\n return new HttpRequest(HttpMethod.GET, url);\n }\n\n /**\n * Create a POST request\n * @param url the URL to post to\n * @return http request object\n */\n public static HttpRequest post(String url) {\n return new HttpRequest(HttpMethod.POST, url);\n }\n\n /**\n * Create a PUT request\n * @param url the URL \n * @return http request object\n */\n public static HttpRequest put(String url) {\n return new HttpRequest(HttpMethod.PUT, url);\n }\n\n /**\n * Create a DELETE request\n * @param url the URL to delete\n * @return http request object\n */\n public static HttpRequest delete(String url) {\n return new HttpRequest(HttpMethod.DELETE, url);\n }\n\n /**\n * Get the method of the http request\n * @return the http method\n */\n public HttpMethod getMethod() {\n return method;\n }\n\n /**\n * Get the URL of the http request\n * @return the URL\n */\n public String getUrl() {\n return url;\n }\n\n /**\n * Get the body of the http request\n * @return the body as a string\n */\n public String getBody() {\n return body;\n }\n\n /**\n * Get the content type of the http request\n * @return the content type object\n */\n public ContentType getContentType() {\n return contentType;\n }\n\n /**\n * Set the body of the http request\n * @param body the body as a string\n * @param contentType the content type for the request\n * @return self\n */\n public HttpRequest setBody(String body, ContentType contentType) {\n this.body = body;\n this.contentType = contentType;\n return this;\n }\n\n /**\n * Get the http parameters for the body of the request\n * @return an array of http parameters\n */\n public HttpParameter[] getBodyForm() {\n return bodyForm;\n }\n\n /**\n * Set the body form http parameters\n * @param parameters the http parameters to set in the body\n * @return self\n */\n public HttpRequest setBodyForm(HttpParameter[] parameters) {\n bodyForm = parameters.clone();\n return this;\n }\n}", "public interface HttpResponse {\n public String asString();\n \n public byte[] asBytes();\n\n public int getStatusCode();\n\n public String getReasonPhrase();\n\n /**\n * Was there a client error (such as a 404)?\n *\n * @return boolean\n */\n public boolean isClientError();\n\n /**\n * Was there a server error?\n *\n * @return boolean\n */\n public boolean isServerError();\n\n /**\n * Was there any kind of error?\n *\n * @return boolean\n */\n public boolean isError();\n\n /**\n * Was the request a success?\n *\n * @return boolean\n */\n public boolean isSuccess();\n}" ]
import edu.jhuapl.dorset.agents.Agent; import edu.jhuapl.dorset.agents.AgentRequest; import edu.jhuapl.dorset.agents.AgentResponse; import edu.jhuapl.dorset.http.HttpClient; import edu.jhuapl.dorset.http.HttpRequest; import edu.jhuapl.dorset.http.HttpResponse; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.File; import java.io.FileNotFoundException; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Scanner; import org.junit.Test;
/** * Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.jhuapl.dorset.agents; public class StockAgentTest { private String apikey = "default_apikey"; protected String getJsonData(String filename) { ClassLoader classLoader = StockAgent.class.getClassLoader(); URL url = classLoader.getResource(filename); try { Path path = Paths.get(url.toURI()); try (Scanner scanner = new Scanner(new File(path.toString()))) { return scanner.useDelimiter("\\Z").next(); } } catch (URISyntaxException | FileNotFoundException e) { throw new RuntimeException(e); } } @Test public void testStockAgentExactMatch() { String keyword = "facebook, Inc."; String jsonData = getJsonData("stockagent/MockJson_Facebook.json");
HttpClient client = new FakeHttpClient(new FakeHttpResponse(jsonData));
3
bladecoder/blade-ink
src/test/java/com/bladecoder/ink/runtime/test/RuntimeSpecTest.java
[ "public class Profiler {\n\tprivate Stopwatch continueWatch = new Stopwatch();\n\tprivate Stopwatch stepWatch = new Stopwatch();\n\tprivate Stopwatch snapWatch = new Stopwatch();\n\n\tprivate double continueTotal;\n\tprivate double snapTotal;\n\tprivate double stepTotal;\n\n\tprivate String[] currStepStack;\n\tprivate StepDetails currStepDetails;\n\tprivate ProfileNode rootNode;\n\tprivate int numContinues;\n\n\tprivate class StepDetails {\n\t\tpublic String type;\n\t\tpublic RTObject obj;\n\t\tpublic double time;\n\n\t\tStepDetails(String type, RTObject obj, double time) {\n\t\t\tthis.type = type;\n\t\t\tthis.obj = obj;\n\t\t\tthis.time = time;\n\t\t}\n\t}\n\n\tprivate List<StepDetails> stepDetails = new ArrayList<>();\n\n\t/**\n\t * The root node in the hierarchical tree of recorded ink timings.\n\t */\n\tpublic ProfileNode getRootNode() {\n\t\treturn rootNode;\n\t}\n\n\tProfiler() {\n\t\trootNode = new ProfileNode();\n\t}\n\n\t/**\n\t * Generate a printable report based on the data recording during profiling.\n\t */\n\tpublic String report() {\n\t\tStringBuilder sb = new StringBuilder();\n\n\t\tsb.append(String.format(\"%d CONTINUES / LINES:\\n\", numContinues));\n\t\tsb.append(String.format(\"TOTAL TIME: %s\\n\", formatMillisecs(continueTotal)));\n\t\tsb.append(String.format(\"SNAPSHOTTING: %s\\n\", formatMillisecs(snapTotal)));\n\t\tsb.append(String.format(\"OTHER: %s\\n\", formatMillisecs(continueTotal - (stepTotal + snapTotal))));\n\t\tsb.append(rootNode.toString());\n\n\t\treturn sb.toString();\n\t}\n\n\tvoid preContinue() {\n\t\tcontinueWatch.reset();\n\t\tcontinueWatch.start();\n\t}\n\n\tvoid postContinue() {\n\t\tcontinueWatch.stop();\n\t\tcontinueTotal += millisecs(continueWatch);\n\t\tnumContinues++;\n\t}\n\n\tvoid preStep() {\n\t\tcurrStepStack = null;\n\t\tstepWatch.reset();\n\t\tstepWatch.start();\n\t}\n\n\tvoid step(CallStack callstack) {\n\t\tstepWatch.stop();\n\n\t\tString[] stack = new String[callstack.getElements().size()];\n\t\tfor (int i = 0; i < stack.length; i++) {\n\n\t\t\tString stackElementName = \"\";\n\n\t\t\tif (!callstack.getElements().get(i).currentPointer.isNull()) {\n\t\t\t\tPath objPath = callstack.getElements().get(i).currentPointer.getPath();\n\n\t\t\t\tfor (int c = 0; c < objPath.getLength(); c++) {\n\t\t\t\t\tComponent comp = objPath.getComponent(c);\n\t\t\t\t\tif (!comp.isIndex()) {\n\t\t\t\t\t\tstackElementName = comp.getName();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstack[i] = stackElementName;\n\t\t}\n\n\t\tcurrStepStack = stack;\n\n\t\tRTObject currObj = callstack.getCurrentElement().currentPointer.resolve();\n\n\t\tString stepType = null;\n\t\tControlCommand controlCommandStep = currObj instanceof ControlCommand ? (ControlCommand) currObj : null;\n\t\tif (controlCommandStep != null)\n\t\t\tstepType = controlCommandStep.getCommandType().toString() + \" CC\";\n\t\telse\n\t\t\tstepType = currObj.getClass().getSimpleName();\n\n\t\tcurrStepDetails = new StepDetails(stepType, currObj, 0f);\n\n\t\tstepWatch.start();\n\t}\n\n\tvoid postStep() {\n\t\tstepWatch.stop();\n\n\t\tdouble duration = millisecs(stepWatch);\n\t\tstepTotal += duration;\n\n\t\trootNode.addSample(currStepStack, duration);\n\n\t\tcurrStepDetails.time = duration;\n\t\tstepDetails.add(currStepDetails);\n\t}\n\n\t/**\n\t * Generate a printable report specifying the average and maximum times spent\n\t * stepping over different internal ink instruction types. This report type is\n\t * primarily used to profile the ink engine itself rather than your own specific\n\t * ink.\n\t */\n\tpublic String stepLengthReport() {\n\t\tStringBuilder sb = new StringBuilder();\n\n\t\tsb.append(\"TOTAL: \" + rootNode.getTotalMillisecs() + \"ms\\n\");\n\n\t\t// AVERAGE STEP TIMES\n\t\tHashMap<String, Double> typeToDetails = new HashMap<>();\n\n\t\t// average group by s.type\n\t\tfor (StepDetails sd : stepDetails) {\n\t\t\tif (typeToDetails.containsKey(sd.type))\n\t\t\t\tcontinue;\n\n\t\t\tString type = sd.type;\n\t\t\tdouble avg = 0f;\n\t\t\tfloat num = 0;\n\n\t\t\tfor (StepDetails sd2 : stepDetails) {\n\t\t\t\tif (type.equals(sd2.type)) {\n\t\t\t\t\tnum++;\n\t\t\t\t\tavg += sd2.time;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tavg = avg / num;\n\n\t\t\ttypeToDetails.put(sd.type, avg);\n\t\t}\n\n\t\t// sort by average\n\t\tList<Entry<String, Double>> averageStepTimes = new LinkedList<>(typeToDetails.entrySet());\n\n\t\tCollections.sort(averageStepTimes, new Comparator<Entry<String, Double>>() {\n\t\t\t@Override\n\t\t\tpublic int compare(Entry<String, Double> o1, Entry<String, Double> o2) {\n\t\t\t\treturn (int) (o1.getValue() - o2.getValue());\n\t\t\t}\n\t\t});\n\n\t\t// join times\n\t\tsb.append(\"AVERAGE STEP TIMES: \");\n\t\tfor (int i = 0; i < averageStepTimes.size(); i++) {\n\t\t\tsb.append(averageStepTimes.get(i).getKey());\n\t\t\tsb.append(\": \");\n\t\t\tsb.append(averageStepTimes.get(i).getValue());\n\t\t\tsb.append(\"ms\");\n\n\t\t\tif (i != averageStepTimes.size() - 1)\n\t\t\t\tsb.append(',');\n\t\t}\n\n\t\tsb.append('\\n');\n\n\t\t// ACCUMULATED STEP TIMES\n\t\ttypeToDetails.clear();\n\n\t\t// average group by s.type\n\t\tfor (StepDetails sd : stepDetails) {\n\t\t\tif (typeToDetails.containsKey(sd.type))\n\t\t\t\tcontinue;\n\n\t\t\tString type = sd.type;\n\t\t\tdouble sum = 0f;\n\n\t\t\tfor (StepDetails sd2 : stepDetails) {\n\t\t\t\tif (type.equals(sd2.type)) {\n\t\t\t\t\tsum += sd2.time;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttypeToDetails.put(sd.type + \" (x\" + typeToDetails.size() + \")\", sum);\n\t\t}\n\n\t\t// sort by average\n\t\tList<Entry<String, Double>> accumStepTimes = new LinkedList<>(typeToDetails.entrySet());\n\n\t\tCollections.sort(accumStepTimes, new Comparator<Entry<String, Double>>() {\n\t\t\t@Override\n\t\t\tpublic int compare(Entry<String, Double> o1, Entry<String, Double> o2) {\n\t\t\t\treturn (int) (o1.getValue() - o2.getValue());\n\t\t\t}\n\t\t});\n\n\t\t// join times\n\t\tsb.append(\"ACCUMULATED STEP TIMES: \");\n\t\tfor (int i = 0; i < accumStepTimes.size(); i++) {\n\t\t\tsb.append(accumStepTimes.get(i).getKey());\n\t\t\tsb.append(\": \");\n\t\t\tsb.append(accumStepTimes.get(i).getValue());\n\n\t\t\tif (i != accumStepTimes.size() - 1)\n\t\t\t\tsb.append(',');\n\t\t}\n\n\t\tsb.append('\\n');\n\n\t\treturn sb.toString();\n\t}\n\n\t/**\n\t * Create a large log of all the internal instructions that were evaluated while\n\t * profiling was active. Log is in a tab-separated format, for easy loading into\n\t * a spreadsheet application.\n\t */\n\tpublic String megalog() {\n\t\tStringBuilder sb = new StringBuilder();\n\n\t\tsb.append(\"Step type\\tDescription\\tPath\\tTime\\n\");\n\n\t\tfor (StepDetails step : stepDetails) {\n\t\t\tsb.append(step.type);\n\t\t\tsb.append(\"\\t\");\n\t\t\tsb.append(step.obj.toString());\n\t\t\tsb.append(\"\\t\");\n\t\t\tsb.append(step.obj.getPath());\n\t\t\tsb.append(\"\\t\");\n\t\t\tsb.append(Double.toString(step.time));\n\t\t\tsb.append('\\n');\n\t\t}\n\n\t\treturn sb.toString();\n\t}\n\n\tvoid preSnapshot() {\n\t\tsnapWatch.reset();\n\t\tsnapWatch.start();\n\t}\n\n\tvoid postSnapshot() {\n\t\tsnapWatch.stop();\n\t\tsnapTotal += millisecs(snapWatch);\n\t}\n\n\tdouble millisecs(Stopwatch watch) {\n\t\treturn watch.getElapsedMilliseconds();\n\t}\n\n\tstatic String formatMillisecs(double num) {\n\t\tif (num > 5000) {\n\t\t\treturn String.format(\"%.1f secs\", num / 1000.0);\n\t\t}\n\t\tif (num > 1000) {\n\t\t\treturn String.format(\"%.2f secs\", num / 1000.0);\n\t\t} else if (num > 100) {\n\t\t\treturn String.format(\"%.0f ms\", num);\n\t\t} else if (num > 1) {\n\t\t\treturn String.format(\"%.1f ms\", num);\n\t\t} else if (num > 0.01) {\n\t\t\treturn String.format(\"%.3f ms\", num);\n\t\t} else {\n\t\t\treturn String.format(\"%.0f ms\", num);\n\t\t}\n\t}\n}", "public class Story extends RTObject implements VariablesState.VariableChanged {\n\t/**\n\t * General purpose delegate definition for bound EXTERNAL function definitions\n\t * from ink. Note that this version isn't necessary if you have a function with\n\t * three arguments or less.\n\t *\n\t * @param <R> the result type\n\t * @see ExternalFunction0\n\t * @see ExternalFunction1\n\t * @see ExternalFunction2\n\t * @see ExternalFunction3\n\t */\n\tpublic interface ExternalFunction<R> {\n\t\tR call(Object... args) throws Exception;\n\t}\n\n\t/**\n\t * EXTERNAL function delegate with zero arguments.\n\t *\n\t * @param <R> the result type\n\t */\n\tpublic abstract static class ExternalFunction0<R> implements ExternalFunction<R> {\n\t\t@Override\n\t\tpublic final R call(Object... args) throws Exception {\n\t\t\tif (args.length != 0) {\n\t\t\t\tthrow new IllegalArgumentException(\"Expecting 0 arguments.\");\n\t\t\t}\n\t\t\treturn call();\n\t\t}\n\n\t\tprotected abstract R call() throws Exception;\n\t}\n\n\t/**\n\t * EXTERNAL function delegate with one argument.\n\t *\n\t * @param <T> the argument type\n\t * @param <R> the result type\n\t */\n\tpublic abstract static class ExternalFunction1<T, R> implements ExternalFunction<R> {\n\t\t@Override\n\t\tpublic final R call(Object... args) throws Exception {\n\t\t\tif (args.length != 1) {\n\t\t\t\tthrow new IllegalArgumentException(\"Expecting 1 argument.\");\n\t\t\t}\n\t\t\treturn call(coerceArg(args[0]));\n\t\t}\n\n\t\tprotected abstract R call(T t) throws Exception;\n\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tprotected T coerceArg(Object arg) throws Exception {\n\t\t\treturn (T) arg;\n\t\t}\n\t}\n\n\t/**\n\t * EXTERNAL function delegate with two arguments.\n\t *\n\t * @param <T1> the first argument type\n\t * @param <T2> the second argument type\n\t * @param <R> the result type\n\t */\n\tpublic abstract static class ExternalFunction2<T1, T2, R> implements ExternalFunction<R> {\n\t\t@Override\n\t\tpublic final R call(Object... args) throws Exception {\n\t\t\tif (args.length != 2) {\n\t\t\t\tthrow new IllegalArgumentException(\"Expecting 2 arguments.\");\n\t\t\t}\n\t\t\treturn call(coerceArg0(args[0]), coerceArg1(args[1]));\n\t\t}\n\n\t\tprotected abstract R call(T1 t1, T2 t2) throws Exception;\n\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tprotected T1 coerceArg0(Object arg) throws Exception {\n\t\t\treturn (T1) arg;\n\t\t}\n\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tprotected T2 coerceArg1(Object arg) throws Exception {\n\t\t\treturn (T2) arg;\n\t\t}\n\t}\n\n\t/**\n\t * EXTERNAL function delegate with three arguments.\n\t *\n\t * @param <T1> the first argument type\n\t * @param <T2> the second argument type\n\t * @param <T3> the third argument type\n\t * @param <R> the result type\n\t */\n\tpublic abstract static class ExternalFunction3<T1, T2, T3, R> implements ExternalFunction<R> {\n\t\t@Override\n\t\tpublic final R call(Object... args) throws Exception {\n\t\t\tif (args.length != 3) {\n\t\t\t\tthrow new IllegalArgumentException(\"Expecting 3 arguments.\");\n\t\t\t}\n\t\t\treturn call(coerceArg0(args[0]), coerceArg1(args[1]), coerceArg2(args[2]));\n\t\t}\n\n\t\tprotected abstract R call(T1 t1, T2 t2, T3 t3) throws Exception;\n\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tprotected T1 coerceArg0(Object arg) throws Exception {\n\t\t\treturn (T1) arg;\n\t\t}\n\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tprotected T2 coerceArg1(Object arg) throws Exception {\n\t\t\treturn (T2) arg;\n\t\t}\n\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tprotected T3 coerceArg2(Object arg) throws Exception {\n\t\t\treturn (T3) arg;\n\t\t}\n\t}\n\n\tclass ExternalFunctionDef {\n\t\tpublic ExternalFunction<?> function;\n\t\tpublic boolean lookaheadSafe;\n\t}\n\n\t// Version numbers are for engine itself and story file, rather\n\t// than the story state save format\n\t// -- old engine, new format: always fail\n\t// -- new engine, old format: possibly cope, based on this number\n\t// When incrementing the version number above, the question you\n\t// should ask yourself is:\n\t// -- Will the engine be able to load an old story file from\n\t// before I made these changes to the engine?\n\t// If possible, you should support it, though it's not as\n\t// critical as loading old save games, since it's an\n\t// in-development problem only.\n\n\t/**\n\t * Delegate definition for variable observation - see ObserveVariable.\n\t */\n\tpublic interface VariableObserver {\n\t\tvoid call(String variableName, Object newValue);\n\t}\n\n\t/**\n\t * The current version of the ink story file format.\n\t */\n\tpublic static final int inkVersionCurrent = 20;\n\n\t/**\n\t * The minimum legacy version of ink that can be loaded by the current version\n\t * of the code.\n\t */\n\tpublic static final int inkVersionMinimumCompatible = 18;\n\n\tprivate Container mainContentContainer;\n\tprivate ListDefinitionsOrigin listDefinitions;\n\n\t/**\n\t * An ink file can provide a fallback functions for when when an EXTERNAL has\n\t * been left unbound by the client, and the fallback function will be called\n\t * instead. Useful when testing a story in playmode, when it's not possible to\n\t * write a client-side C# external function, but you don't want it to fail to\n\t * run.\n\t */\n\tprivate boolean allowExternalFunctionFallbacks;\n\n\tprivate HashMap<String, ExternalFunctionDef> externals;\n\n\tprivate boolean hasValidatedExternals;\n\n\tprivate StoryState state;\n\n\tprivate Container temporaryEvaluationContainer;\n\n\tprivate HashMap<String, List<VariableObserver>> variableObservers;\n\n\tprivate List<Container> prevContainers = new ArrayList<>();\n\n\tprivate Profiler profiler;\n\n\tprivate boolean asyncContinueActive;\n\tprivate StoryState stateSnapshotAtLastNewline = null;\n\n\tprivate int recursiveContinueCount = 0;\n\n\tprivate boolean asyncSaving;\n\n\tprivate boolean sawLookaheadUnsafeFunctionAfterNewline = false;\n\n\tpublic Error.ErrorHandler onError = null;\n\n\t// Warning: When creating a Story using this constructor, you need to\n\t// call ResetState on it before use. Intended for compiler use only.\n\t// For normal use, use the constructor that takes a json string.\n\tpublic Story(Container contentContainer, List<ListDefinition> lists) {\n\t\tmainContentContainer = contentContainer;\n\n\t\tif (lists != null) {\n\t\t\tlistDefinitions = new ListDefinitionsOrigin(lists);\n\t\t}\n\n\t\texternals = new HashMap<>();\n\t}\n\n\tpublic Story(Container contentContainer) {\n\t\tthis(contentContainer, null);\n\t}\n\n\t/**\n\t * Construct a Story Object using a JSON String compiled through inklecate.\n\t */\n\tpublic Story(String jsonString) throws Exception {\n\t\tthis((Container) null);\n\t\tHashMap<String, Object> rootObject = SimpleJson.textToDictionary(jsonString);\n\n\t\tObject versionObj = rootObject.get(\"inkVersion\");\n\t\tif (versionObj == null)\n\t\t\tthrow new Exception(\"ink version number not found. Are you sure it's a valid .ink.json file?\");\n\n\t\tint formatFromFile = versionObj instanceof String ? Integer.parseInt((String) versionObj) : (int) versionObj;\n\n\t\tif (formatFromFile > inkVersionCurrent) {\n\t\t\tthrow new Exception(\"Version of ink used to build story was newer than the current version of the engine\");\n\t\t} else if (formatFromFile < inkVersionMinimumCompatible) {\n\t\t\tthrow new Exception(\n\t\t\t\t\t\"Version of ink used to build story is too old to be loaded by this version of the engine\");\n\t\t} else if (formatFromFile != inkVersionCurrent) {\n\t\t\tSystem.out.println(\n\t\t\t\t\t\"WARNING: Version of ink used to build story doesn't match current version of engine. Non-critical, but recommend synchronising.\");\n\t\t}\n\n\t\tObject rootToken = rootObject.get(\"root\");\n\t\tif (rootToken == null)\n\t\t\tthrow new Exception(\"Root node for ink not found. Are you sure it's a valid .ink.json file?\");\n\n\t\tObject listDefsObj = rootObject.get(\"listDefs\");\n\t\tif (listDefsObj != null) {\n\t\t\tlistDefinitions = Json.jTokenToListDefinitions(listDefsObj);\n\t\t}\n\n\t\tRTObject runtimeObject = Json.jTokenToRuntimeObject(rootToken);\n\t\tmainContentContainer = runtimeObject instanceof Container ? (Container) runtimeObject : null;\n\n\t\tresetState();\n\t}\n\n\tvoid addError(String message) throws Exception {\n\t\taddError(message, false, false);\n\t}\n\n\tvoid warning(String message) throws Exception {\n\t\taddError(message, true, false);\n\t}\n\n\tvoid addError(String message, boolean isWarning, boolean useEndLineNumber) throws Exception {\n\t\tDebugMetadata dm = currentDebugMetadata();\n\n\t\tString errorTypeStr = isWarning ? \"WARNING\" : \"ERROR\";\n\n\t\tif (dm != null) {\n\t\t\tint lineNum = useEndLineNumber ? dm.endLineNumber : dm.startLineNumber;\n\t\t\tmessage = String.format(\"RUNTIME %s: '%s' line %d: %s\", errorTypeStr, dm.fileName, lineNum, message);\n\t\t} else if (!state.getCurrentPointer().isNull()) {\n\t\t\tmessage = String.format(\"RUNTIME %s: (%s): %s\", errorTypeStr,\n\t\t\t\t\tstate.getCurrentPointer().getPath().toString(), message);\n\t\t} else {\n\t\t\tmessage = \"RUNTIME \" + errorTypeStr + \": \" + message;\n\t\t}\n\n\t\tstate.addError(message, isWarning);\n\n\t\t// In a broken state don't need to know about any other errors.\n\t\tif (!isWarning)\n\t\t\tstate.forceEnd();\n\t}\n\n\t/**\n\t * Start recording ink profiling information during calls to Continue on Story.\n\t * Return a Profiler instance that you can request a report from when you're\n\t * finished.\n\t *\n\t * @throws Exception\n\t */\n\tpublic Profiler startProfiling() throws Exception {\n\t\tifAsyncWeCant(\"start profiling\");\n\t\tprofiler = new Profiler();\n\n\t\treturn profiler;\n\t}\n\n\t/**\n\t * Stop recording ink profiling information during calls to Continue on Story.\n\t * To generate a report from the profiler, call\n\t */\n\tpublic void endProfiling() {\n\t\tprofiler = null;\n\t}\n\n\tvoid Assert(boolean condition, Object... formatParams) throws Exception {\n\t\tAssert(condition, null, formatParams);\n\t}\n\n\tvoid Assert(boolean condition, String message, Object... formatParams) throws Exception {\n\t\tif (!condition) {\n\t\t\tif (message == null) {\n\t\t\t\tmessage = \"Story assert\";\n\t\t\t}\n\t\t\tif (formatParams != null && formatParams.length > 0) {\n\t\t\t\tmessage = String.format(message, formatParams);\n\t\t\t}\n\n\t\t\tthrow new Exception(message + \" \" + currentDebugMetadata());\n\t\t}\n\t}\n\n\t/**\n\t * Binds a Java function to an ink EXTERNAL function.\n\t *\n\t * @param funcName EXTERNAL ink function name to bind to.\n\t * @param func The Java function to bind.\n\t * @param lookaheadSafe The ink engine often evaluates further than you might\n\t * expect beyond the current line just in case it sees glue\n\t * that will cause the two lines to become one. In this\n\t * case it's possible that a function can appear to be\n\t * called twice instead of just once, and earlier than you\n\t * expect. If it's safe for your function to be called in\n\t * this way (since the result and side effect of the\n\t * function will not change), then you can pass 'true'.\n\t * Usually, you want to pass 'false', especially if you\n\t * want some action to be performed in game code when this\n\t * function is called.\n\t */\n\tpublic void bindExternalFunction(String funcName, ExternalFunction<?> func, boolean lookaheadSafe)\n\t\t\tthrows Exception {\n\t\tifAsyncWeCant(\"bind an external function\");\n\t\tAssert(!externals.containsKey(funcName), \"Function '\" + funcName + \"' has already been bound.\");\n\t\tExternalFunctionDef externalFunctionDef = new ExternalFunctionDef();\n\t\texternalFunctionDef.function = func;\n\t\texternalFunctionDef.lookaheadSafe = lookaheadSafe;\n\n\t\texternals.put(funcName, externalFunctionDef);\n\t}\n\n\tpublic void bindExternalFunction(String funcName, ExternalFunction<?> func) throws Exception {\n\t\tbindExternalFunction(funcName, func, true);\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic <T> T tryCoerce(Object value, Class<T> type) throws Exception {\n\n\t\tif (value == null)\n\t\t\treturn null;\n\n\t\tif (type.isAssignableFrom(value.getClass()))\n\t\t\treturn (T) value;\n\n\t\tif (value instanceof Float && type == Integer.class) {\n\t\t\tInteger intVal = (int) Math.round((Float) value);\n\t\t\treturn (T) intVal;\n\t\t}\n\n\t\tif (value instanceof Integer && type == Float.class) {\n\t\t\tFloat floatVal = Float.valueOf((Integer) value);\n\t\t\treturn (T) floatVal;\n\t\t}\n\n\t\tif (value instanceof Integer && type == Boolean.class) {\n\t\t\tint intVal = (Integer) value;\n\t\t\treturn (T) (intVal == 0 ? Boolean.FALSE : Boolean.TRUE);\n\t\t}\n\n\t\tif (value instanceof Boolean && type == Integer.class) {\n\t\t\tboolean val = (Boolean) value;\n\t\t\treturn (T) (val ? (Integer) 1 : (Integer) 0);\n\t\t}\n\n\t\tif (type == String.class) {\n\t\t\treturn (T) value.toString();\n\t\t}\n\n\t\tAssert(false, \"Failed to cast \" + value.getClass().getCanonicalName() + \" to \" + type.getCanonicalName());\n\n\t\treturn null;\n\t}\n\n\t/**\n\t * Get any global tags associated with the story. These are defined as hash tags\n\t * defined at the very top of the story.\n\t *\n\t * @throws Exception\n\t */\n\tpublic List<String> getGlobalTags() throws Exception {\n\t\treturn tagsAtStartOfFlowContainerWithPathString(\"\");\n\t}\n\n\t/**\n\t * Gets any tags associated with a particular knot or knot.stitch. These are\n\t * defined as hash tags defined at the very top of a knot or stitch.\n\t *\n\t * @param path The path of the knot or stitch, in the form \"knot\" or\n\t * \"knot.stitch\".\n\t * @throws Exception\n\t */\n\tpublic List<String> tagsForContentAtPath(String path) throws Exception {\n\t\treturn tagsAtStartOfFlowContainerWithPathString(path);\n\t}\n\n\tList<String> tagsAtStartOfFlowContainerWithPathString(String pathString) throws Exception {\n\t\tPath path = new Path(pathString);\n\n\t\t// Expected to be global story, knot or stitch\n\t\tContainer flowContainer = null;\n\t\tRTObject c = contentAtPath(path).getContainer();\n\n\t\tif (c instanceof Container)\n\t\t\tflowContainer = (Container) c;\n\n\t\twhile (true) {\n\t\t\tRTObject firstContent = flowContainer.getContent().get(0);\n\t\t\tif (firstContent instanceof Container)\n\t\t\t\tflowContainer = (Container) firstContent;\n\t\t\telse\n\t\t\t\tbreak;\n\t\t}\n\n\t\t// Any initial tag objects count as the \"main tags\" associated with that\n\t\t// story/knot/stitch\n\t\tList<String> tags = null;\n\t\tfor (RTObject c2 : flowContainer.getContent()) {\n\t\t\tTag tag = null;\n\n\t\t\tif (c2 instanceof Tag)\n\t\t\t\ttag = (Tag) c2;\n\n\t\t\tif (tag != null) {\n\t\t\t\tif (tags == null)\n\t\t\t\t\ttags = new ArrayList<>();\n\t\t\t\ttags.add(tag.getText());\n\t\t\t} else\n\t\t\t\tbreak;\n\t\t}\n\n\t\treturn tags;\n\t}\n\n\t/**\n\t * Useful when debugging a (very short) story, to visualise the state of the\n\t * story. Add this call as a watch and open the extended text. A left-arrow mark\n\t * will denote the current point of the story. It's only recommended that this\n\t * is used on very short debug stories, since it can end up generate a large\n\t * quantity of text otherwise.\n\t */\n\tpublic String buildStringOfHierarchy() {\n\t\tStringBuilder sb = new StringBuilder();\n\n\t\tgetMainContentContainer().buildStringOfHierarchy(sb, 0, state.getCurrentPointer().resolve());\n\n\t\treturn sb.toString();\n\t}\n\n\tvoid callExternalFunction(String funcName, int numberOfArguments) throws Exception {\n\t\tExternalFunctionDef funcDef;\n\t\tContainer fallbackFunctionContainer = null;\n\n\t\tfuncDef = externals.get(funcName);\n\n\t\t// Should this function break glue? Abort run if we've already seen a newline.\n\t\t// Set a bool to tell it to restore the snapshot at the end of this instruction.\n\t\tif (funcDef != null && !funcDef.lookaheadSafe && stateSnapshotAtLastNewline != null) {\n\t\t\tsawLookaheadUnsafeFunctionAfterNewline = true;\n\t\t\treturn;\n\t\t}\n\n\t\t// Try to use fallback function?\n\t\tif (funcDef == null) {\n\t\t\tif (allowExternalFunctionFallbacks) {\n\n\t\t\t\tfallbackFunctionContainer = knotContainerWithName(funcName);\n\n\t\t\t\tAssert(fallbackFunctionContainer != null, \"Trying to call EXTERNAL function '\" + funcName\n\t\t\t\t\t\t+ \"' which has not been bound, and fallback ink function could not be found.\");\n\n\t\t\t\t// Divert direct into fallback function and we're done\n\t\t\t\tstate.getCallStack().push(PushPopType.Function, 0, state.getOutputStream().size());\n\t\t\t\tstate.setDivertedPointer(Pointer.startOf(fallbackFunctionContainer));\n\t\t\t\treturn;\n\n\t\t\t} else {\n\t\t\t\tAssert(false, \"Trying to call EXTERNAL function '\" + funcName\n\t\t\t\t\t\t+ \"' which has not been bound (and ink fallbacks disabled).\");\n\t\t\t}\n\t\t}\n\n\t\t// Pop arguments\n\t\tArrayList<Object> arguments = new ArrayList<>();\n\t\tfor (int i = 0; i < numberOfArguments; ++i) {\n\t\t\tValue<?> poppedObj = (Value<?>) state.popEvaluationStack();\n\t\t\tObject valueObj = poppedObj.getValueObject();\n\t\t\targuments.add(valueObj);\n\t\t}\n\n\t\t// Reverse arguments from the order they were popped,\n\t\t// so they're the right way round again.\n\t\tCollections.reverse(arguments);\n\n\t\t// Run the function!\n\t\tObject funcResult = funcDef.function.call(arguments.toArray());\n\n\t\t// Convert return value (if any) to the a type that the ink engine can use\n\t\tRTObject returnObj;\n\t\tif (funcResult != null) {\n\t\t\treturnObj = AbstractValue.create(funcResult);\n\t\t\tAssert(returnObj != null, \"Could not create ink value from returned Object of type \"\n\t\t\t\t\t+ funcResult.getClass().getCanonicalName());\n\t\t} else {\n\t\t\treturnObj = new Void();\n\t\t}\n\n\t\tstate.pushEvaluationStack(returnObj);\n\t}\n\n\t/**\n\t * Check whether more content is available if you were to call Continue() - i.e.\n\t * are we mid story rather than at a choice point or at the end.\n\t *\n\t * @return true if it's possible to call Continue()\n\t */\n\tpublic boolean canContinue() {\n\t\treturn state.canContinue();\n\t}\n\n\t/**\n\t * Chooses the Choice from the currentChoices list with the given index.\n\t * Internally, this sets the current content path to that pointed to by the\n\t * Choice, ready to continue story evaluation.\n\t */\n\tpublic void chooseChoiceIndex(int choiceIdx) throws Exception {\n\t\tList<Choice> choices = getCurrentChoices();\n\t\tAssert(choiceIdx >= 0 && choiceIdx < choices.size(), \"choice out of range\");\n\n\t\t// Replace callstack with the one from the thread at the choosing point,\n\t\t// so that we can jump into the right place in the flow.\n\t\t// This is important in case the flow was forked by a new thread, which\n\t\t// can create multiple leading edges for the story, each of\n\t\t// which has its own context.\n\t\tChoice choiceToChoose = choices.get(choiceIdx);\n\t\tstate.getCallStack().setCurrentThread(choiceToChoose.getThreadAtGeneration());\n\n\t\tchoosePath(choiceToChoose.targetPath);\n\t}\n\n\tvoid choosePath(Path p) throws Exception {\n\t\tchoosePath(p, true);\n\t}\n\n\tvoid choosePath(Path p, boolean incrementingTurnIndex) throws Exception {\n\t\tstate.setChosenPath(p, incrementingTurnIndex);\n\n\t\t// Take a note of newly visited containers for read counts etc\n\t\tvisitChangedContainersDueToDivert();\n\t}\n\n\t/**\n\t * Change the current position of the story to the given path. From here you can\n\t * call Continue() to evaluate the next line.\n\t *\n\t * The path String is a dot-separated path as used ly by the engine. These\n\t * examples should work:\n\t *\n\t * myKnot myKnot.myStitch\n\t *\n\t * Note however that this won't necessarily work:\n\t *\n\t * myKnot.myStitch.myLabelledChoice\n\t *\n\t * ...because of the way that content is nested within a weave structure.\n\t *\n\t * By default this will reset the callstack beforehand, which means that any\n\t * tunnels, threads or functions you were in at the time of calling will be\n\t * discarded. This is different from the behaviour of ChooseChoiceIndex, which\n\t * will always keep the callstack, since the choices are known to come from the\n\t * correct state, and known their source thread.\n\t *\n\t * You have the option of passing false to the resetCallstack parameter if you\n\t * don't want this behaviour, and will leave any active threads, tunnels or\n\t * function calls in-tact.\n\t *\n\t * This is potentially dangerous! If you're in the middle of a tunnel, it'll\n\t * redirect only the inner-most tunnel, meaning that when you tunnel-return\n\t * using '-&gt;-&gt;-&gt;', it'll return to where you were before. This may be\n\t * what you want though. However, if you're in the middle of a function,\n\t * ChoosePathString will throw an exception.\n\t *\n\t *\n\t * @param path A dot-separted path string, as specified above.\n\t * @param resetCallstack Whether to reset the callstack first (see summary\n\t * description).\n\t * @param arguments Optional set of arguments to pass, if path is to a knot\n\t * that takes them.\n\t */\n\tpublic void choosePathString(String path, boolean resetCallstack, Object[] arguments) throws Exception {\n\t\tifAsyncWeCant(\"call ChoosePathString right now\");\n\n\t\tif (resetCallstack) {\n\t\t\tresetCallstack();\n\t\t} else {\n\t\t\t// ChoosePathString is potentially dangerous since you can call it when the\n\t\t\t// stack is\n\t\t\t// pretty much in any state. Let's catch one of the worst offenders.\n\t\t\tif (state.getCallStack().getCurrentElement().type == PushPopType.Function) {\n\t\t\t\tString funcDetail = \"\";\n\t\t\t\tContainer container = state.getCallStack().getCurrentElement().currentPointer.container;\n\t\t\t\tif (container != null) {\n\t\t\t\t\tfuncDetail = \"(\" + container.getPath().toString() + \") \";\n\t\t\t\t}\n\t\t\t\tthrow new Exception(\"Story was running a function \" + funcDetail + \"when you called ChoosePathString(\"\n\t\t\t\t\t\t+ path + \") - this is almost certainly not not what you want! Full stack trace: \\n\"\n\t\t\t\t\t\t+ state.getCallStack().getCallStackTrace());\n\t\t\t}\n\t\t}\n\n\t\tstate.passArgumentsToEvaluationStack(arguments);\n\t\tchoosePath(new Path(path));\n\t}\n\n\tpublic void choosePathString(String path) throws Exception {\n\t\tchoosePathString(path, true, null);\n\t}\n\n\tpublic void choosePathString(String path, boolean resetCallstack) throws Exception {\n\t\tchoosePathString(path, resetCallstack, null);\n\t}\n\n\tvoid ifAsyncWeCant(String activityStr) throws Exception {\n\t\tif (asyncContinueActive)\n\t\t\tthrow new Exception(\"Can't \" + activityStr\n\t\t\t\t\t+ \". Story is in the middle of a ContinueAsync(). Make more ContinueAsync() calls or a single Continue() call beforehand.\");\n\t}\n\n\tSearchResult contentAtPath(Path path) throws Exception {\n\t\treturn getMainContentContainer().contentAtPath(path);\n\t}\n\n\tContainer knotContainerWithName(String name) {\n\n\t\tINamedContent namedContainer = mainContentContainer.getNamedContent().get(name);\n\n\t\tif (namedContainer != null)\n\t\t\treturn namedContainer instanceof Container ? (Container) namedContainer : null;\n\t\telse\n\t\t\treturn null;\n\t}\n\n\t/**\n\t * The current flow name if using multi-flow funtionality - see SwitchFlow\n\t */\n\tpublic String getCurrentFlowName() {\n\t\treturn state.getCurrentFlowName();\n\t}\n\n\tpublic void switchFlow(String flowName) throws Exception {\n\t\tifAsyncWeCant(\"switch flow\");\n\n\t\tif (asyncSaving)\n\t\t\tthrow new Exception(\"Story is already in background saving mode, can't switch flow to \" + flowName);\n\n\t\tstate.switchFlowInternal(flowName);\n\t}\n\n\tpublic void removeFlow(String flowName) throws Exception {\n\t\tstate.removeFlowInternal(flowName);\n\t}\n\n\tpublic void switchToDefaultFlow() throws Exception {\n\t\tstate.switchToDefaultFlowInternal();\n\t}\n\n\t/**\n\t * Continue the story for one line of content, if possible. If you're not sure\n\t * if there's more content available, for example if you want to check whether\n\t * you're at a choice point or at the end of the story, you should call\n\t * canContinue before calling this function.\n\t *\n\t * @return The line of text content.\n\t */\n\tpublic String Continue() throws StoryException, Exception {\n\t\tcontinueAsync(0);\n\t\treturn getCurrentText();\n\t}\n\n\t/**\n\t * If ContinueAsync was called (with milliseconds limit &gt; 0) then this\n\t * property will return false if the ink evaluation isn't yet finished, and you\n\t * need to call it again in order for the Continue to fully complete.\n\t */\n\tpublic boolean asyncContinueComplete() {\n\t\treturn !asyncContinueActive;\n\t}\n\n\t/**\n\t * An \"asnychronous\" version of Continue that only partially evaluates the ink,\n\t * with a budget of a certain time limit. It will exit ink evaluation early if\n\t * the evaluation isn't complete within the time limit, with the\n\t * asyncContinueComplete property being false. This is useful if ink evaluation\n\t * takes a long time, and you want to distribute it over multiple game frames\n\t * for smoother animation. If you pass a limit of zero, then it will fully\n\t * evaluate the ink in the same way as calling Continue (and in fact, this\n\t * exactly what Continue does internally).\n\t */\n\tpublic void continueAsync(float millisecsLimitAsync) throws Exception {\n\t\tif (!hasValidatedExternals)\n\t\t\tvalidateExternalBindings();\n\n\t\tcontinueInternal(millisecsLimitAsync);\n\t}\n\n\tvoid continueInternal() throws Exception {\n\t\tcontinueInternal(0);\n\t}\n\n\tvoid continueInternal(float millisecsLimitAsync) throws Exception {\n\t\tif (profiler != null)\n\t\t\tprofiler.preContinue();\n\n\t\tboolean isAsyncTimeLimited = millisecsLimitAsync > 0;\n\n\t\trecursiveContinueCount++;\n\n\t\t// Doing either:\n\t\t// - full run through non-async (so not active and don't want to be)\n\t\t// - Starting async run-through\n\t\tif (!asyncContinueActive) {\n\t\t\tasyncContinueActive = isAsyncTimeLimited;\n\t\t\tif (!canContinue()) {\n\t\t\t\tthrow new Exception(\"Can't continue - should check canContinue before calling Continue\");\n\t\t\t}\n\n\t\t\tstate.setDidSafeExit(false);\n\n\t\t\tstate.resetOutput();\n\n\t\t\t// It's possible for ink to call game to call ink to call game etc\n\t\t\t// In this case, we only want to batch observe variable changes\n\t\t\t// for the outermost call.\n\t\t\tif (recursiveContinueCount == 1)\n\t\t\t\tstate.getVariablesState().setbatchObservingVariableChanges(true);\n\t\t}\n\n\t\t// Start timing\n\t\tStopwatch durationStopwatch = new Stopwatch();\n\t\tdurationStopwatch.start();\n\n\t\tboolean outputStreamEndsInNewline = false;\n\t\tsawLookaheadUnsafeFunctionAfterNewline = false;\n\t\tdo {\n\n\t\t\ttry {\n\t\t\t\toutputStreamEndsInNewline = continueSingleStep();\n\t\t\t} catch (StoryException e) {\n\t\t\t\taddError(e.getMessage(), false, e.useEndLineNumber);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (outputStreamEndsInNewline)\n\t\t\t\tbreak;\n\n\t\t\t// Run out of async time?\n\t\t\tif (asyncContinueActive && durationStopwatch.getElapsedMilliseconds() > millisecsLimitAsync) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t} while (canContinue());\n\n\t\tdurationStopwatch.stop();\n\n\t\t// 4 outcomes:\n\t\t// - got newline (so finished this line of text)\n\t\t// - can't continue (e.g. choices or ending)\n\t\t// - ran out of time during evaluation\n\t\t// - error\n\t\t//\n\t\t// Successfully finished evaluation in time (or in error)\n\t\tif (outputStreamEndsInNewline || !canContinue()) {\n\t\t\t// Need to rewind, due to evaluating further than we should?\n\t\t\tif (stateSnapshotAtLastNewline != null) {\n\t\t\t\trestoreStateSnapshot();\n\t\t\t}\n\n\t\t\t// Finished a section of content / reached a choice point?\n\t\t\tif (!canContinue()) {\n\t\t\t\tif (state.getCallStack().canPopThread())\n\t\t\t\t\taddError(\"Thread available to pop, threads should always be flat by the end of evaluation?\");\n\n\t\t\t\tif (state.getGeneratedChoices().size() == 0 && !state.isDidSafeExit()\n\t\t\t\t\t\t&& temporaryEvaluationContainer == null) {\n\t\t\t\t\tif (state.getCallStack().canPop(PushPopType.Tunnel))\n\t\t\t\t\t\taddError(\"unexpectedly reached end of content. Do you need a '->->' to return from a tunnel?\");\n\t\t\t\t\telse if (state.getCallStack().canPop(PushPopType.Function))\n\t\t\t\t\t\taddError(\"unexpectedly reached end of content. Do you need a '~ return'?\");\n\t\t\t\t\telse if (!state.getCallStack().canPop())\n\t\t\t\t\t\taddError(\"ran out of content. Do you need a '-> DONE' or '-> END'?\");\n\t\t\t\t\telse\n\t\t\t\t\t\taddError(\"unexpectedly reached end of content for unknown reason. Please debug compiler!\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tstate.setDidSafeExit(false);\n\t\t\tsawLookaheadUnsafeFunctionAfterNewline = false;\n\n\t\t\tif (recursiveContinueCount == 1)\n\t\t\t\tstate.getVariablesState().setbatchObservingVariableChanges(false);\n\t\t\tasyncContinueActive = false;\n\t\t}\n\n\t\trecursiveContinueCount--;\n\n\t\tif (profiler != null)\n\t\t\tprofiler.postContinue();\n\n\t\t// Report any errors that occured during evaluation.\n\t\t// This may either have been StoryExceptions that were thrown\n\t\t// and caught during evaluation, or directly added with AddError.\n\t\tif (state.hasError() || state.hasWarning()) {\n\t\t\tif (onError != null) {\n\t\t\t\tif (state.hasError()) {\n\t\t\t\t\tfor (String err : state.getCurrentErrors()) {\n\t\t\t\t\t\tonError.error(err, ErrorType.Error);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (state.hasWarning()) {\n\t\t\t\t\tfor (String err : state.getCurrentWarnings()) {\n\t\t\t\t\t\tonError.error(err, ErrorType.Warning);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tresetErrors();\n\t\t\t}\n\t\t\t// Throw an exception since there's no error handler\n\t\t\telse {\n\t\t\t\tStringBuilder sb = new StringBuilder();\n\t\t\t\tsb.append(\"Ink had \");\n\t\t\t\tif (state.hasError()) {\n\t\t\t\t\tsb.append(state.getCurrentErrors().size());\n\t\t\t\t\tsb.append(state.getCurrentErrors().size() == 1 ? \" error\" : \" errors\");\n\t\t\t\t\tif (state.hasWarning())\n\t\t\t\t\t\tsb.append(\" and \");\n\t\t\t\t}\n\t\t\t\tif (state.hasWarning()) {\n\t\t\t\t\tsb.append(state.getCurrentWarnings().size());\n\t\t\t\t\tsb.append(state.getCurrentWarnings().size() == 1 ? \" warning\" : \" warnings\");\n\t\t\t\t}\n\t\t\t\tsb.append(\n\t\t\t\t\t\t\". It is strongly suggested that you assign an error handler to story.onError. The first issue was: \");\n\t\t\t\tsb.append(state.hasError() ? state.getCurrentErrors().get(0) : state.getCurrentWarnings().get(0));\n\n\t\t\t\t// If you get this exception, please assign an error handler to your story.\n\t\t\t\t// If you're using Unity, you can do something like this when you create\n\t\t\t\t// your story:\n\t\t\t\t//\n\t\t\t\t// var story = new Ink.Runtime.Story(jsonTxt);\n\t\t\t\t// story.onError = (errorMessage, errorType) => {\n\t\t\t\t// if( errorType == ErrorType.Warning )\n\t\t\t\t// Debug.LogWarning(errorMessage);\n\t\t\t\t// else\n\t\t\t\t// Debug.LogError(errorMessage);\n\t\t\t\t// };\n\t\t\t\t//\n\t\t\t\t//\n\t\t\t\tthrow new StoryException(sb.toString());\n\t\t\t}\n\t\t}\n\t}\n\n\tboolean continueSingleStep() throws Exception {\n\t\tif (profiler != null)\n\t\t\tprofiler.preStep();\n\n\t\t// Run main step function (walks through content)\n\t\tstep();\n\n\t\tif (profiler != null)\n\t\t\tprofiler.postStep();\n\n\t\t// Run out of content and we have a default invisible choice that we can follow?\n\t\tif (!canContinue() && !state.getCallStack().elementIsEvaluateFromGame()) {\n\n\t\t\ttryFollowDefaultInvisibleChoice();\n\t\t}\n\n\t\tif (profiler != null)\n\t\t\tprofiler.preSnapshot();\n\n\t\t// Don't save/rewind during string evaluation, which is e.g. used for choices\n\t\tif (!state.inStringEvaluation()) {\n\n\t\t\t// We previously found a newline, but were we just double checking that\n\t\t\t// it wouldn't immediately be removed by glue?\n\t\t\tif (stateSnapshotAtLastNewline != null) {\n\n\t\t\t\t// Has proper text or a tag been added? Then we know that the newline\n\t\t\t\t// that was previously added is definitely the end of the line.\n\t\t\t\tOutputStateChange change = calculateNewlineOutputStateChange(\n\t\t\t\t\t\tstateSnapshotAtLastNewline.getCurrentText(), state.getCurrentText(),\n\t\t\t\t\t\tstateSnapshotAtLastNewline.getCurrentTags().size(), state.getCurrentTags().size());\n\n\t\t\t\t// The last time we saw a newline, it was definitely the end of the line, so we\n\t\t\t\t// want to rewind to that point.\n\t\t\t\tif (change == OutputStateChange.ExtendedBeyondNewline || sawLookaheadUnsafeFunctionAfterNewline) {\n\t\t\t\t\trestoreStateSnapshot();\n\n\t\t\t\t\t// Hit a newline for sure, we're done\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\n\t\t\t\t// Newline that previously existed is no longer valid - e.g.\n\t\t\t\t// glue was encounted that caused it to be removed.\n\t\t\t\telse if (change == OutputStateChange.NewlineRemoved) {\n\t\t\t\t\tstateSnapshotAtLastNewline = null;\n\t\t\t\t\tdiscardSnapshot();\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t// Current content ends in a newline - approaching end of our evaluation\n\t\t\tif (state.outputStreamEndsInNewline()) {\n\n\t\t\t\t// If we can continue evaluation for a bit:\n\t\t\t\t// Create a snapshot in case we need to rewind.\n\t\t\t\t// We're going to continue stepping in case we see glue or some\n\t\t\t\t// non-text content such as choices.\n\t\t\t\tif (canContinue()) {\n\n\t\t\t\t\t// Don't bother to record the state beyond the current newline.\n\t\t\t\t\t// e.g.:\n\t\t\t\t\t// Hello world\\n // record state at the end of here\n\t\t\t\t\t// ~ complexCalculation() // don't actually need this unless it generates text\n\t\t\t\t\tif (stateSnapshotAtLastNewline == null)\n\t\t\t\t\t\tstateSnapshot();\n\t\t\t\t}\n\n\t\t\t\t// Can't continue, so we're about to exit - make sure we\n\t\t\t\t// don't have an old state hanging around.\n\t\t\t\telse {\n\t\t\t\t\tdiscardSnapshot();\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tif (profiler != null)\n\t\t\tprofiler.postSnapshot();\n\n\t\t// outputStreamEndsInNewline = false\n\t\treturn false;\n\n\t}\n\n\t/**\n\t * Continue the story until the next choice point or until it runs out of\n\t * content. This is as opposed to the Continue() method which only evaluates one\n\t * line of output at a time.\n\t *\n\t * @return The resulting text evaluated by the ink engine, concatenated\n\t * together.\n\t */\n\tpublic String continueMaximally() throws StoryException, Exception {\n\t\tifAsyncWeCant(\"ContinueMaximally\");\n\n\t\tStringBuilder sb = new StringBuilder();\n\n\t\twhile (canContinue()) {\n\t\t\tsb.append(Continue());\n\t\t}\n\n\t\treturn sb.toString();\n\t}\n\n\tDebugMetadata currentDebugMetadata() {\n\t\tDebugMetadata dm;\n\n\t\t// Try to get from the current path first\n\t\tfinal Pointer pointer = new Pointer(state.getCurrentPointer());\n\t\tif (!pointer.isNull()) {\n\t\t\tdm = pointer.resolve().getDebugMetadata();\n\t\t\tif (dm != null) {\n\t\t\t\treturn dm;\n\t\t\t}\n\t\t}\n\n\t\t// Move up callstack if possible\n\t\tfor (int i = state.getCallStack().getElements().size() - 1; i >= 0; --i) {\n\t\t\tpointer.assign(state.getCallStack().getElements().get(i).currentPointer);\n\t\t\tif (!pointer.isNull() && pointer.resolve() != null) {\n\t\t\t\tdm = pointer.resolve().getDebugMetadata();\n\t\t\t\tif (dm != null) {\n\t\t\t\t\treturn dm;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Current/previous path may not be valid if we've just had an error,\n\t\t// or if we've simply run out of content.\n\t\t// As a last resort, try to grab something from the output stream\n\t\tfor (int i = state.getOutputStream().size() - 1; i >= 0; --i) {\n\t\t\tRTObject outputObj = state.getOutputStream().get(i);\n\t\t\tdm = outputObj.getDebugMetadata();\n\t\t\tif (dm != null) {\n\t\t\t\treturn dm;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tint currentLineNumber() throws Exception {\n\t\tDebugMetadata dm = currentDebugMetadata();\n\t\tif (dm != null) {\n\t\t\treturn dm.startLineNumber;\n\t\t}\n\t\treturn 0;\n\t}\n\n\tvoid error(String message) throws Exception {\n\t\terror(message, false);\n\t}\n\n\t// Throw an exception that gets caught and causes AddError to be called,\n\t// then exits the flow.\n\tvoid error(String message, boolean useEndLineNumber) throws Exception {\n\t\tStoryException e = new StoryException(message);\n\t\te.useEndLineNumber = useEndLineNumber;\n\t\tthrow e;\n\t}\n\n\t// Evaluate a \"hot compiled\" piece of ink content, as used by the REPL-like\n\t// CommandLinePlayer.\n\tRTObject evaluateExpression(Container exprContainer) throws StoryException, Exception {\n\t\tint startCallStackHeight = state.getCallStack().getElements().size();\n\n\t\tstate.getCallStack().push(PushPopType.Tunnel);\n\n\t\ttemporaryEvaluationContainer = exprContainer;\n\n\t\tstate.goToStart();\n\n\t\tint evalStackHeight = state.getEvaluationStack().size();\n\n\t\tContinue();\n\n\t\ttemporaryEvaluationContainer = null;\n\n\t\t// Should have fallen off the end of the Container, which should\n\t\t// have auto-popped, but just in case we didn't for some reason,\n\t\t// manually pop to restore the state (including currentPath).\n\t\tif (state.getCallStack().getElements().size() > startCallStackHeight) {\n\t\t\tstate.popCallstack();\n\t\t}\n\n\t\tint endStackHeight = state.getEvaluationStack().size();\n\t\tif (endStackHeight > evalStackHeight) {\n\t\t\treturn state.popEvaluationStack();\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\n\t}\n\n\t/**\n\t * The list of Choice Objects available at the current point in the Story. This\n\t * list will be populated as the Story is stepped through with the Continue()\n\t * method. Once canContinue becomes false, this list will be populated, and is\n\t * usually (but not always) on the final Continue() step.\n\t */\n\tpublic List<Choice> getCurrentChoices() {\n\n\t\t// Don't include invisible choices for external usage.\n\t\tList<Choice> choices = new ArrayList<>();\n\t\tfor (Choice c : state.getCurrentChoices()) {\n\t\t\tif (!c.isInvisibleDefault) {\n\t\t\t\tc.setIndex(choices.size());\n\t\t\t\tchoices.add(c);\n\t\t\t}\n\t\t}\n\n\t\treturn choices;\n\t}\n\n\t/**\n\t * Gets a list of tags as defined with '#' in source that were seen during the\n\t * latest Continue() call.\n\t *\n\t * @throws Exception\n\t */\n\tpublic List<String> getCurrentTags() throws Exception {\n\t\tifAsyncWeCant(\"call currentTags since it's a work in progress\");\n\t\treturn state.getCurrentTags();\n\t}\n\n\t/**\n\t * Any warnings generated during evaluation of the Story.\n\t */\n\tpublic List<String> getCurrentWarnings() {\n\t\treturn state.getCurrentWarnings();\n\t}\n\n\t/**\n\t * Any errors generated during evaluation of the Story.\n\t */\n\tpublic List<String> getCurrentErrors() {\n\t\treturn state.getCurrentErrors();\n\t}\n\n\t/**\n\t * The latest line of text to be generated from a Continue() call.\n\t *\n\t * @throws Exception\n\t */\n\tpublic String getCurrentText() throws Exception {\n\t\tifAsyncWeCant(\"call currentText since it's a work in progress\");\n\t\treturn state.getCurrentText();\n\t}\n\n\t/**\n\t * The entire current state of the story including (but not limited to):\n\t *\n\t * * Global variables * Temporary variables * Read/visit and turn counts * The\n\t * callstack and evaluation stacks * The current threads\n\t *\n\t */\n\tpublic StoryState getState() {\n\t\treturn state;\n\t}\n\n\t/**\n\t * The VariablesState Object contains all the global variables in the story.\n\t * However, note that there's more to the state of a Story than just the global\n\t * variables. This is a convenience accessor to the full state Object.\n\t */\n\tpublic VariablesState getVariablesState() {\n\t\treturn state.getVariablesState();\n\t}\n\n\tpublic ListDefinitionsOrigin getListDefinitions() {\n\t\treturn listDefinitions;\n\t}\n\n\t/**\n\t * Whether the currentErrors list contains any errors. THIS MAY BE REMOVED - you\n\t * should be setting an error handler directly using Story.onError.\n\t */\n\tpublic boolean hasError() {\n\t\treturn state.hasError();\n\t}\n\n\t/**\n\t * Whether the currentWarnings list contains any warnings.\n\t */\n\tpublic boolean hasWarning() {\n\t\treturn state.hasWarning();\n\t}\n\n\tboolean incrementContentPointer() {\n\t\tboolean successfulIncrement = true;\n\n\t\tPointer pointer = new Pointer(state.getCallStack().getCurrentElement().currentPointer);\n\t\tpointer.index++;\n\n\t\t// Each time we step off the end, we fall out to the next container, all\n\t\t// the\n\t\t// while we're in indexed rather than named content\n\t\twhile (pointer.index >= pointer.container.getContent().size()) {\n\n\t\t\tsuccessfulIncrement = false;\n\n\t\t\tContainer nextAncestor = pointer.container.getParent() instanceof Container\n\t\t\t\t\t? (Container) pointer.container.getParent()\n\t\t\t\t\t: null;\n\n\t\t\tif (nextAncestor == null) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tint indexInAncestor = nextAncestor.getContent().indexOf(pointer.container);\n\t\t\tif (indexInAncestor == -1) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tpointer = new Pointer(nextAncestor, indexInAncestor);\n\n\t\t\t// Increment to next content in outer container\n\t\t\tpointer.index++;\n\n\t\t\tsuccessfulIncrement = true;\n\t\t}\n\n\t\tif (!successfulIncrement)\n\t\t\tpointer.assign(Pointer.Null);\n\n\t\tstate.getCallStack().getCurrentElement().currentPointer.assign(pointer);\n\n\t\treturn successfulIncrement;\n\t}\n\n\t// Does the expression result represented by this Object evaluate to true?\n\t// e.g. is it a Number that's not equal to 1?\n\tboolean isTruthy(RTObject obj) throws Exception {\n\t\tboolean truthy = false;\n\t\tif (obj instanceof Value) {\n\t\t\tValue<?> val = (Value<?>) obj;\n\n\t\t\tif (val instanceof DivertTargetValue) {\n\t\t\t\tDivertTargetValue divTarget = (DivertTargetValue) val;\n\t\t\t\terror(\"Shouldn't use a divert target (to \" + divTarget.getTargetPath()\n\t\t\t\t\t\t+ \") as a conditional value. Did you intend a function call 'likeThis()' or a read count check 'likeThis'? (no arrows)\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\treturn val.isTruthy();\n\t\t}\n\t\treturn truthy;\n\t}\n\n\t/**\n\t * When the named global variable changes it's value, the observer will be\n\t * called to notify it of the change. Note that if the value changes multiple\n\t * times within the ink, the observer will only be called once, at the end of\n\t * the ink's evaluation. If, during the evaluation, it changes and then changes\n\t * back again to its original value, it will still be called. Note that the\n\t * observer will also be fired if the value of the variable is changed\n\t * externally to the ink, by directly setting a value in story.variablesState.\n\t *\n\t * @param variableName The name of the global variable to observe.\n\t * @param observer A delegate function to call when the variable changes.\n\t * @throws Exception\n\t */\n\tpublic void observeVariable(String variableName, VariableObserver observer) throws Exception {\n\t\tifAsyncWeCant(\"observe a new variable\");\n\n\t\tif (variableObservers == null)\n\t\t\tvariableObservers = new HashMap<>();\n\n\t\tif (!state.getVariablesState().globalVariableExistsWithName(variableName))\n\t\t\tthrow new Exception(\n\t\t\t\t\t\"Cannot observe variable '\" + variableName + \"' because it wasn't declared in the ink story.\");\n\n\t\tif (variableObservers.containsKey(variableName)) {\n\t\t\tvariableObservers.get(variableName).add(observer);\n\t\t} else {\n\t\t\tList<VariableObserver> l = new ArrayList<>();\n\t\t\tl.add(observer);\n\t\t\tvariableObservers.put(variableName, l);\n\t\t}\n\t}\n\n\t/**\n\t * Convenience function to allow multiple variables to be observed with the same\n\t * observer delegate function. See the singular ObserveVariable for details. The\n\t * observer will get one call for every variable that has changed.\n\t *\n\t * @param variableNames The set of variables to observe.\n\t * @param observer The delegate function to call when any of the named\n\t * variables change.\n\t * @throws Exception\n\t * @throws StoryException\n\t */\n\tpublic void observeVariables(List<String> variableNames, VariableObserver observer)\n\t\t\tthrows StoryException, Exception {\n\t\tfor (String varName : variableNames) {\n\t\t\tobserveVariable(varName, observer);\n\t\t}\n\t}\n\n\t/**\n\t * Removes the variable observer, to stop getting variable change notifications.\n\t * If you pass a specific variable name, it will stop observing that particular\n\t * one. If you pass null (or leave it blank, since it's optional), then the\n\t * observer will be removed from all variables that it's subscribed to.\n\t *\n\t * @param observer The observer to stop observing.\n\t * @param specificVariableName (Optional) Specific variable name to stop\n\t * observing.\n\t * @throws Exception\n\t */\n\tpublic void removeVariableObserver(VariableObserver observer, String specificVariableName) throws Exception {\n\t\tifAsyncWeCant(\"remove a variable observer\");\n\n\t\tif (variableObservers == null)\n\t\t\treturn;\n\n\t\t// Remove observer for this specific variable\n\t\tif (specificVariableName != null) {\n\t\t\tif (variableObservers.containsKey(specificVariableName)) {\n\t\t\t\tvariableObservers.get(specificVariableName).remove(observer);\n\t\t\t\tif (variableObservers.get(specificVariableName).size() == 0) {\n\t\t\t\t\tvariableObservers.remove(specificVariableName);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// Remove observer for all variables\n\t\t\tfor (Map.Entry<String, List<VariableObserver>> obs : variableObservers.entrySet()) {\n\t\t\t\tobs.getValue().remove(observer);\n\t\t\t\tif (obs.getValue().size() == 0) {\n\t\t\t\t\tvariableObservers.remove(obs.getKey());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void removeVariableObserver(VariableObserver observer) throws Exception {\n\t\tremoveVariableObserver(observer, null);\n\t}\n\n\t@Override\n\tpublic void variableStateDidChangeEvent(String variableName, RTObject newValueObj) throws Exception {\n\t\tif (variableObservers == null)\n\t\t\treturn;\n\n\t\tList<VariableObserver> observers = variableObservers.get(variableName);\n\n\t\tif (observers != null) {\n\t\t\tif (!(newValueObj instanceof Value)) {\n\t\t\t\tthrow new Exception(\"Tried to get the value of a variable that isn't a standard type\");\n\t\t\t}\n\n\t\t\tValue<?> val = (Value<?>) newValueObj;\n\n\t\t\tfor (VariableObserver o : observers) {\n\t\t\t\to.call(variableName, val.getValueObject());\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic Container getMainContentContainer() {\n\t\tif (temporaryEvaluationContainer != null) {\n\t\t\treturn temporaryEvaluationContainer;\n\t\t} else {\n\t\t\treturn mainContentContainer;\n\t\t}\n\t}\n\n\tString buildStringOfContainer(Container container) {\n\t\tStringBuilder sb = new StringBuilder();\n\n\t\tcontainer.buildStringOfHierarchy(sb, 0, state.getCurrentPointer().resolve());\n\n\t\treturn sb.toString();\n\t}\n\n\tprivate void nextContent() throws Exception {\n\t\t// Setting previousContentObject is critical for\n\t\t// VisitChangedContainersDueToDivert\n\t\tstate.setPreviousPointer(state.getCurrentPointer());\n\n\t\t// Divert step?\n\t\tif (!state.getDivertedPointer().isNull()) {\n\n\t\t\tstate.setCurrentPointer(state.getDivertedPointer());\n\t\t\tstate.setDivertedPointer(Pointer.Null);\n\n\t\t\t// Internally uses state.previousContentObject and\n\t\t\t// state.currentContentObject\n\t\t\tvisitChangedContainersDueToDivert();\n\n\t\t\t// Diverted location has valid content?\n\t\t\tif (!state.getCurrentPointer().isNull()) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Otherwise, if diverted location doesn't have valid content,\n\t\t\t// drop down and attempt to increment.\n\t\t\t// This can happen if the diverted path is intentionally jumping\n\t\t\t// to the end of a container - e.g. a Conditional that's re-joining\n\t\t}\n\n\t\tboolean successfulPointerIncrement = incrementContentPointer();\n\n\t\t// Ran out of content? Try to auto-exit from a function,\n\t\t// or finish evaluating the content of a thread\n\t\tif (!successfulPointerIncrement) {\n\n\t\t\tboolean didPop = false;\n\n\t\t\tif (state.getCallStack().canPop(PushPopType.Function)) {\n\n\t\t\t\t// Pop from the call stack\n\t\t\t\tstate.popCallstack(PushPopType.Function);\n\n\t\t\t\t// This pop was due to dropping off the end of a function that\n\t\t\t\t// didn't return anything,\n\t\t\t\t// so in this case, we make sure that the evaluator has\n\t\t\t\t// something to chomp on if it needs it\n\t\t\t\tif (state.getInExpressionEvaluation()) {\n\t\t\t\t\tstate.pushEvaluationStack(new Void());\n\t\t\t\t}\n\n\t\t\t\tdidPop = true;\n\t\t\t} else if (state.getCallStack().canPopThread()) {\n\t\t\t\tstate.getCallStack().popThread();\n\n\t\t\t\tdidPop = true;\n\t\t\t} else {\n\t\t\t\tstate.tryExitFunctionEvaluationFromGame();\n\t\t\t}\n\n\t\t\t// Step past the point where we last called out\n\t\t\tif (didPop && !state.getCurrentPointer().isNull()) {\n\t\t\t\tnextContent();\n\t\t\t}\n\t\t}\n\t}\n\n\t// Note that this is O(n), since it re-evaluates the shuffle indices\n\t// from a consistent seed each time.\n\t// TODO: Is this the best algorithm it can be?\n\tint nextSequenceShuffleIndex() throws Exception {\n\t\tRTObject popEvaluationStack = state.popEvaluationStack();\n\n\t\tIntValue numElementsIntVal = popEvaluationStack instanceof IntValue ? (IntValue) popEvaluationStack : null;\n\n\t\tif (numElementsIntVal == null) {\n\t\t\terror(\"expected number of elements in sequence for shuffle index\");\n\t\t\treturn 0;\n\t\t}\n\n\t\tContainer seqContainer = state.getCurrentPointer().container;\n\n\t\tint numElements = numElementsIntVal.value;\n\n\t\tIntValue seqCountVal = (IntValue) state.popEvaluationStack();\n\t\tint seqCount = seqCountVal.value;\n\t\tint loopIndex = seqCount / numElements;\n\t\tint iterationIndex = seqCount % numElements;\n\n\t\t// Generate the same shuffle based on:\n\t\t// - The hash of this container, to make sure it's consistent\n\t\t// each time the runtime returns to the sequence\n\t\t// - How many times the runtime has looped around this full shuffle\n\t\tString seqPathStr = seqContainer.getPath().toString();\n\t\tint sequenceHash = 0;\n\t\tfor (char c : seqPathStr.toCharArray()) {\n\t\t\tsequenceHash += c;\n\t\t}\n\n\t\tint randomSeed = sequenceHash + loopIndex + state.getStorySeed();\n\n\t\tRandom random = new Random(randomSeed);\n\n\t\tArrayList<Integer> unpickedIndices = new ArrayList<>();\n\t\tfor (int i = 0; i < numElements; ++i) {\n\t\t\tunpickedIndices.add(i);\n\t\t}\n\n\t\tfor (int i = 0; i <= iterationIndex; ++i) {\n\t\t\tint chosen = random.nextInt(Integer.MAX_VALUE) % unpickedIndices.size();\n\t\t\tint chosenIndex = unpickedIndices.get(chosen);\n\t\t\tunpickedIndices.remove(chosen);\n\n\t\t\tif (i == iterationIndex) {\n\t\t\t\treturn chosenIndex;\n\t\t\t}\n\t\t}\n\n\t\tthrow new Exception(\"Should never reach here\");\n\t}\n\n\t/**\n\t * Checks whether contentObj is a control or flow Object rather than a piece of\n\t * content, and performs the required command if necessary.\n\t *\n\t * @return true if Object was logic or flow control, false if it's normal\n\t * content.\n\t * @param contentObj Content Object.\n\t */\n\tboolean performLogicAndFlowControl(RTObject contentObj) throws Exception {\n\t\tif (contentObj == null) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// Divert\n\t\tif (contentObj instanceof Divert) {\n\n\t\t\tDivert currentDivert = (Divert) contentObj;\n\n\t\t\tif (currentDivert.isConditional()) {\n\t\t\t\tRTObject conditionValue = state.popEvaluationStack();\n\n\t\t\t\t// False conditional? Cancel divert\n\t\t\t\tif (!isTruthy(conditionValue))\n\t\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tif (currentDivert.hasVariableTarget()) {\n\t\t\t\tString varName = currentDivert.getVariableDivertName();\n\n\t\t\t\tRTObject varContents = state.getVariablesState().getVariableWithName(varName);\n\n\t\t\t\tif (varContents == null) {\n\t\t\t\t\terror(\"Tried to divert using a target from a variable that could not be found (\" + varName + \")\");\n\t\t\t\t} else if (!(varContents instanceof DivertTargetValue)) {\n\n\t\t\t\t\tIntValue intContent = varContents instanceof IntValue ? (IntValue) varContents : null;\n\n\t\t\t\t\tString errorMessage = \"Tried to divert to a target from a variable, but the variable (\" + varName\n\t\t\t\t\t\t\t+ \") didn't contain a divert target, it \";\n\t\t\t\t\tif (intContent != null && intContent.value == 0) {\n\t\t\t\t\t\terrorMessage += \"was empty/null (the value 0).\";\n\t\t\t\t\t} else {\n\t\t\t\t\t\terrorMessage += \"contained '\" + varContents + \"'.\";\n\t\t\t\t\t}\n\n\t\t\t\t\terror(errorMessage);\n\t\t\t\t}\n\n\t\t\t\tDivertTargetValue target = (DivertTargetValue) varContents;\n\t\t\t\tstate.setDivertedPointer(pointerAtPath(target.getTargetPath()));\n\n\t\t\t} else if (currentDivert.isExternal()) {\n\t\t\t\tcallExternalFunction(currentDivert.getTargetPathString(), currentDivert.getExternalArgs());\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\tstate.setDivertedPointer(currentDivert.getTargetPointer());\n\t\t\t}\n\n\t\t\tif (currentDivert.getPushesToStack()) {\n\t\t\t\tstate.getCallStack().push(currentDivert.getStackPushType(), 0, state.getOutputStream().size());\n\t\t\t}\n\n\t\t\tif (state.getDivertedPointer().isNull() && !currentDivert.isExternal()) {\n\n\t\t\t\t// Human readable name available - runtime divert is part of a\n\t\t\t\t// hard-written divert that to missing content\n\t\t\t\tif (currentDivert != null && currentDivert.getDebugMetadata().sourceName != null) {\n\t\t\t\t\terror(\"Divert target doesn't exist: \" + currentDivert.getDebugMetadata().sourceName);\n\t\t\t\t} else {\n\t\t\t\t\terror(\"Divert resolution failed: \" + currentDivert);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\t\t// Start/end an expression evaluation? Or print out the result?\n\t\telse if (contentObj instanceof ControlCommand) {\n\t\t\tControlCommand evalCommand = (ControlCommand) contentObj;\n\n\t\t\tint choiceCount;\n\t\t\tswitch (evalCommand.getCommandType()) {\n\n\t\t\tcase EvalStart:\n\t\t\t\tAssert(state.getInExpressionEvaluation() == false, \"Already in expression evaluation?\");\n\t\t\t\tstate.setInExpressionEvaluation(true);\n\t\t\t\tbreak;\n\n\t\t\tcase EvalEnd:\n\t\t\t\tAssert(state.getInExpressionEvaluation() == true, \"Not in expression evaluation mode\");\n\t\t\t\tstate.setInExpressionEvaluation(false);\n\t\t\t\tbreak;\n\n\t\t\tcase EvalOutput:\n\n\t\t\t\t// If the expression turned out to be empty, there may not be\n\t\t\t\t// anything on the stack\n\t\t\t\tif (state.getEvaluationStack().size() > 0) {\n\n\t\t\t\t\tRTObject output = state.popEvaluationStack();\n\n\t\t\t\t\t// Functions may evaluate to Void, in which case we skip\n\t\t\t\t\t// output\n\t\t\t\t\tif (!(output instanceof Void)) {\n\t\t\t\t\t\t// TODO: Should we really always blanket convert to\n\t\t\t\t\t\t// string?\n\t\t\t\t\t\t// It would be okay to have numbers in the output stream\n\t\t\t\t\t\t// the\n\t\t\t\t\t\t// only problem is when exporting text for viewing, it\n\t\t\t\t\t\t// skips over numbers etc.\n\t\t\t\t\t\tStringValue text = new StringValue(output.toString());\n\n\t\t\t\t\t\tstate.pushToOutputStream(text);\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase NoOp:\n\t\t\t\tbreak;\n\n\t\t\tcase Duplicate:\n\t\t\t\tstate.pushEvaluationStack(state.peekEvaluationStack());\n\t\t\t\tbreak;\n\n\t\t\tcase PopEvaluatedValue:\n\t\t\t\tstate.popEvaluationStack();\n\t\t\t\tbreak;\n\n\t\t\tcase PopFunction:\n\t\t\tcase PopTunnel:\n\n\t\t\t\tPushPopType popType = evalCommand.getCommandType() == ControlCommand.CommandType.PopFunction\n\t\t\t\t\t\t? PushPopType.Function\n\t\t\t\t\t\t: PushPopType.Tunnel;\n\n\t\t\t\t// Tunnel onwards is allowed to specify an optional override\n\t\t\t\t// divert to go to immediately after returning: ->-> target\n\t\t\t\tDivertTargetValue overrideTunnelReturnTarget = null;\n\t\t\t\tif (popType == PushPopType.Tunnel) {\n\t\t\t\t\tRTObject popped = state.popEvaluationStack();\n\n\t\t\t\t\tif (popped instanceof DivertTargetValue) {\n\t\t\t\t\t\toverrideTunnelReturnTarget = (DivertTargetValue) popped;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (overrideTunnelReturnTarget == null) {\n\t\t\t\t\t\tAssert(popped instanceof Void, \"Expected void if ->-> doesn't override target\");\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (state.tryExitFunctionEvaluationFromGame()) {\n\t\t\t\t\tbreak;\n\t\t\t\t} else if (state.getCallStack().getCurrentElement().type != popType || !state.getCallStack().canPop()) {\n\n\t\t\t\t\tHashMap<PushPopType, String> names = new HashMap<>();\n\t\t\t\t\tnames.put(PushPopType.Function, \"function return statement (~ return)\");\n\t\t\t\t\tnames.put(PushPopType.Tunnel, \"tunnel onwards statement (->->)\");\n\n\t\t\t\t\tString expected = names.get(state.getCallStack().getCurrentElement().type);\n\t\t\t\t\tif (!state.getCallStack().canPop()) {\n\t\t\t\t\t\texpected = \"end of flow (-> END or choice)\";\n\t\t\t\t\t}\n\n\t\t\t\t\tString errorMsg = String.format(\"Found %s, when expected %s\", names.get(popType), expected);\n\n\t\t\t\t\terror(errorMsg);\n\t\t\t\t}\n\n\t\t\t\telse {\n\t\t\t\t\tstate.popCallstack();\n\n\t\t\t\t\t// Does tunnel onwards override by diverting to a new ->->\n\t\t\t\t\t// target?\n\t\t\t\t\tif (overrideTunnelReturnTarget != null)\n\t\t\t\t\t\tstate.setDivertedPointer(pointerAtPath(overrideTunnelReturnTarget.getTargetPath()));\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase BeginString:\n\t\t\t\tstate.pushToOutputStream(evalCommand);\n\n\t\t\t\tAssert(state.getInExpressionEvaluation() == true,\n\t\t\t\t\t\t\"Expected to be in an expression when evaluating a string\");\n\t\t\t\tstate.setInExpressionEvaluation(false);\n\t\t\t\tbreak;\n\n\t\t\tcase EndString:\n\n\t\t\t\t// Since we're iterating backward through the content,\n\t\t\t\t// build a stack so that when we build the string,\n\t\t\t\t// it's in the right order\n\t\t\t\tStack<RTObject> contentStackForString = new Stack<>();\n\n\t\t\t\tint outputCountConsumed = 0;\n\t\t\t\tfor (int i = state.getOutputStream().size() - 1; i >= 0; --i) {\n\t\t\t\t\tRTObject obj = state.getOutputStream().get(i);\n\n\t\t\t\t\toutputCountConsumed++;\n\n\t\t\t\t\tControlCommand command = obj instanceof ControlCommand ? (ControlCommand) obj : null;\n\n\t\t\t\t\tif (command != null && command.getCommandType() == ControlCommand.CommandType.BeginString) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (obj instanceof StringValue)\n\t\t\t\t\t\tcontentStackForString.push(obj);\n\t\t\t\t}\n\n\t\t\t\t// Consume the content that was produced for this string\n\t\t\t\tstate.popFromOutputStream(outputCountConsumed);\n\n\t\t\t\t// Build String out of the content we collected\n\t\t\t\tStringBuilder sb = new StringBuilder();\n\t\t\t\twhile (contentStackForString.size() > 0) {\n\t\t\t\t\tRTObject c = contentStackForString.pop();\n\t\t\t\t\tsb.append(c.toString());\n\t\t\t\t}\n\n\t\t\t\t// Return to expression evaluation (from content mode)\n\t\t\t\tstate.setInExpressionEvaluation(true);\n\t\t\t\tstate.pushEvaluationStack(new StringValue(sb.toString()));\n\t\t\t\tbreak;\n\n\t\t\tcase ChoiceCount:\n\t\t\t\tchoiceCount = state.getGeneratedChoices().size();\n\t\t\t\tstate.pushEvaluationStack(new IntValue(choiceCount));\n\t\t\t\tbreak;\n\n\t\t\tcase Turns:\n\t\t\t\tstate.pushEvaluationStack(new IntValue(state.getCurrentTurnIndex() + 1));\n\t\t\t\tbreak;\n\n\t\t\tcase TurnsSince:\n\t\t\tcase ReadCount:\n\t\t\t\tRTObject target = state.popEvaluationStack();\n\t\t\t\tif (!(target instanceof DivertTargetValue)) {\n\t\t\t\t\tString extraNote = \"\";\n\t\t\t\t\tif (target instanceof IntValue)\n\t\t\t\t\t\textraNote = \". Did you accidentally pass a read count ('knot_name') instead of a target ('-> knot_name')?\";\n\t\t\t\t\terror(\"TURNS_SINCE expected a divert target (knot, stitch, label name), but saw \" + target\n\t\t\t\t\t\t\t+ extraNote);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tDivertTargetValue divertTarget = target instanceof DivertTargetValue ? (DivertTargetValue) target\n\t\t\t\t\t\t: null;\n\n\t\t\t\tRTObject otmp = contentAtPath(divertTarget.getTargetPath()).correctObj();\n\t\t\t\tContainer container = otmp instanceof Container ? (Container) otmp : null;\n\n\t\t\t\tint eitherCount;\n\n\t\t\t\tif (container != null) {\n\t\t\t\t\tif (evalCommand.getCommandType() == ControlCommand.CommandType.TurnsSince)\n\t\t\t\t\t\teitherCount = state.turnsSinceForContainer(container);\n\t\t\t\t\telse\n\t\t\t\t\t\teitherCount = state.visitCountForContainer(container);\n\t\t\t\t} else {\n\t\t\t\t\tif (evalCommand.getCommandType() == ControlCommand.CommandType.TurnsSince)\n\t\t\t\t\t\teitherCount = -1; // turn count, default to never/unknown\n\t\t\t\t\telse\n\t\t\t\t\t\teitherCount = 0; // visit count, assume 0 to default to allowing entry\n\n\t\t\t\t\twarning(\"Failed to find container for \" + evalCommand.toString() + \" lookup at \"\n\t\t\t\t\t\t\t+ divertTarget.getTargetPath().toString());\n\t\t\t\t}\n\n\t\t\t\tstate.pushEvaluationStack(new IntValue(eitherCount));\n\t\t\t\tbreak;\n\n\t\t\tcase Random: {\n\t\t\t\tIntValue maxInt = null;\n\n\t\t\t\tRTObject o = state.popEvaluationStack();\n\n\t\t\t\tif (o instanceof IntValue)\n\t\t\t\t\tmaxInt = (IntValue) o;\n\n\t\t\t\tIntValue minInt = null;\n\n\t\t\t\to = state.popEvaluationStack();\n\n\t\t\t\tif (o instanceof IntValue)\n\t\t\t\t\tminInt = (IntValue) o;\n\n\t\t\t\tif (minInt == null)\n\t\t\t\t\terror(\"Invalid value for minimum parameter of RANDOM(min, max)\");\n\n\t\t\t\tif (maxInt == null)\n\t\t\t\t\terror(\"Invalid value for maximum parameter of RANDOM(min, max)\");\n\n\t\t\t\t// +1 because it's inclusive of min and max, for e.g.\n\t\t\t\t// RANDOM(1,6) for a dice roll.\n\t\t\t\tint randomRange = maxInt.value - minInt.value + 1;\n\t\t\t\tif (randomRange <= 0)\n\t\t\t\t\terror(\"RANDOM was called with minimum as \" + minInt.value + \" and maximum as \" + maxInt.value\n\t\t\t\t\t\t\t+ \". The maximum must be larger\");\n\n\t\t\t\tint resultSeed = state.getStorySeed() + state.getPreviousRandom();\n\t\t\t\tRandom random = new Random(resultSeed);\n\n\t\t\t\tint nextRandom = random.nextInt(Integer.MAX_VALUE);\n\t\t\t\tint chosenValue = (nextRandom % randomRange) + minInt.value;\n\t\t\t\tstate.pushEvaluationStack(new IntValue(chosenValue));\n\n\t\t\t\t// Next random number (rather than keeping the Random object\n\t\t\t\t// around)\n\t\t\t\tstate.setPreviousRandom(state.getPreviousRandom() + 1);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase SeedRandom: {\n\t\t\t\tIntValue seed = null;\n\n\t\t\t\tRTObject o = state.popEvaluationStack();\n\n\t\t\t\tif (o instanceof IntValue)\n\t\t\t\t\tseed = (IntValue) o;\n\n\t\t\t\tif (seed == null)\n\t\t\t\t\terror(\"Invalid value passed to SEED_RANDOM\");\n\n\t\t\t\t// Story seed affects both RANDOM and shuffle behaviour\n\t\t\t\tstate.setStorySeed(seed.value);\n\t\t\t\tstate.setPreviousRandom(0);\n\n\t\t\t\t// SEED_RANDOM returns nothing.\n\t\t\t\tstate.pushEvaluationStack(new Void());\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase VisitIndex:\n\t\t\t\tint count = state.visitCountForContainer(state.getCurrentPointer().container) - 1; // index\n\t\t\t\t// not\n\t\t\t\t// count\n\t\t\t\tstate.pushEvaluationStack(new IntValue(count));\n\t\t\t\tbreak;\n\n\t\t\tcase SequenceShuffleIndex:\n\t\t\t\tint shuffleIndex = nextSequenceShuffleIndex();\n\t\t\t\tstate.pushEvaluationStack(new IntValue(shuffleIndex));\n\t\t\t\tbreak;\n\n\t\t\tcase StartThread:\n\t\t\t\t// Handled in main step function\n\t\t\t\tbreak;\n\n\t\t\tcase Done:\n\n\t\t\t\t// We may exist in the context of the initial\n\t\t\t\t// act of creating the thread, or in the context of\n\t\t\t\t// evaluating the content.\n\t\t\t\tif (state.getCallStack().canPopThread()) {\n\t\t\t\t\tstate.getCallStack().popThread();\n\t\t\t\t}\n\n\t\t\t\t// In normal flow - allow safe exit without warning\n\t\t\t\telse {\n\t\t\t\t\tstate.setDidSafeExit(true);\n\n\t\t\t\t\t// Stop flow in current thread\n\t\t\t\t\tstate.setCurrentPointer(Pointer.Null);\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\n\t\t\t// Force flow to end completely\n\t\t\tcase End:\n\t\t\t\tstate.forceEnd();\n\t\t\t\tbreak;\n\n\t\t\tcase ListFromInt: {\n\t\t\t\tIntValue intVal = null;\n\n\t\t\t\tRTObject o = state.popEvaluationStack();\n\n\t\t\t\tif (o instanceof IntValue)\n\t\t\t\t\tintVal = (IntValue) o;\n\n\t\t\t\tStringValue listNameVal = null;\n\n\t\t\t\to = state.popEvaluationStack();\n\n\t\t\t\tif (o instanceof StringValue)\n\t\t\t\t\tlistNameVal = (StringValue) o;\n\n\t\t\t\tif (intVal == null) {\n\t\t\t\t\tthrow new StoryException(\"Passed non-integer when creating a list element from a numerical value.\");\n\t\t\t\t}\n\n\t\t\t\tListValue generatedListValue = null;\n\n\t\t\t\tListDefinition foundListDef = listDefinitions.getListDefinition(listNameVal.value);\n\n\t\t\t\tif (foundListDef != null) {\n\t\t\t\t\tInkListItem foundItem;\n\n\t\t\t\t\tfoundItem = foundListDef.getItemWithValue(intVal.value);\n\n\t\t\t\t\tif (foundItem != null) {\n\t\t\t\t\t\tgeneratedListValue = new ListValue(foundItem, intVal.value);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tthrow new StoryException(\"Failed to find List called \" + listNameVal.value);\n\t\t\t\t}\n\n\t\t\t\tif (generatedListValue == null)\n\t\t\t\t\tgeneratedListValue = new ListValue();\n\n\t\t\t\tstate.pushEvaluationStack(generatedListValue);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase ListRange: {\n\t\t\t\tRTObject p = state.popEvaluationStack();\n\t\t\t\tValue<?> max = p instanceof Value ? (Value<?>) p : null;\n\n\t\t\t\tp = state.popEvaluationStack();\n\t\t\t\tValue<?> min = p instanceof Value ? (Value<?>) p : null;\n\n\t\t\t\tp = state.popEvaluationStack();\n\t\t\t\tListValue targetList = p instanceof ListValue ? (ListValue) p : null;\n\n\t\t\t\tif (targetList == null || min == null || max == null)\n\t\t\t\t\tthrow new StoryException(\"Expected List, minimum and maximum for LIST_RANGE\");\n\n\t\t\t\tInkList result = targetList.value.listWithSubRange(min.getValueObject(), max.getValueObject());\n\n\t\t\t\tstate.pushEvaluationStack(new ListValue(result));\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase ListRandom: {\n\n\t\t\t\tRTObject o = state.popEvaluationStack();\n\t\t\t\tListValue listVal = o instanceof ListValue ? (ListValue) o : null;\n\n\t\t\t\tif (listVal == null)\n\t\t\t\t\tthrow new StoryException(\"Expected list for LIST_RANDOM\");\n\n\t\t\t\tInkList list = listVal.value;\n\n\t\t\t\tInkList newList = null;\n\n\t\t\t\t// List was empty: return empty list\n\t\t\t\tif (list.size() == 0) {\n\t\t\t\t\tnewList = new InkList();\n\t\t\t\t}\n\n\t\t\t\t// Non-empty source list\n\t\t\t\telse {\n\t\t\t\t\t// Generate a random index for the element to take\n\t\t\t\t\tint resultSeed = state.getStorySeed() + state.getPreviousRandom();\n\t\t\t\t\tRandom random = new Random(resultSeed);\n\n\t\t\t\t\tint nextRandom = random.nextInt(Integer.MAX_VALUE);\n\t\t\t\t\tint listItemIndex = nextRandom % list.size();\n\n\t\t\t\t\t// Iterate through to get the random element\n\t\t\t\t\tIterator<Entry<InkListItem, Integer>> listEnumerator = list.entrySet().iterator();\n\n\t\t\t\t\tEntry<InkListItem, Integer> randomItem = null;\n\n\t\t\t\t\tfor (int i = 0; i <= listItemIndex; i++) {\n\t\t\t\t\t\trandomItem = listEnumerator.next();\n\t\t\t\t\t}\n\n\t\t\t\t\t// Origin list is simply the origin of the one element\n\t\t\t\t\tnewList = new InkList(randomItem.getKey().getOriginName(), this);\n\t\t\t\t\tnewList.put(randomItem.getKey(), randomItem.getValue());\n\n\t\t\t\t\tstate.setPreviousRandom(nextRandom);\n\t\t\t\t}\n\n\t\t\t\tstate.pushEvaluationStack(new ListValue(newList));\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tdefault:\n\t\t\t\terror(\"unhandled ControlCommand: \" + evalCommand);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\t\t// Variable assignment\n\t\telse if (contentObj instanceof VariableAssignment)\n\n\t\t{\n\t\t\tVariableAssignment varAss = (VariableAssignment) contentObj;\n\t\t\tRTObject assignedVal = state.popEvaluationStack();\n\n\t\t\t// When in temporary evaluation, don't create new variables purely\n\t\t\t// within\n\t\t\t// the temporary context, but attempt to create them globally\n\t\t\t// var prioritiseHigherInCallStack = _temporaryEvaluationContainer\n\t\t\t// != null;\n\n\t\t\tstate.getVariablesState().assign(varAss, assignedVal);\n\n\t\t\treturn true;\n\t\t}\n\n\t\t// Variable reference\n\t\telse if (contentObj instanceof VariableReference) {\n\t\t\tVariableReference varRef = (VariableReference) contentObj;\n\t\t\tRTObject foundValue = null;\n\n\t\t\t// Explicit read count value\n\t\t\tif (varRef.getPathForCount() != null) {\n\n\t\t\t\tContainer container = varRef.getContainerForCount();\n\t\t\t\tint count = state.visitCountForContainer(container);\n\t\t\t\tfoundValue = new IntValue(count);\n\t\t\t}\n\n\t\t\t// Normal variable reference\n\t\t\telse {\n\n\t\t\t\tfoundValue = state.getVariablesState().getVariableWithName(varRef.getName());\n\n\t\t\t\tif (foundValue == null) {\n\t\t\t\t\twarning(\"Variable not found: '\" + varRef.getName()\n\t\t\t\t\t\t\t+ \"'. Using default value of 0 (false). This can happen with temporary variables if the declaration hasn't yet been hit. Globals are always given a default value on load if a value doesn't exist in the save state.\");\n\t\t\t\t\tfoundValue = new IntValue(0);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstate.pushEvaluationStack(foundValue);\n\n\t\t\treturn true;\n\t\t}\n\n\t\t// Native function call\n\t\telse if (contentObj instanceof NativeFunctionCall) {\n\t\t\tNativeFunctionCall func = (NativeFunctionCall) contentObj;\n\t\t\tList<RTObject> funcParams = state.popEvaluationStack(func.getNumberOfParameters());\n\n\t\t\tRTObject result = func.call(funcParams);\n\t\t\tstate.pushEvaluationStack(result);\n\t\t\treturn true;\n\t\t}\n\n\t\t// No control content, must be ordinary content\n\t\treturn false;\n\t}\n\n\t// Assumption: prevText is the snapshot where we saw a newline, and we're\n\t// checking whether we're really done\n\t// with that line. Therefore prevText will definitely end in a newline.\n\t//\n\t// We take tags into account too, so that a tag following a content line:\n\t// Content\n\t// # tag\n\t// ... doesn't cause the tag to be wrongly associated with the content above.\n\tenum OutputStateChange {\n\t\tNoChange, ExtendedBeyondNewline, NewlineRemoved\n\t}\n\n\tOutputStateChange calculateNewlineOutputStateChange(String prevText, String currText, int prevTagCount,\n\t\t\tint currTagCount) {\n\t\t// Simple case: nothing's changed, and we still have a newline\n\t\t// at the end of the current content\n\t\tboolean newlineStillExists = currText.length() >= prevText.length()\n\t\t\t\t&& currText.charAt(prevText.length() - 1) == '\\n';\n\t\tif (prevTagCount == currTagCount && prevText.length() == currText.length() && newlineStillExists)\n\t\t\treturn OutputStateChange.NoChange;\n\n\t\t// Old newline has been removed, it wasn't the end of the line after all\n\t\tif (!newlineStillExists) {\n\t\t\treturn OutputStateChange.NewlineRemoved;\n\t\t}\n\n\t\t// Tag added - definitely the start of a new line\n\t\tif (currTagCount > prevTagCount)\n\t\t\treturn OutputStateChange.ExtendedBeyondNewline;\n\n\t\t// There must be new content - check whether it's just whitespace\n\t\tfor (int i = prevText.length(); i < currText.length(); i++) {\n\t\t\tchar c = currText.charAt(i);\n\t\t\tif (c != ' ' && c != '\\t') {\n\t\t\t\treturn OutputStateChange.ExtendedBeyondNewline;\n\t\t\t}\n\t\t}\n\n\t\t// There's new text but it's just spaces and tabs, so there's still the\n\t\t// potential\n\t\t// for glue to kill the newline.\n\t\treturn OutputStateChange.NoChange;\n\t}\n\n\tChoice processChoice(ChoicePoint choicePoint) throws Exception {\n\t\tboolean showChoice = true;\n\n\t\t// Don't create choice if choice point doesn't pass conditional\n\t\tif (choicePoint.hasCondition()) {\n\t\t\tRTObject conditionValue = state.popEvaluationStack();\n\t\t\tif (!isTruthy(conditionValue)) {\n\t\t\t\tshowChoice = false;\n\t\t\t}\n\t\t}\n\n\t\tString startText = \"\";\n\t\tString choiceOnlyText = \"\";\n\n\t\tif (choicePoint.hasChoiceOnlyContent()) {\n\t\t\tStringValue choiceOnlyStrVal = (StringValue) state.popEvaluationStack();\n\t\t\tchoiceOnlyText = choiceOnlyStrVal.value;\n\t\t}\n\n\t\tif (choicePoint.hasStartContent()) {\n\t\t\tStringValue startStrVal = (StringValue) state.popEvaluationStack();\n\t\t\tstartText = startStrVal.value;\n\t\t}\n\n\t\t// Don't create choice if player has already read this content\n\t\tif (choicePoint.isOnceOnly()) {\n\t\t\tint visitCount = state.visitCountForContainer(choicePoint.getChoiceTarget());\n\t\t\tif (visitCount > 0) {\n\t\t\t\tshowChoice = false;\n\t\t\t}\n\t\t}\n\n\t\t// We go through the full process of creating the choice above so\n\t\t// that we consume the content for it, since otherwise it'll\n\t\t// be shown on the output stream.\n\t\tif (!showChoice) {\n\t\t\treturn null;\n\t\t}\n\n\t\tChoice choice = new Choice();\n\t\tchoice.targetPath = choicePoint.getPathOnChoice();\n\t\tchoice.sourcePath = choicePoint.getPath().toString();\n\t\tchoice.isInvisibleDefault = choicePoint.isInvisibleDefault();\n\n\t\t// We need to capture the state of the callstack at the point where\n\t\t// the choice was generated, since after the generation of this choice\n\t\t// we may go on to pop out from a tunnel (possible if the choice was\n\t\t// wrapped in a conditional), or we may pop out from a thread,\n\t\t// at which point that thread is discarded.\n\t\t// Fork clones the thread, gives it a new ID, but without affecting\n\t\t// the thread stack itself.\n\t\tchoice.setThreadAtGeneration(state.getCallStack().forkThread());\n\n\t\t// Set final text for the choice\n\t\tchoice.setText((startText + choiceOnlyText).trim());\n\n\t\treturn choice;\n\t}\n\n\t/**\n\t * Unwinds the callstack. Useful to reset the Story's evaluation without\n\t * actually changing any meaningful state, for example if you want to exit a\n\t * section of story prematurely and tell it to go elsewhere with a call to\n\t * ChoosePathString(...). Doing so without calling ResetCallstack() could cause\n\t * unexpected issues if, for example, the Story was in a tunnel already.\n\t */\n\tpublic void resetCallstack() throws Exception {\n\t\tifAsyncWeCant(\"ResetCallstack\");\n\n\t\tstate.forceEnd();\n\t}\n\n\tvoid resetErrors() {\n\t\tstate.resetErrors();\n\t}\n\n\tvoid resetGlobals() throws Exception {\n\t\tif (mainContentContainer.getNamedContent().containsKey(\"global decl\")) {\n\t\t\tfinal Pointer originalPointer = new Pointer(state.getCurrentPointer());\n\n\t\t\tchoosePath(new Path(\"global decl\"), false);\n\n\t\t\t// Continue, but without validating external bindings,\n\t\t\t// since we may be doing this reset at initialisation time.\n\t\t\tcontinueInternal();\n\n\t\t\tstate.setCurrentPointer(originalPointer);\n\t\t}\n\n\t\tstate.getVariablesState().snapshotDefaultGlobals();\n\t}\n\n\t/**\n\t * Reset the Story back to its initial state as it was when it was first\n\t * constructed.\n\t */\n\tpublic void resetState() throws Exception {\n\t\t// TODO: Could make this possible\n\t\tifAsyncWeCant(\"ResetState\");\n\n\t\tstate = new StoryState(this);\n\n\t\tstate.getVariablesState().setVariableChangedEvent(this);\n\n\t\tresetGlobals();\n\t}\n\n\tPointer pointerAtPath(Path path) throws Exception {\n\t\tif (path.getLength() == 0)\n\t\t\treturn Pointer.Null;\n\n\t\tfinal Pointer p = new Pointer();\n\n\t\tint pathLengthToUse = path.getLength();\n\t\tfinal SearchResult result;\n\n\t\tif (path.getLastComponent().isIndex()) {\n\t\t\tpathLengthToUse = path.getLength() - 1;\n\t\t\tresult = new SearchResult(mainContentContainer.contentAtPath(path, 0, pathLengthToUse));\n\t\t\tp.container = result.getContainer();\n\t\t\tp.index = path.getLastComponent().getIndex();\n\t\t} else {\n\t\t\tresult = new SearchResult(mainContentContainer.contentAtPath(path));\n\t\t\tp.container = result.getContainer();\n\t\t\tp.index = -1;\n\t\t}\n\n\t\tif (result.obj == null || result.obj == mainContentContainer && pathLengthToUse > 0)\n\t\t\terror(\"Failed to find content at path '\" + path + \"', and no approximation of it was possible.\");\n\t\telse if (result.approximate)\n\t\t\twarning(\"Failed to find content at path '\" + path + \"', so it was approximated to: '\" + result.obj.getPath()\n\t\t\t\t\t+ \"'.\");\n\n\t\treturn p;\n\t}\n\n\tvoid step() throws Exception {\n\n\t\tboolean shouldAddToStream = true;\n\n\t\t// Get current content\n\t\tfinal Pointer pointer = new Pointer();\n\t\tpointer.assign(state.getCurrentPointer());\n\n\t\tif (pointer.isNull()) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Step directly to the first element of content in a container (if\n\t\t// necessary)\n\t\tRTObject r = pointer.resolve();\n\t\tContainer containerToEnter = r instanceof Container ? (Container) r : null;\n\n\t\twhile (containerToEnter != null) {\n\n\t\t\t// Mark container as being entered\n\t\t\tvisitContainer(containerToEnter, true);\n\n\t\t\t// No content? the most we can do is step past it\n\t\t\tif (containerToEnter.getContent().size() == 0)\n\t\t\t\tbreak;\n\n\t\t\tpointer.assign(Pointer.startOf(containerToEnter));\n\n\t\t\tr = pointer.resolve();\n\t\t\tcontainerToEnter = r instanceof Container ? (Container) r : null;\n\t\t}\n\n\t\tstate.setCurrentPointer(pointer);\n\n\t\tif (profiler != null) {\n\t\t\tprofiler.step(state.getCallStack());\n\t\t}\n\n\t\t// Is the current content Object:\n\t\t// - Normal content\n\t\t// - Or a logic/flow statement - if so, do it\n\t\t// Stop flow if we hit a stack pop when we're unable to pop (e.g.\n\t\t// return/done statement in knot\n\t\t// that was diverted to rather than called as a function)\n\t\tRTObject currentContentObj = pointer.resolve();\n\t\tboolean isLogicOrFlowControl = performLogicAndFlowControl(currentContentObj);\n\n\t\t// Has flow been forced to end by flow control above?\n\t\tif (state.getCurrentPointer().isNull()) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (isLogicOrFlowControl) {\n\t\t\tshouldAddToStream = false;\n\t\t}\n\n\t\t// Choice with condition?\n\t\tChoicePoint choicePoint = currentContentObj instanceof ChoicePoint ? (ChoicePoint) currentContentObj : null;\n\t\tif (choicePoint != null) {\n\t\t\tChoice choice = processChoice(choicePoint);\n\t\t\tif (choice != null) {\n\t\t\t\tstate.getGeneratedChoices().add(choice);\n\t\t\t}\n\n\t\t\tcurrentContentObj = null;\n\t\t\tshouldAddToStream = false;\n\t\t}\n\n\t\t// If the container has no content, then it will be\n\t\t// the \"content\" itself, but we skip over it.\n\t\tif (currentContentObj instanceof Container) {\n\t\t\tshouldAddToStream = false;\n\t\t}\n\n\t\t// Content to add to evaluation stack or the output stream\n\t\tif (shouldAddToStream) {\n\n\t\t\t// If we're pushing a variable pointer onto the evaluation stack,\n\t\t\t// ensure that it's specific\n\t\t\t// to our current (possibly temporary) context index. And make a\n\t\t\t// copy of the pointer\n\t\t\t// so that we're not editing the original runtime Object.\n\t\t\tVariablePointerValue varPointer = currentContentObj instanceof VariablePointerValue\n\t\t\t\t\t? (VariablePointerValue) currentContentObj\n\t\t\t\t\t: null;\n\n\t\t\tif (varPointer != null && varPointer.getContextIndex() == -1) {\n\n\t\t\t\t// Create new Object so we're not overwriting the story's own\n\t\t\t\t// data\n\t\t\t\tint contextIdx = state.getCallStack().contextForVariableNamed(varPointer.getVariableName());\n\t\t\t\tcurrentContentObj = new VariablePointerValue(varPointer.getVariableName(), contextIdx);\n\t\t\t}\n\n\t\t\t// Expression evaluation content\n\t\t\tif (state.getInExpressionEvaluation()) {\n\t\t\t\tstate.pushEvaluationStack(currentContentObj);\n\t\t\t}\n\t\t\t// Output stream content (i.e. not expression evaluation)\n\t\t\telse {\n\t\t\t\tstate.pushToOutputStream(currentContentObj);\n\t\t\t}\n\t\t}\n\n\t\t// Increment the content pointer, following diverts if necessary\n\t\tnextContent();\n\n\t\t// Starting a thread should be done after the increment to the content\n\t\t// pointer,\n\t\t// so that when returning from the thread, it returns to the content\n\t\t// after this instruction.\n\t\tControlCommand controlCmd = currentContentObj instanceof ControlCommand ? (ControlCommand) currentContentObj\n\t\t\t\t: null;\n\t\tif (controlCmd != null && controlCmd.getCommandType() == ControlCommand.CommandType.StartThread) {\n\t\t\tstate.getCallStack().pushThread();\n\t\t}\n\t}\n\n\t/**\n\t * The Story itself in JSON representation.\n\t *\n\t * @throws Exception\n\t */\n\tpublic String toJson() throws Exception {\n\t\t// return ToJsonOld();\n\t\tSimpleJson.Writer writer = new SimpleJson.Writer();\n\t\ttoJson(writer);\n\t\treturn writer.toString();\n\t}\n\n\t/**\n\t * The Story itself in JSON representation.\n\t *\n\t * @throws Exception\n\t */\n\tpublic void toJson(OutputStream stream) throws Exception {\n\t\tSimpleJson.Writer writer = new SimpleJson.Writer(stream);\n\t\ttoJson(writer);\n\t}\n\n\tvoid toJson(SimpleJson.Writer writer) throws Exception {\n\t\twriter.writeObjectStart();\n\n\t\twriter.writeProperty(\"inkVersion\", inkVersionCurrent);\n\n\t\t// Main container content\n\t\twriter.writeProperty(\"root\", new InnerWriter() {\n\n\t\t\t@Override\n\t\t\tpublic void write(Writer w) throws Exception {\n\t\t\t\tJson.writeRuntimeContainer(w, mainContentContainer);\n\t\t\t}\n\t\t});\n\n\t\t// List definitions\n\t\tif (listDefinitions != null) {\n\n\t\t\twriter.writePropertyStart(\"listDefs\");\n\t\t\twriter.writeObjectStart();\n\n\t\t\tfor (ListDefinition def : listDefinitions.getLists()) {\n\t\t\t\twriter.writePropertyStart(def.getName());\n\t\t\t\twriter.writeObjectStart();\n\n\t\t\t\tfor (Entry<InkListItem, Integer> itemToVal : def.getItems().entrySet()) {\n\t\t\t\t\tInkListItem item = itemToVal.getKey();\n\t\t\t\t\tint val = itemToVal.getValue();\n\t\t\t\t\twriter.writeProperty(item.getItemName(), val);\n\t\t\t\t}\n\n\t\t\t\twriter.writeObjectEnd();\n\t\t\t\twriter.writePropertyEnd();\n\t\t\t}\n\n\t\t\twriter.writeObjectEnd();\n\t\t\twriter.writePropertyEnd();\n\t\t}\n\n\t\twriter.writeObjectEnd();\n\t}\n\n\tboolean tryFollowDefaultInvisibleChoice() throws Exception {\n\t\tList<Choice> allChoices = state.getCurrentChoices();\n\n\t\t// Is a default invisible choice the ONLY choice?\n\t\t// var invisibleChoices = allChoices.Where (c =>\n\t\t// c.choicePoint.isInvisibleDefault).ToList();\n\t\tArrayList<Choice> invisibleChoices = new ArrayList<>();\n\t\tfor (Choice c : allChoices) {\n\t\t\tif (c.isInvisibleDefault) {\n\t\t\t\tinvisibleChoices.add(c);\n\t\t\t}\n\t\t}\n\n\t\tif (invisibleChoices.size() == 0 || allChoices.size() > invisibleChoices.size())\n\t\t\treturn false;\n\n\t\tChoice choice = invisibleChoices.get(0);\n\n\t\t// Invisible choice may have been generated on a different thread,\n\t\t// in which case we need to restore it before we continue\n\t\tstate.getCallStack().setCurrentThread(choice.getThreadAtGeneration());\n\n\t\t// If there's a chance that this state will be rolled back to before\n\t\t// the invisible choice then make sure that the choice thread is\n\t\t// left intact, and it isn't re-entered in an old state.\n\t\tif (stateSnapshotAtLastNewline != null)\n\t\t\tstate.getCallStack().setCurrentThread(state.getCallStack().forkThread());\n\n\t\tchoosePath(choice.targetPath, false);\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * Remove a binding for a named EXTERNAL ink function.\n\t */\n\tpublic void unbindExternalFunction(String funcName) throws Exception {\n\t\tifAsyncWeCant(\"unbind an external a function\");\n\t\tAssert(externals.containsKey(funcName), \"Function '\" + funcName + \"' has not been bound.\");\n\t\texternals.remove(funcName);\n\t}\n\n\t/**\n\t * Check that all EXTERNAL ink functions have a valid bound C# function. Note\n\t * that this is automatically called on the first call to Continue().\n\t */\n\tpublic void validateExternalBindings() throws Exception {\n\t\tHashSet<String> missingExternals = new HashSet<>();\n\n\t\tvalidateExternalBindings(mainContentContainer, missingExternals);\n\t\thasValidatedExternals = true;\n\t\t// No problem! Validation complete\n\t\tif (missingExternals.size() == 0) {\n\t\t\thasValidatedExternals = true;\n\t\t} else { // Error for all missing externals\n\n\t\t\tStringBuilder join = new StringBuilder();\n\t\t\tboolean first = true;\n\t\t\tfor (String item : missingExternals) {\n\t\t\t\tif (first)\n\t\t\t\t\tfirst = false;\n\t\t\t\telse\n\t\t\t\t\tjoin.append(\", \");\n\n\t\t\t\tjoin.append(item);\n\t\t\t}\n\n\t\t\tString message = String.format(\"ERROR: Missing function binding for external%s: '%s' %s\",\n\t\t\t\t\tmissingExternals.size() > 1 ? \"s\" : \"\", join.toString(),\n\t\t\t\t\tallowExternalFunctionFallbacks ? \", and no fallback ink function found.\"\n\t\t\t\t\t\t\t: \" (ink fallbacks disabled)\");\n\n\t\t\terror(message);\n\t\t}\n\t}\n\n\tvoid validateExternalBindings(Container c, HashSet<String> missingExternals) throws Exception {\n\t\tfor (RTObject innerContent : c.getContent()) {\n\t\t\tContainer container = innerContent instanceof Container ? (Container) innerContent : null;\n\t\t\tif (container == null || !container.hasValidName())\n\t\t\t\tvalidateExternalBindings(innerContent, missingExternals);\n\t\t}\n\n\t\tfor (INamedContent innerKeyValue : c.getNamedContent().values()) {\n\t\t\tvalidateExternalBindings(innerKeyValue instanceof RTObject ? (RTObject) innerKeyValue : (RTObject) null,\n\t\t\t\t\tmissingExternals);\n\t\t}\n\t}\n\n\tvoid validateExternalBindings(RTObject o, HashSet<String> missingExternals) throws Exception {\n\t\tContainer container = o instanceof Container ? (Container) o : null;\n\n\t\tif (container != null) {\n\t\t\tvalidateExternalBindings(container, missingExternals);\n\t\t\treturn;\n\t\t}\n\n\t\tDivert divert = o instanceof Divert ? (Divert) o : null;\n\n\t\tif (divert != null && divert.isExternal()) {\n\t\t\tString name = divert.getTargetPathString();\n\n\t\t\tif (!externals.containsKey(name)) {\n\n\t\t\t\tif (allowExternalFunctionFallbacks) {\n\t\t\t\t\tboolean fallbackFound = mainContentContainer.getNamedContent().containsKey(name);\n\t\t\t\t\tif (!fallbackFound) {\n\t\t\t\t\t\tmissingExternals.add(name);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tmissingExternals.add(name);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid visitChangedContainersDueToDivert() throws Exception {\n\t\tfinal Pointer previousPointer = new Pointer(state.getPreviousPointer());\n\t\tfinal Pointer pointer = new Pointer(state.getCurrentPointer());\n\n\t\t// Unless we're pointing *directly* at a piece of content, we don't do\n\t\t// counting here. Otherwise, the main stepping function will do the counting.\n\t\tif (pointer.isNull() || pointer.index == -1)\n\t\t\treturn;\n\n\t\t// First, find the previously open set of containers\n\n\t\tprevContainers.clear();\n\n\t\tif (!previousPointer.isNull()) {\n\n\t\t\tContainer prevAncestor = null;\n\n\t\t\tif (previousPointer.resolve() instanceof Container) {\n\t\t\t\tprevAncestor = (Container) previousPointer.resolve();\n\t\t\t} else if (previousPointer.container instanceof Container) {\n\t\t\t\tprevAncestor = previousPointer.container;\n\t\t\t}\n\n\t\t\twhile (prevAncestor != null) {\n\t\t\t\tprevContainers.add(prevAncestor);\n\t\t\t\tprevAncestor = prevAncestor.getParent() instanceof Container ? (Container) prevAncestor.getParent()\n\t\t\t\t\t\t: null;\n\t\t\t}\n\t\t}\n\n\t\t// If the new Object is a container itself, it will be visited\n\t\t// automatically at the next actual\n\t\t// content step. However, we need to walk up the new ancestry to see if\n\t\t// there are more new containers\n\t\tRTObject currentChildOfContainer = pointer.resolve();\n\n\t\t// Invalid pointer? May happen if attemptingto\n\t\tif (currentChildOfContainer == null)\n\t\t\treturn;\n\n\t\tContainer currentContainerAncestor = currentChildOfContainer.getParent() instanceof Container\n\t\t\t\t? (Container) currentChildOfContainer.getParent()\n\t\t\t\t: null;\n\n\t\tboolean allChildrenEnteredAtStart = true;\n\t\twhile (currentContainerAncestor != null && (!prevContainers.contains(currentContainerAncestor)\n\t\t\t\t|| currentContainerAncestor.getCountingAtStartOnly())) {\n\n\t\t\t// Check whether this ancestor container is being entered at the\n\t\t\t// start,\n\t\t\t// by checking whether the child Object is the first.\n\t\t\tboolean enteringAtStart = currentContainerAncestor.getContent().size() > 0\n\t\t\t\t\t&& currentChildOfContainer == currentContainerAncestor.getContent().get(0)\n\t\t\t\t\t&& allChildrenEnteredAtStart;\n\n\t\t\t// Don't count it as entering at start if we're entering random somewhere within\n\t\t\t// a container B that happens to be nested at index 0 of container A. It only\n\t\t\t// counts\n\t\t\t// if we're diverting directly to the first leaf node.\n\t\t\tif (!enteringAtStart)\n\t\t\t\tallChildrenEnteredAtStart = false;\n\n\t\t\t// Mark a visit to this container\n\t\t\tvisitContainer(currentContainerAncestor, enteringAtStart);\n\n\t\t\tcurrentChildOfContainer = currentContainerAncestor;\n\t\t\tcurrentContainerAncestor = currentContainerAncestor.getParent() instanceof Container\n\t\t\t\t\t? (Container) currentContainerAncestor.getParent()\n\t\t\t\t\t: null;\n\n\t\t}\n\t}\n\n\t// Mark a container as having been visited\n\tvoid visitContainer(Container container, boolean atStart) throws Exception {\n\t\tif (!container.getCountingAtStartOnly() || atStart) {\n\t\t\tif (container.getVisitsShouldBeCounted())\n\t\t\t\tstate.incrementVisitCountForContainer(container);\n\n\t\t\tif (container.getTurnIndexShouldBeCounted())\n\t\t\t\tstate.recordTurnIndexVisitToContainer(container);\n\t\t}\n\t}\n\n\tpublic boolean allowExternalFunctionFallbacks() {\n\t\treturn allowExternalFunctionFallbacks;\n\t}\n\n\tpublic void setAllowExternalFunctionFallbacks(boolean allowExternalFunctionFallbacks) {\n\t\tthis.allowExternalFunctionFallbacks = allowExternalFunctionFallbacks;\n\t}\n\n\t/**\n\t * Evaluates a function defined in ink.\n\t *\n\t * @param functionName The name of the function as declared in ink.\n\t * @param arguments The arguments that the ink function takes, if any. Note\n\t * that we don't (can't) do any validation on the number of\n\t * arguments right now, so make sure you get it right!\n\t * @return The return value as returned from the ink function with `~ return\n\t * myValue`, or null if nothing is returned.\n\t * @throws Exception\n\t */\n\tpublic Object evaluateFunction(String functionName, Object[] arguments) throws Exception {\n\t\treturn evaluateFunction(functionName, null, arguments);\n\t}\n\n\tpublic Object evaluateFunction(String functionName) throws Exception {\n\t\treturn evaluateFunction(functionName, null, null);\n\t}\n\n\t/**\n\t * Checks if a function exists.\n\t *\n\t * @return True if the function exists, else false.\n\t * @param functionName The name of the function as declared in ink.\n\t */\n\tpublic boolean hasFunction(String functionName) {\n\t\ttry {\n\t\t\treturn knotContainerWithName(functionName) != null;\n\t\t} catch (Exception e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Evaluates a function defined in ink, and gathers the possibly multi-line text\n\t * as generated by the function.\n\t *\n\t * @param arguments The arguments that the ink function takes, if any. Note\n\t * that we don't (can't) do any validation on the number of\n\t * arguments right now, so make sure you get it right!\n\t * @param functionName The name of the function as declared in ink.\n\t * @param textOutput This text output is any text written as normal content\n\t * within the function, as opposed to the return value, as\n\t * returned with `~ return`.\n\t * @return The return value as returned from the ink function with `~ return\n\t * myValue`, or null if nothing is returned.\n\t * @throws Exception\n\t */\n\tpublic Object evaluateFunction(String functionName, StringBuilder textOutput, Object[] arguments) throws Exception {\n\t\tifAsyncWeCant(\"evaluate a function\");\n\n\t\tif (functionName == null) {\n\t\t\tthrow new Exception(\"Function is null\");\n\t\t} else if (functionName.trim().isEmpty()) {\n\t\t\tthrow new Exception(\"Function is empty or white space.\");\n\t\t}\n\n\t\t// Get the content that we need to run\n\t\tContainer funcContainer = knotContainerWithName(functionName);\n\t\tif (funcContainer == null)\n\t\t\tthrow new Exception(\"Function doesn't exist: '\" + functionName + \"'\");\n\n\t\t// Snapshot the output stream\n\t\tArrayList<RTObject> outputStreamBefore = new ArrayList<>(state.getOutputStream());\n\t\tstate.resetOutput();\n\n\t\t// State will temporarily replace the callstack in order to evaluate\n\t\tstate.startFunctionEvaluationFromGame(funcContainer, arguments);\n\n\t\t// Evaluate the function, and collect the string output\n\t\twhile (canContinue()) {\n\t\t\tString text = Continue();\n\n\t\t\tif (textOutput != null)\n\t\t\t\ttextOutput.append(text);\n\t\t}\n\n\t\t// Restore the output stream in case this was called\n\t\t// during main story evaluation.\n\t\tstate.resetOutput(outputStreamBefore);\n\n\t\t// Finish evaluation, and see whether anything was produced\n\t\tObject result = state.completeFunctionEvaluationFromGame();\n\t\treturn result;\n\t}\n\n\t// Maximum snapshot stack:\n\t// - stateSnapshotDuringSave -- not retained, but returned to game code\n\t// - _stateSnapshotAtLastNewline (has older patch)\n\t// - _state (current, being patched)\n\tvoid stateSnapshot() {\n\t\tstateSnapshotAtLastNewline = state;\n\t\tstate = state.copyAndStartPatching();\n\t}\n\n\tvoid restoreStateSnapshot() {\n\t\t// Patched state had temporarily hijacked our\n\t\t// VariablesState and set its own callstack on it,\n\t\t// so we need to restore that.\n\t\t// If we're in the middle of saving, we may also\n\t\t// need to give the VariablesState the old patch.\n\t\tstateSnapshotAtLastNewline.restoreAfterPatch();\n\n\t\tstate = stateSnapshotAtLastNewline;\n\t\tstateSnapshotAtLastNewline = null;\n\n\t\t// If save completed while the above snapshot was\n\t\t// active, we need to apply any changes made since\n\t\t// the save was started but before the snapshot was made.\n\t\tif (!asyncSaving) {\n\t\t\tstate.applyAnyPatch();\n\t\t}\n\t}\n\n\tvoid discardSnapshot() {\n\t\t// Normally we want to integrate the patch\n\t\t// into the main global/counts dictionaries.\n\t\t// However, if we're in the middle of async\n\t\t// saving, we simply stay in a \"patching\" state,\n\t\t// albeit with the newer cloned patch.\n\t\tif (!asyncSaving)\n\t\t\tstate.applyAnyPatch();\n\n\t\t// No longer need the snapshot.\n\t\tstateSnapshotAtLastNewline = null;\n\t}\n\n\t/**\n\t * Advanced usage! If you have a large story, and saving state to JSON takes too\n\t * long for your framerate, you can temporarily freeze a copy of the state for\n\t * saving on a separate thread. Internally, the engine maintains a \"diff patch\".\n\t * When you've finished saving your state, call BackgroundSaveComplete() and\n\t * that diff patch will be applied, allowing the story to continue in its usual\n\t * mode.\n\t *\n\t * @return The state for background thread save.\n\t * @throws Exception\n\t */\n\tpublic StoryState copyStateForBackgroundThreadSave() throws Exception {\n\t\tifAsyncWeCant(\"start saving on a background thread\");\n\t\tif (asyncSaving)\n\t\t\tthrow new Exception(\n\t\t\t\t\t\"Story is already in background saving mode, can't call CopyStateForBackgroundThreadSave again!\");\n\t\tStoryState stateToSave = state;\n\t\tstate = state.copyAndStartPatching();\n\t\tasyncSaving = true;\n\t\treturn stateToSave;\n\t}\n\n\t/**\n\t * See CopyStateForBackgroundThreadSave. This method releases the \"frozen\" save\n\t * state, applying its patch that it was using internally.\n\t */\n\tpublic void backgroundSaveComplete() {\n\t\t// CopyStateForBackgroundThreadSave must be called outside\n\t\t// of any async ink evaluation, since otherwise you'd be saving\n\t\t// during an intermediate state.\n\t\t// However, it's possible to *complete* the save in the middle of\n\t\t// a glue-lookahead when there's a state stored in _stateSnapshotAtLastNewline.\n\t\t// This state will have its own patch that is newer than the save patch.\n\t\t// We hold off on the final apply until the glue-lookahead is finished.\n\t\t// In that case, the apply is always done, it's just that it may\n\t\t// apply the looked-ahead changes OR it may simply apply the changes\n\t\t// made during the save process to the old _stateSnapshotAtLastNewline state.\n\t\tif (stateSnapshotAtLastNewline == null) {\n\t\t\tstate.applyAnyPatch();\n\t\t}\n\n\t\tasyncSaving = false;\n\t}\n}", "public interface ExternalFunction<R> {\n\tR call(Object... args) throws Exception;\n}", "public abstract static class ExternalFunction0<R> implements ExternalFunction<R> {\n\t@Override\n\tpublic final R call(Object... args) throws Exception {\n\t\tif (args.length != 0) {\n\t\t\tthrow new IllegalArgumentException(\"Expecting 0 arguments.\");\n\t\t}\n\t\treturn call();\n\t}\n\n\tprotected abstract R call() throws Exception;\n}", "public abstract static class ExternalFunction1<T, R> implements ExternalFunction<R> {\n\t@Override\n\tpublic final R call(Object... args) throws Exception {\n\t\tif (args.length != 1) {\n\t\t\tthrow new IllegalArgumentException(\"Expecting 1 argument.\");\n\t\t}\n\t\treturn call(coerceArg(args[0]));\n\t}\n\n\tprotected abstract R call(T t) throws Exception;\n\n\t@SuppressWarnings(\"unchecked\")\n\tprotected T coerceArg(Object arg) throws Exception {\n\t\treturn (T) arg;\n\t}\n}", "public abstract static class ExternalFunction2<T1, T2, R> implements ExternalFunction<R> {\n\t@Override\n\tpublic final R call(Object... args) throws Exception {\n\t\tif (args.length != 2) {\n\t\t\tthrow new IllegalArgumentException(\"Expecting 2 arguments.\");\n\t\t}\n\t\treturn call(coerceArg0(args[0]), coerceArg1(args[1]));\n\t}\n\n\tprotected abstract R call(T1 t1, T2 t2) throws Exception;\n\n\t@SuppressWarnings(\"unchecked\")\n\tprotected T1 coerceArg0(Object arg) throws Exception {\n\t\treturn (T1) arg;\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tprotected T2 coerceArg1(Object arg) throws Exception {\n\t\treturn (T2) arg;\n\t}\n}", "public abstract static class ExternalFunction3<T1, T2, T3, R> implements ExternalFunction<R> {\n\t@Override\n\tpublic final R call(Object... args) throws Exception {\n\t\tif (args.length != 3) {\n\t\t\tthrow new IllegalArgumentException(\"Expecting 3 arguments.\");\n\t\t}\n\t\treturn call(coerceArg0(args[0]), coerceArg1(args[1]), coerceArg2(args[2]));\n\t}\n\n\tprotected abstract R call(T1 t1, T2 t2, T3 t3) throws Exception;\n\n\t@SuppressWarnings(\"unchecked\")\n\tprotected T1 coerceArg0(Object arg) throws Exception {\n\t\treturn (T1) arg;\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tprotected T2 coerceArg1(Object arg) throws Exception {\n\t\treturn (T2) arg;\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tprotected T3 coerceArg2(Object arg) throws Exception {\n\t\treturn (T3) arg;\n\t}\n}", "public interface VariableObserver {\n\tvoid call(String variableName, Object newValue);\n}", "@SuppressWarnings(\"serial\")\r\npublic class StoryException extends Exception {\r\n\tpublic boolean useEndLineNumber;\r\n\r\n\t/**\r\n\t * Constructs a default instance of a StoryException without a message.\r\n\t */\r\n\tpublic StoryException() throws Exception {\r\n\t}\r\n\r\n\t/**\r\n\t * Constructs an instance of a StoryException with a message.\r\n\t * \r\n\t * @param message\r\n\t * The error message.\r\n\t */\r\n\tpublic StoryException(String message) throws Exception {\r\n\t\tsuper(message);\r\n\t}\r\n\r\n}\r" ]
import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.junit.Test; import com.bladecoder.ink.runtime.Profiler; import com.bladecoder.ink.runtime.Story; import com.bladecoder.ink.runtime.Story.ExternalFunction; import com.bladecoder.ink.runtime.Story.ExternalFunction0; import com.bladecoder.ink.runtime.Story.ExternalFunction1; import com.bladecoder.ink.runtime.Story.ExternalFunction2; import com.bladecoder.ink.runtime.Story.ExternalFunction3; import com.bladecoder.ink.runtime.Story.VariableObserver; import com.bladecoder.ink.runtime.StoryException;
package com.bladecoder.ink.runtime.test; public class RuntimeSpecTest { /** * Test external function call. */ @Test public void externalFunction() throws Exception { List<String> text = new ArrayList<>(); String json = TestUtils.getJsonString("inkfiles/runtime/external-function-2-arg.ink.json"); final Story story = new Story(json); story.bindExternalFunction("externalFunction", new ExternalFunction<Integer>() { @Override public Integer call(Object[] args) throws Exception { int x = story.tryCoerce(args[0], Integer.class); int y = story.tryCoerce(args[1], Integer.class); return x - y; } }); TestUtils.nextAll(story, text); Assert.assertEquals(1, text.size()); Assert.assertEquals("The value is -1.", text.get(0)); } /** * Test external function zero arguments call. */ @Test public void externalFunctionZeroArguments() throws Exception { List<String> text = new ArrayList<>(); String json = TestUtils.getJsonString("inkfiles/runtime/external-function-0-arg.ink.json"); final Story story = new Story(json); story.bindExternalFunction("externalFunction", new ExternalFunction0<String>() { @Override protected String call() { return "Hello world"; } }); TestUtils.nextAll(story, text); Assert.assertEquals(1, text.size()); Assert.assertEquals("The value is Hello world.", text.get(0)); } /** * Test external function one argument call. */ @Test public void externalFunctionOneArgument() throws Exception { List<String> text = new ArrayList<>(); String json = TestUtils.getJsonString("inkfiles/runtime/external-function-1-arg.ink.json"); final Story story = new Story(json); story.bindExternalFunction("externalFunction", new ExternalFunction1<Integer, Boolean>() { @Override protected Boolean call(Integer arg) { return arg != 1; } }); TestUtils.nextAll(story, text); Assert.assertEquals(1, text.size()); Assert.assertEquals("The value is false.", text.get(0)); } /** * Test external function one argument call. Overrides coerce method. */ @Test public void externalFunctionOneArgumentCoerceOverride() throws Exception { List<String> text = new ArrayList<>(); String json = TestUtils.getJsonString("inkfiles/runtime/external-function-1-arg.ink.json"); final Story story = new Story(json); story.bindExternalFunction("externalFunction", new ExternalFunction1<Boolean, Boolean>() { @Override protected Boolean coerceArg(Object arg) throws Exception { return story.tryCoerce(arg, Boolean.class); } @Override protected Boolean call(Boolean arg) { return !arg; } }); TestUtils.nextAll(story, text); Assert.assertEquals(1, text.size()); Assert.assertEquals("The value is false.", text.get(0)); } /** * Test external function two arguments call. */ @Test public void externalFunctionTwoArguments() throws Exception { List<String> text = new ArrayList<>(); String json = TestUtils.getJsonString("inkfiles/runtime/external-function-2-arg.ink.json"); final Story story = new Story(json);
story.bindExternalFunction("externalFunction", new ExternalFunction2<Integer, Float, Integer>() {
5
neoremind/navi-pbrpc
src/main/java/com/baidu/beidou/navi/pbrpc/client/BlockingIOPbrpcClient.java
[ "public class CallFuture<T> implements Future<T>, Callback<T> {\r\n\r\n /**\r\n * 内部回调用的栅栏\r\n */\r\n private final CountDownLatch latch = new CountDownLatch(1);\r\n\r\n /**\r\n * 调用返回结果\r\n */\r\n private T result = null;\r\n\r\n /**\r\n * 调用错误信息\r\n */\r\n private Throwable error = null;\r\n\r\n /**\r\n * Creates a new instance of CallFuture.\r\n */\r\n private CallFuture() {\r\n\r\n }\r\n\r\n /**\r\n * 静态创建方法\r\n * \r\n * @return\r\n */\r\n public static <E> CallFuture<E> newInstance() {\r\n return new CallFuture<E>();\r\n }\r\n\r\n /**\r\n * Sets the RPC response, and unblocks all threads waiting on {@link #get()} or {@link #get(long, TimeUnit)}.\r\n * \r\n * @param result\r\n * the RPC result to set.\r\n */\r\n public void handleResult(T result) {\r\n this.result = result;\r\n latch.countDown();\r\n }\r\n\r\n /**\r\n * Sets an error thrown during RPC execution, and unblocks all threads waiting on {@link #get()} or\r\n * {@link #get(long, TimeUnit)}.\r\n * \r\n * @param error\r\n * the RPC error to set.\r\n */\r\n public void handleError(Throwable error) {\r\n this.error = error;\r\n latch.countDown();\r\n }\r\n\r\n /**\r\n * Gets the value of the RPC result without blocking. Using {@link #get()} or {@link #get(long, TimeUnit)} is\r\n * usually preferred because these methods block until the result is available or an error occurs.\r\n * \r\n * @return the value of the response, or null if no result was returned or the RPC has not yet completed.\r\n */\r\n public T getResult() {\r\n return result;\r\n }\r\n\r\n /**\r\n * Gets the error that was thrown during RPC execution. Does not block. Either {@link #get()} or\r\n * {@link #get(long, TimeUnit)} should be called first because these methods block until the RPC has completed.\r\n * \r\n * @return the RPC error that was thrown, or null if no error has occurred or if the RPC has not yet completed.\r\n */\r\n public Throwable getError() {\r\n return error;\r\n }\r\n\r\n /**\r\n * @see java.util.concurrent.Future#get()\r\n */\r\n public T get() throws InterruptedException {\r\n latch.await();\r\n if (error != null) {\r\n throw new PbrpcException(\"Error occurrs due to \" + error.getMessage(), error);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * @see java.util.concurrent.Future#get(long, java.util.concurrent.TimeUnit)\r\n */\r\n public T get(long timeout, TimeUnit unit) {\r\n try {\r\n if (latch.await(timeout, unit)) {\r\n if (error != null) {\r\n throw new PbrpcException(\"Error occurrs due to \" + error.getMessage(), error);\r\n }\r\n return result;\r\n } else {\r\n throw new TimeoutException(\"CallFuture async get time out\");\r\n }\r\n } catch (InterruptedException e) {\r\n Thread.currentThread().interrupt();\r\n throw new RuntimeException(\"CallFuture is interuptted\", e);\r\n }\r\n }\r\n\r\n /**\r\n * Waits for the CallFuture to complete without returning the result.\r\n * \r\n * @throws InterruptedException\r\n * if interrupted.\r\n */\r\n public void await() throws InterruptedException {\r\n latch.await();\r\n }\r\n\r\n /**\r\n * Waits for the CallFuture to complete without returning the result.\r\n * \r\n * @param timeout\r\n * the maximum time to wait.\r\n * @param unit\r\n * the time unit of the timeout argument.\r\n * @throws InterruptedException\r\n * if interrupted.\r\n * @throws TimeoutException\r\n * if the wait timed out.\r\n */\r\n public void await(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException {\r\n if (!latch.await(timeout, unit)) {\r\n throw new TimeoutException();\r\n }\r\n }\r\n\r\n /**\r\n * @see java.util.concurrent.Future#cancel(boolean)\r\n */\r\n public boolean cancel(boolean mayInterruptIfRunning) {\r\n return false;\r\n }\r\n\r\n /**\r\n * @see java.util.concurrent.Future#isCancelled()\r\n */\r\n public boolean isCancelled() {\r\n return false;\r\n }\r\n\r\n /**\r\n * @see java.util.concurrent.Future#isDone()\r\n */\r\n public boolean isDone() {\r\n return latch.getCount() <= 0;\r\n }\r\n\r\n}", "public interface Codec {\n\n /**\n * 反序列化\n * \n * @param clazz\n * 反序列化后的类定义\n * @param bytes\n * 字节码\n * @return 反序列化后的对象\n * @throws CodecException\n */\n Object decode(Class<?> clazz, byte[] bytes) throws CodecException;\n\n /**\n * 序列化\n * \n * @param clazz\n * 待序列化的类定义\n * @param object\n * 待序列化的对象\n * @return 字节码\n * @throws CodecException\n */\n byte[] encode(Class<?> clazz, Object object) throws CodecException;\n\n}", "public class ProtobufCodec implements Codec {\n\n /**\n * Protobuf生成原生Java代码中的方法解码方法名称\n */\n private static final String METHOD_NAME_PARSEFROM = \"parseFrom\";\n\n /**\n * Protobuf生成原生Java代码中的方法编码方法名称\n */\n private static final String METHOD_NAME_TOBYTE = \"toByteArray\";\n\n /**\n * 方法缓存,用于Protobuf生成原生Java代码中的某些编解码方法。 缓存的方法包括:\n * <p/>\n * <ul>\n * <li><code>parseFrom(byte[] bytes)</code></li>\n * <li><code>toByteArray()</code></li>\n * </ul>\n * \n * @see com.baidu.beidou.navi.pbrpc.util.ConcurrentCache\n * @see com.baidu.beidou.navi.pbrpc.util.Computable\n */\n private static final Computable<String, Method> PROTOBUF_METHOD_CACHE = new ConcurrentCache<String, Method>();\n\n /**\n * @see com.baidu.beidou.navi.pbrpc.codec.Codec#decode(java.lang.Class, byte[])\n */\n @Override\n public Object decode(final Class<?> clazz, byte[] data) throws CodecException {\n try {\n if (data == null || data.length == 0) {\n return null;\n }\n Method m = PROTOBUF_METHOD_CACHE.get(clazz.getName() + METHOD_NAME_PARSEFROM,\n new Callable<Method>() {\n @Override\n public Method call() throws Exception {\n return clazz.getMethod(METHOD_NAME_PARSEFROM, byte[].class);\n }\n });\n GeneratedMessage msg = (GeneratedMessage) m.invoke(clazz, data);\n return msg;\n } catch (Exception e) {\n throw new CodecException(\"Decode failed due to \" + e.getMessage(), e);\n }\n }\n\n /**\n * @see com.baidu.beidou.navi.pbrpc.codec.Codec#encode(java.lang.Class, java.lang.Object)\n */\n @Override\n public byte[] encode(final Class<?> clazz, Object object) throws CodecException {\n try {\n Method m = PROTOBUF_METHOD_CACHE.get(clazz.getName() + METHOD_NAME_TOBYTE,\n new Callable<Method>() {\n @Override\n public Method call() throws Exception {\n return clazz.getMethod(METHOD_NAME_TOBYTE);\n }\n });\n byte[] data = (byte[]) m.invoke(object);\n return data;\n } catch (Exception e) {\n throw new CodecException(\"Encode failed due to \" + e.getMessage(), e);\n }\n }\n\n}", "public class OperationNotSupportException extends RuntimeException {\n\n /**\n * serialVersionUID\n */\n private static final long serialVersionUID = 5196421433506179782L;\n\n /**\n * Creates a new instance of OperationNotSupportException.\n */\n public OperationNotSupportException() {\n super();\n }\n\n /**\n * Creates a new instance of OperationNotSupportException.\n * \n * @param arg0\n * @param arg1\n */\n public OperationNotSupportException(String arg0, Throwable arg1) {\n super(arg0, arg1);\n }\n\n /**\n * Creates a new instance of OperationNotSupportException.\n * \n * @param arg0\n */\n public OperationNotSupportException(String arg0) {\n super(arg0);\n }\n\n /**\n * Creates a new instance of OperationNotSupportException.\n * \n * @param arg0\n */\n public OperationNotSupportException(Throwable arg0) {\n super(arg0);\n }\n\n}", "public class PbrpcConnectionException extends RuntimeException {\n\n /**\n * serialVersionUID\n */\n private static final long serialVersionUID = 5196421433506179782L;\n\n /**\n * Creates a new instance of PbrpcConnectionException.\n */\n public PbrpcConnectionException() {\n super();\n }\n\n /**\n * Creates a new instance of PbrpcConnectionException.\n * \n * @param arg0\n * @param arg1\n */\n public PbrpcConnectionException(String arg0, Throwable arg1) {\n super(arg0, arg1);\n }\n\n /**\n * Creates a new instance of PbrpcConnectionException.\n * \n * @param arg0\n */\n public PbrpcConnectionException(String arg0) {\n super(arg0);\n }\n\n /**\n * Creates a new instance of PbrpcConnectionException.\n * \n * @param arg0\n */\n public PbrpcConnectionException(Throwable arg0) {\n super(arg0);\n }\n\n}", "public class PbrpcException extends RuntimeException {\n\n /**\n * serialVersionUID\n */\n private static final long serialVersionUID = 5196421433506179782L;\n\n /**\n * Creates a new instance of PbrpcException.\n */\n public PbrpcException() {\n super();\n }\n\n /**\n * Creates a new instance of PbrpcException.\n * \n * @param arg0\n * @param arg1\n */\n public PbrpcException(String arg0, Throwable arg1) {\n super(arg0, arg1);\n }\n\n /**\n * Creates a new instance of PbrpcException.\n * \n * @param arg0\n */\n public PbrpcException(String arg0) {\n super(arg0);\n }\n\n /**\n * Creates a new instance of PbrpcException.\n * \n * @param arg0\n */\n public PbrpcException(Throwable arg0) {\n super(arg0);\n }\n\n}", "public interface Header {\n\n /**\n * 头固定字节长度\n * \n * @return\n */\n int getFixedHeaderLen();\n\n /**\n * 消息body体长度\n * \n * @param bodyLen\n */\n void setBodyLen(long bodyLen);\n\n /**\n * 获取消息body体长度\n * \n * @return\n */\n long getBodyLen();\n\n /**\n * 从字节码构造头\n * \n * @param input\n */\n void wrap(byte[] input);\n\n /**\n * 头序列化为字节码\n * \n * @return\n * @throws RuntimeException\n */\n byte[] toBytes() throws RuntimeException;\n\n}", "public class PbrpcMsg {\n\n /**\n * 服务的标识id,一般客户端需要制定该id,服务端可以利用这个id路由到某个方法上调用。<br/>\n * 实际就是{@link NsHead}头中<tt>methodId</tt>,用于在服务端和客户端传递\n */\n private int serviceId;\n\n /**\n * 服务上下文logId,用于tracing使用。 <br/>\n * 实际就是{@link NsHead}头中<tt>logId</tt>,用于在服务端和客户端传递\n */\n private long logId;\n\n /**\n * 调用提供者,类似于appid。<br/>\n * 实际就是{@link NsHead}头中<tt>provider</tt>,用于在服务端和客户端传递\n */\n private String provider;\n\n /**\n * 一些不关业务逻辑处理的errorCode,由框架负责处理标示,发送请求时候请无设置该值\n */\n private ErrorCode errorCode;\n\n /**\n * 传输的经过protobuf序列化的字节码\n */\n private byte[] data;\n\n /**\n * @see java.lang.Object#toString()\n */\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"PbrpcMsg[logId=\");\n sb.append(logId);\n sb.append(\", serviceId=\");\n sb.append(serviceId);\n sb.append(\", provider=\");\n sb.append(provider);\n sb.append(\", dataLength=\");\n sb.append((data == null) ? 0 : data.length);\n if (errorCode != null) {\n sb.append(\", errorCode=\");\n sb.append(errorCode);\n }\n sb.append(\"]\");\n return sb.toString();\n }\n\n /**\n * 根据NsHead构造\n * \n * @param nsHead\n * @return\n */\n public static PbrpcMsg of(NsHead nsHead) {\n PbrpcMsg ret = new PbrpcMsg();\n ret.setServiceId((int) nsHead.getMethodId());\n ret.setLogId(nsHead.getLogId());\n ret.setErrorCode(ErrorCode.get(nsHead.getFlags()));\n ret.setProvider(nsHead.getProvider());\n return ret;\n }\n\n /**\n * 简单信息的拷贝复制,不拷贝字节码\n * \n * @param msg\n * @return\n */\n public static PbrpcMsg copyLiteOf(PbrpcMsg msg) {\n PbrpcMsg ret = new PbrpcMsg();\n ret.setLogId(msg.getLogId());\n ret.setProvider(msg.getProvider());\n ret.setServiceId(msg.getServiceId());\n ret.setErrorCode(msg.getErrorCode());\n return ret;\n }\n\n public ErrorCode getErrorCode() {\n return errorCode;\n }\n\n public PbrpcMsg setErrorCode(ErrorCode errorCode) {\n this.errorCode = errorCode;\n return this;\n }\n\n public int getServiceId() {\n return serviceId;\n }\n\n public PbrpcMsg setServiceId(int serviceId) {\n this.serviceId = serviceId;\n return this;\n }\n\n public byte[] getData() {\n return data;\n }\n\n public PbrpcMsg setData(byte[] data) {\n this.data = data;\n return this;\n }\n\n public long getLogId() {\n return logId;\n }\n\n public PbrpcMsg setLogId(long logId) {\n this.logId = logId;\n return this;\n }\n\n public String getProvider() {\n return provider;\n }\n\n public PbrpcMsg setProvider(String provider) {\n this.provider = provider;\n return this;\n }\n\n}" ]
import io.netty.channel.ChannelFuture; import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.baidu.beidou.navi.pbrpc.client.callback.CallFuture; import com.baidu.beidou.navi.pbrpc.codec.Codec; import com.baidu.beidou.navi.pbrpc.codec.impl.ProtobufCodec; import com.baidu.beidou.navi.pbrpc.exception.client.OperationNotSupportException; import com.baidu.beidou.navi.pbrpc.exception.client.PbrpcConnectionException; import com.baidu.beidou.navi.pbrpc.exception.client.PbrpcException; import com.baidu.beidou.navi.pbrpc.protocol.Header; import com.baidu.beidou.navi.pbrpc.transport.PbrpcMsg; import com.google.protobuf.GeneratedMessage;
package com.baidu.beidou.navi.pbrpc.client; /** * ClassName: BlockingIOPbrpcClient <br/> * Function: 简单的远程访问客户端,使用短连接Blocking IO方式调用服务端,不使用nio * * @author Zhang Xu */ public class BlockingIOPbrpcClient implements PbrpcClient { private static final Logger LOG = LoggerFactory.getLogger(BlockingIOPbrpcClient.class); /** * 远程服务ip地址 */ private String ip; /** * 远程服务端口 */ private int port; /** * 客户端连接超时,单位毫秒 */ private int connTimeout; /** * 客户端调用超时,单位毫秒 */ private int readTimeout; /** * 是否为短连接调用 */ private boolean isShortAliveConn = true; /** * 长连接调用会使用的 */ private Socket socket; /** * 客户端配置 */ private PbrpcClientConfiguration pbrpcClientConfiguration = new PbrpcClientConfiguration(); /** * 可配置,默认使用protobuf来做body的序列化 */ private Codec codec = new ProtobufCodec(); /** * header+body通讯协议方式的头解析构造器 */ private HeaderResolver headerResolver = new NsHeaderResolver(); public BlockingIOPbrpcClient() { } /** * Creates a new instance of BlockingIOPbrpcClient. * * @param pbrpcClientConfiguration * @param isShortAliveConnection * @param ip * @param port * @param connTimeout * @param readTimeout */ BlockingIOPbrpcClient(PbrpcClientConfiguration pbrpcClientConfiguration, boolean isShortAliveConnection, String ip, int port, int connTimeout, int readTimeout) { if (pbrpcClientConfiguration != null) { this.pbrpcClientConfiguration = pbrpcClientConfiguration; } this.isShortAliveConn = isShortAliveConnection; this.ip = ip; this.port = port; this.connTimeout = connTimeout; this.readTimeout = readTimeout; } /** * Creates a new instance of BlockingIOPbrpcClient. * * @param ip * @param port * @param connTimeout * @param readTimeout */ public BlockingIOPbrpcClient(String ip, int port, int connTimeout, int readTimeout) { this(null, true, ip, port, connTimeout, readTimeout); } /** * @see com.baidu.beidou.navi.pbrpc.client.PbrpcClient#connect() */ public ChannelFuture connect() {
throw new OperationNotSupportException();
3
buni-rock/Pixie
04_Software/03_Development/02_SourceCode/java/src/gui/editobject/BoxEdit.java
[ "public class Constants {\n\n /**\n * Number of objects which can be segmented in the application\n */\n public static final int NUMBER_OF_OBJECTS = 2;\n\n /**\n * The path to the user preferences containing the configuration specific to\n * the user.\n */\n public static final String USER_PREF_FILE_PATH = \".\" + File.separatorChar + \"cfg\" + File.separatorChar + \"userPreferences.txt\";\n\n /**\n * Defines the when max size of the brush for which the mouse is an arrow.\n * If the brush size is greater than the specified value, an icon is\n * generated for the mouse.\n */\n public static final int MIN_MOUSE_BRUSH_ICON = 2;\n\n /**\n * The width of the result panel where the segmented image is shown.\n */\n public static final int RESULT_PANEL_WIDTH = 400;\n /**\n * The height of the result panel where the segmented image is shown.\n */\n public static final int RESULT_PANEL_HEIGHT = 300;\n\n /**\n * The path to where the User manual of Pixie is stored.\n */\n public static final String APPLICATION_MANUAL = \".\" + File.separatorChar + \"doc\" + File.separatorChar + \"Pixie_Manual.pdf\";\n\n /**\n * The release number of the software.\n */\n public static final String RELEASE_NUMBER = \"0.5\";\n /**\n * The number of the current sprint.\n */\n public static final String SPRINT_NUMBER = \"3\";\n /**\n * The software version is made of the release number together with the\n * sprint number. This will help in tracking the implemented issue for each\n * release.\n */\n public static final String SOFTWARE_VERSION = RELEASE_NUMBER + \".\" + SPRINT_NUMBER;\n\n /**\n * The version of JCuda used in the current software.\n */\n public static final String JCUDA_VERSION = \"0.8.0\";\n /**\n * The version of JCuda used in the current software.\n */\n public static final String JOCL_VERSION = \"2.0.0\";\n /**\n * The version of the jar used for the drawing tablet communication.\n */\n public static final String JPEN_VERSION = \"2\";\n /**\n * The version of the jar used for the drawing tablet communication.\n */\n public static final String HAMCREST_VERSION = \"1.3\";\n /**\n * The version of the JUnit for which the tests are running.\n */\n public static final String JUNIT_VERSION = \"4.12\";\n /**\n * The version of openCV used in the project.\n */\n public static final String OPENCV_VERSION = \"3.2\";\n\n /**\n * Play video file in forward mode\n */\n public static final int PLAY_MODE_FORWARD = 0;\n\n /**\n * Play video file in backward mode\n */\n public static final int PLAY_MODE_BACKWARD = 1;\n\n /**\n * Marks an action regarding the next frame.\n */\n public static final int NEXT_FRAME = 0;\n /**\n * Marks an action regarding the previous frame.\n */\n public static final int PREV_FRAME = 1;\n /**\n * Marks an action regarding the jump to a certain frame.\n */\n public static final int JUMP_TO_FRAME = 2;\n\n /**\n * Shows that the matting algorithm shall be run on the original image.\n */\n public static final int RUN_MATT_ORIG_IMG = 0;\n /**\n * Shows that the matting algorithm shall be run on the highlighted image.\n */\n public static final int RUN_MATT_HIGHLIGHT_IMG = 1;\n\n /**\n * The percentage of border which has to be added to the box, in preview\n * mode.\n */\n public static final float BORDER_PERCENTAGE = 0.2f;\n /**\n * The min border which shall be added to the box, in preview mode.\n */\n public static final int MIN_BORDER = 10;\n\n /**\n * Allow the max percentage of the screen to be used for resizing the\n * BBoxes/Crops\n */\n public static final double MAX_SCREEN_PERCENT_RESIZE = 0.85;\n\n /**\n * How much percentage shall be left for insets and other screen\n * decorations, on the horizontal direction.\n */\n public static final float TOLERANCE_WIDTH = 0.06f;\n\n /**\n * How much percentage shall be left for insets and other screen\n * decorations, on the vertical direction.\n */\n public static final float TOLERANCE_HEIGHT = 0.12f;\n\n /**\n * The text used to mark an invalid attribute.\n */\n public static final String INVALID_ATTRIBUTE_TEXT = \"undefined\";\n \n /**\n * The default text in the root of the object attributes tree.\n */\n public static final String OBJECT_ATTRIBUTES_TEXT = \"Object Attributes\";\n \n /**\n * The default text in the root of the frame attributes tree.\n */\n public static final String FRAME_ATTRIBUTES_TEXT = \"Frame Attributes\";\n\n /**\n * The name of the original image.\n */\n public static final String ORIGINAL_IMG = \"Original Image\";\n /**\n * The name of the segmented image.\n */\n public static final String SEGMENTED_IMG = \"Working Panel\";\n /**\n * The name of the segmented image.\n */\n public static final String SEGMENTED_IMG_RESIZED = \"Working Panel Resized\";\n /**\n * The name of the result image.\n */\n public static final String SEMANTIC_SEGMENTATION_IMG = \"Semantic Segmentation\";\n /**\n * The name of the joined images.\n */\n public static final String JOINED_IMGS = \"Joined Images\";\n\n /**\n * The name of the default folder where to export files.\n */\n public static final String EXPORT_IMGS_PATH = new File(\"\").getAbsolutePath() + File.separatorChar + \"Export\";\n\n /**\n * The possible options of getting a grayscale value out of an rgb one.\n */\n public enum GrayscaleOption {\n /**\n * Standard luminance grayscale option.\n */\n STANDARD_LUMINANCE, // L = 0.2126*R + 0.7152*G + 0.0722*B\n /**\n * Gimp luminance grayscale option.\n */\n GIMP_LUMINANCE, // L = 0.222*R + 0.717*G + 0.061*B\n /**\n * Fast grayscale grayscale option.\n */\n FAST_GRAYSCALE // L = ((2*R + 5*G + 1*B) / 8) = ((r<<1 + g<<2 + g + b) >> 3)\n }\n\n /**\n * The possible normalisation technics of a vector.\n */\n public enum Normalisation {\n /**\n * L 2 norm block normalisation.\n */\n L2_NORM_BLOCK, // |x| = sqrt(x1^2 + x2^2 + x3^2 + ... + xn^2)\n /**\n * L 2 hys block normalisation.\n */\n L2_HYS_BLOCK, // l2-norm followd by clipping (limiting the maximum values to 0.2) and renormalising\n /**\n * Tile level normalisation.\n */\n TILE_LEVEL, // normalisation at tile level (divide by the max of the tile)\n /**\n * Block level normalisation.\n */\n BLOCK_LEVEL, // normalisation at block level (divide by the max of the block)\n /**\n * Image level normalisation.\n */\n IMAGE_LEVEL, // normalisation at image level (divide by the max of the image)\n /**\n * Do nothing normalisation.\n */\n DO_NOTHING\n }\n\n /**\n * Defines the possible modes of the application.\n */\n public enum AppConfigMode {\n /**\n * Premium edition app config mode.\n */\n PREMIUM_EDITION, // the application opens videos coming from the server and sends the data back to be saved in the database\n /**\n * The Community edition.\n */\n COMMUNITY_EDITION // the application opens pictures coming from a local source and saves the data locally on the machine (in a file)\n }\n\n /**\n * Defines the possible errors or interruptions which could happen during the save of ground\n * truth.\n */\n public enum GTSaveInterruptCodes {\n /**\n * No error gt save interrupt codes.\n */\n NO_ERROR,\n /**\n * Frame attrib not set gt save interrupt codes.\n */\n FRAME_ATTRIB_NOT_SET,\n /**\n * Data not found gt save interrupt codes.\n */\n DATA_NOT_FOUND\n }\n\n /**\n * The constant IMG_EXTENSION_LIST.\n */\n public static final List<String> IMG_EXTENSION_LIST = Arrays.asList(\"bmp\", \"jpg\", \"jpeg\", \"png\");\n /**\n * The constant VIDEO_EXTENSION_LIST.\n */\n public static final List<String> VIDEO_EXTENSION_LIST = Arrays.asList(\"mp4\", \"nv12\", \"bgr\", \"avi\");\n /**\n * The constant EXTENSION_LIST.\n */\n public static final List<String> EXTENSION_LIST = Stream.concat(IMG_EXTENSION_LIST.stream(), VIDEO_EXTENSION_LIST.stream()).collect(Collectors.toList());\n\n /**\n * The path to the file containing the frame attributes, for offline mode.\n */\n public static final String FRAME_ATTRIBUTES_PATH = \"cfg\" + File.separator + \"frameAttributes.txt\";\n\n /**\n * The path to the file containing the object attributes, for offline mode.\n */\n public static final String OBJECT_ATTRIBUTES_PATH = \"cfg\" + File.separator + \"objectAttributes.txt\";\n\n /**\n * The list of colors used in the application for the objects and which are\n * reserved for object segmentation. The user cannot select and use one of\n * them.\n */\n public static final List<Color> COLORS_LIST = Arrays.asList(Color.black, Color.green, Color.blue, Color.yellow, Color.magenta, Color.cyan,\n (new Color(153, 255, 153)), (new Color(153, 51, 255)), (new Color(51, 204, 255)), (new Color(255, 153, 102)), (new Color(102, 102, 255)),\n (new Color(255, 99, 71)), (new Color(165, 42, 42)), (new Color(154, 205, 50)), (new Color(0, 206, 209)), (new Color(75, 0, 130)),\n (new Color(175, 159, 106)), (new Color(119, 159, 106)), (new Color(0, 159, 106)), (new Color(0, 80, 106)), (new Color(0, 200, 106)),\n (new Color(124, 128, 39)), (new Color(124, 128, 236)), (new Color(185, 112, 56)), (new Color(185, 75, 125)), (new Color(128, 0, 0)),\n (new Color(128, 128, 0)), (new Color(0, 128, 0)), (new Color(128, 0, 128)), (new Color(0, 128, 128)), (new Color(0, 0, 128)),\n (new Color(238, 130, 238)), (new Color(245, 222, 179)), (new Color(210, 105, 30)), (new Color(105, 105, 105)), (new Color(30, 144, 255))\n );\n\n /**\n * Utility classes, which are collections of static members, are not meant\n * to be instantiated. Even abstract utility classes, which can be extended,\n * should not have public constructors. Java adds an implicit public\n * constructor to every class which does not define at least one explicitly.\n * Hence, at least one non-public constructor should be defined.\n */\n private Constants() {\n throw new IllegalStateException(\"Utility class, do not instantiate!\");\n }\n}", "public class ConstantsLabeling {\n\n //----------------------Label type definition-----------------------------//\n /**\n * Label type definition: 2D bounding box.\n */\n public static final String LABEL_2D_BOUNDING_BOX = \"2D_bounding_box\";\n\n /**\n * Label type definition: 3D bounding box.\n */\n public static final String LABEL_3D_BOUNDING_BOX = \"3D_bounding_box\";\n\n /**\n * Label type definition: pixel segmentation.\n */\n public static final String LABEL_SCRIBBLE = \"pixel_segmentation_scribble\";\n\n /**\n * Label type definition: polygon segmentation.\n */\n public static final String LABEL_POLYGON = \"polygon_segmentation\";\n\n /**\n * Label type definition: free drawing segmentation.\n */\n public static final String LABEL_FREE_DRAW = \"free_drawing_segmentation\";\n\n //----------------------Label source definition---------------------------//\n /**\n * Label source definition: manual.\n */\n public static final String LABEL_SOURCE_MANUAL = \"manual\";\n\n //----------------------Actions while in scribble mode--------------------//\n /**\n * Types of possible actions while in scribble mode: erase scribbles.\n */\n public static final int ACTION_TYPE_ERASE = -1;\n\n /**\n * Types of possible actions while in scribble mode: draw background\n * scribble.\n */\n public static final int ACTION_TYPE_BACKGROUND = 0;\n\n /**\n * Types of possible actions while in scribble mode: draw object scribble.\n */\n public static final int ACTION_TYPE_OBJECT = 1;\n\n /**\n * Utility classes, which are collections of static members, are not meant\n * to be instantiated. Even abstract utility classes, which can be extended,\n * should not have public constructors. Java adds an implicit public\n * constructor to every class which does not define at least one explicitly.\n * Hence, at least one non-public constructor should be defined.\n */\n private ConstantsLabeling() {\n throw new IllegalStateException(\"Utility class, do not instantiate!\");\n }\n}", "public class UserPreferences implements Serializable {\n\n /**\n * Serial class version in form of MAJOR_MINOR_BUGFIX_DAY_MONTH_YEAR\n */\n private static final long serialVersionUID = 0x00_06_01_11_09_2017L;\n\n /**\n * logger instance\n */\n private final transient org.slf4j.Logger log = LoggerFactory.getLogger(UserPreferences.class);\n\n /**\n * The path to the last used directory.\n */\n private String lastDirectory;\n\n /**\n * Indicator for knowing if the background should be merged or not in the\n * image.\n */\n private boolean mergeBKG;\n\n /**\n * Indicator for knowing if the scribbles should be shown on the work panel.\n */\n private boolean showScribbles;\n\n /**\n * Indicator for knowing if the crops should be shown on the work panel.\n */\n private boolean showCrops;\n\n /**\n * Indicator for knowing if only the crops and scribbles of the current\n * object have to be displayed on the working panel.\n */\n private boolean showJustCurrentObj;\n\n /**\n * Indicator for knowing if the objects should be displayed to the user,\n * after pressing next and going to the next file, for review.\n */\n private boolean popUpObjects;\n\n /**\n * Indicator for knowing if play mode of the video shall be forward or\n * backward.\n */\n private boolean playBackward;\n\n /**\n * Indicator for knowing if file map shall be saved when the data is saved\n * in the database.\n */\n private boolean saveFrameObjMap;\n\n /**\n * Indicator for knowing if the user wants to have the object highlighted.\n * True = draws a transparent layer over the object to highlight it.\n */\n private boolean showObjHighlight;\n\n /**\n * The value of the alpha to be used for the highlight of the object.\n */\n private int objAlphaVal;\n\n /**\n * Indicator for knowing if the image shall be flipped vertically or not.\n */\n private boolean flipVertically;\n\n /**\n * Indicator for knowing if the image shall be mirrored or not.\n */\n private boolean mirrorImage;\n\n /**\n * The preferred value of the DPI for the display of the application.\n */\n private int preferredDPI;\n\n /**\n * Indicator for knowing if the application is running for the first time.\n */\n private boolean firstRun;\n\n /**\n * The path where to export images using the Export option.\n */\n private String imgExportPath;\n\n /**\n * The extension used for the export of images.\n */\n private String imgExportExtension;\n\n /**\n * Export every frame the selected type of image.\n */\n private boolean imgAutoExportEveryFrame;\n\n /**\n * The type of image which is to be saved every frame.\n */\n private String imgTypeForExport;\n\n /**\n * The type of images to be joined for the export of every frame.\n */\n private String imgTypeJoinedExport;\n\n /**\n * Indicator for knowing if the frame annotations should be checked to\n * insure they are valid.\n */\n private boolean checkFrameAnnotations;\n\n /**\n * Indicator for knowing if the object attributes should be checked to\n * insure they are valid.\n */\n private boolean checkObjectAttributes;\n\n /**\n * Instantiate a new user preferences class, which is meant to read the user\n * configuration file and set all its preferences in the application when it\n * starts.\n */\n public UserPreferences() {\n String readLine;\n\n setDefaults();\n\n try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(Constants.USER_PREF_FILE_PATH), Charset.forName(\"UTF-8\")))) {\n while ((readLine = br.readLine()) != null) {\n String[] wordsList = readLine.split(\"=\");\n\n // if the words list is not correct, jump over the line\n if ((wordsList == null) || (wordsList.length < 2)) {\n continue;\n }\n\n switch (wordsList[0]) {\n case \"lastUsedDirectory\":\n lastDirectory = wordsList[wordsList.length - 1];\n break;\n\n case \"mergeBKG\":\n mergeBKG = Boolean.parseBoolean(wordsList[wordsList.length - 1]);\n break;\n\n case \"showScribbles\":\n showScribbles = Boolean.parseBoolean(wordsList[wordsList.length - 1]);\n break;\n\n case \"showCrops\":\n showCrops = Boolean.parseBoolean(wordsList[wordsList.length - 1]);\n break;\n\n case \"showJustCurrentObj\":\n showJustCurrentObj = Boolean.parseBoolean(wordsList[wordsList.length - 1]);\n break;\n\n case \"popUpObjects\":\n popUpObjects = Boolean.parseBoolean(wordsList[wordsList.length - 1]);\n break;\n\n case \"playBackward\":\n playBackward = Boolean.parseBoolean(wordsList[wordsList.length - 1]);\n break;\n\n case \"saveFrameObjMap\":\n saveFrameObjMap = Boolean.parseBoolean(wordsList[wordsList.length - 1]);\n break;\n\n\n case \"showObjHighlight\":\n showObjHighlight = Boolean.parseBoolean(wordsList[wordsList.length - 1]);\n break;\n\n case \"objAlphaVal\":\n objAlphaVal = Integer.parseInt(wordsList[wordsList.length - 1]);\n break;\n\n case \"flipVertically\":\n flipVertically = Boolean.parseBoolean(wordsList[wordsList.length - 1]);\n break;\n\n case \"mirrorImage\":\n mirrorImage = Boolean.parseBoolean(wordsList[wordsList.length - 1]);\n break;\n\n case \"preferredDPI\":\n preferredDPI = Integer.parseInt(wordsList[wordsList.length - 1]);\n break;\n\n case \"firstRun\":\n firstRun = Boolean.parseBoolean(wordsList[wordsList.length - 1]);\n break;\n\n case \"imgExportPath\":\n imgExportPath = wordsList[wordsList.length - 1];\n break;\n\n case \"imgExportExtension\":\n imgExportExtension = wordsList[wordsList.length - 1];\n break;\n\n case \"imgAutoExportEveryFrame\":\n imgAutoExportEveryFrame = Boolean.parseBoolean(wordsList[wordsList.length - 1]);\n break;\n\n case \"imgTypeForExport\":\n imgTypeForExport = wordsList[wordsList.length - 1];\n break;\n\n case \"imgTypeJoinedExport\":\n imgTypeJoinedExport = wordsList[wordsList.length - 1];\n break;\n\n case \"checkFrameAnnotations\":\n checkFrameAnnotations = Boolean.parseBoolean(wordsList[wordsList.length - 1]);\n break;\n\n case \"checkObjectAttributes\":\n checkObjectAttributes = Boolean.parseBoolean(wordsList[wordsList.length - 1]);\n break;\n\n default:\n log.info(\"The userPreferences.txt file contains an unknown key: {}\", wordsList[0]);\n break;\n }\n }\n } catch (IOException ex) {\n log.error(\"The user preferences file was not loaded! Will load default values!!\");\n log.debug(\"The user preferences file was not loaded! Will load default values!! {}\", ex);\n }\n }\n\n /**\n * Returns the directory of the last opened file.\n *\n * @return - the path to the directory from where the last file was opened\n */\n public String getLastDirectory() {\n return lastDirectory;\n }\n\n /**\n * Saves the path to the last opened file. This helps the user to not always\n * navigate through folders.\n *\n * @param lastDirectory - the path to the directory from where the last file was opened\n */\n public void setLastDirectory(String lastDirectory) {\n this.lastDirectory = lastDirectory;\n }\n\n /**\n * Shows if the user wants to have the background merged into the big result\n * or not. This is scribble labeling specific.\n *\n * @return - true if the user used last time the merge background and false otherwise\n */\n public boolean isMergeBKG() {\n return mergeBKG;\n }\n\n /**\n * Shows if the user wants to have the scribbles of the segmented objects,\n * visible on the drawing panel.\n *\n * @return - true if the user used last time the show scribbles and false otherwise\n */\n public boolean isShowScribbles() {\n return showScribbles;\n }\n\n /**\n * Shows if the user wants to have just the current object visible in the\n * drawing panel.\n *\n * @return - true if the user used last time the show just current object and false otherwise\n */\n public boolean isShowJustCurrentObj() {\n return showJustCurrentObj;\n }\n\n /**\n * Sets if the user wants to have the background merged into the big result\n * or not. This is scribble labeling specific.\n *\n * @param mergeBKG - true if the user used last time the merge background and false otherwise\n */\n public void setMergeBKG(boolean mergeBKG) {\n this.mergeBKG = mergeBKG;\n }\n\n /**\n * Sets if the user wants to have the scribbles of the segmented objects,\n * visible on the drawing panel.\n *\n * @param showScribbles - true if the user used last time the show scribbles and false otherwise\n */\n public void setShowScribbles(boolean showScribbles) {\n this.showScribbles = showScribbles;\n }\n\n /**\n * Sets if the user wants to have just the current object visible in the\n * drawing panel.\n *\n * @param showJustCurrentObj - true if the user used last time the show just current object and false otherwise\n */\n public void setShowJustCurrentObj(boolean showJustCurrentObj) {\n this.showJustCurrentObj = showJustCurrentObj;\n }\n\n /**\n * Shows if the user wants to have the crops of the segmented objects,\n * visible on the drawing panel.\n *\n * @return true if the user used last time the show crops and false otherwise\n */\n public boolean isShowCrops() {\n return showCrops;\n }\n\n /**\n * Sets if the user wants to have the crops of the segmented objects,\n * visible on the drawing panel.\n *\n * @param showCrops true if the user used last time the show crops and false otherwise\n */\n public void setShowCrops(boolean showCrops) {\n this.showCrops = showCrops;\n }\n\n /**\n * Shows if the user wants to have the objects pop up for review, after the\n * get next frame call.\n *\n * @return - true if the user wants to review the objects, therefore the user wants them to pop up and false otherwise\n */\n public boolean isPopUpObjects() {\n return popUpObjects;\n }\n\n /**\n * Sets if the user wants to have the objects pop up for review, after the\n * get next frame call.\n *\n * @param popUpObjects - true if the user wants to review the objects, therefore the user wants them to pop up and false otherwise\n */\n public void setPopUpObjects(boolean popUpObjects) {\n this.popUpObjects = popUpObjects;\n }\n\n /**\n * Shows if the user wants to have the video played forward or backward.\n *\n * @return - true if the user wants the video played backward and false if the user wants the video played forward\n */\n public boolean isPlayBackward() {\n return playBackward;\n }\n\n /**\n * Sets if the user wants to have the video played forward or backward.\n *\n * @param playBackward - true if the user wants the video played backward and false if the user wants the video played forward\n */\n public void setPlayBackward(boolean playBackward) {\n this.playBackward = playBackward;\n }\n\n /**\n * Shows if the user wants to save the file object map, when saving data in\n * the database.\n *\n * @return - true if the user wants to save the file object map and false if no file shall be saved\n */\n public boolean isSaveFrameObjMap() {\n return saveFrameObjMap;\n }\n\n /**\n * Sets if the user wants to save the file object map, when saving data in\n * the database.\n *\n * @param saveFrameObjMap - true if the user wants to save the file object map and false if no file shall be saved\n */\n public void setSaveFrameObjMap(boolean saveFrameObjMap) {\n this.saveFrameObjMap = saveFrameObjMap;\n }\n\n /**\n * Shows if the user wants to have the object highlighted.\n *\n * @return true if the user wants to have drawn a transparent layer over the object to highlight it and false if the user wants to have just the border of the object and no filling\n */\n public boolean isShowObjHighlight() {\n return showObjHighlight;\n }\n\n /**\n * Sets if the user wants to have the object highlighted.\n *\n * @param showObjHighlight true if the user wants to have drawn a transparent layer over the object to highlight it and false if the user wants to have just the border of the object and no filling\n */\n public void setShowObjHighlight(boolean showObjHighlight) {\n this.showObjHighlight = showObjHighlight;\n }\n\n /**\n * Shows the value of the alpha to be used for the highlight of the object.\n *\n * @return the integer value, between 0 and 255, for the alpha to be used for highlighting the object\n */\n public int getObjAlphaVal() {\n return objAlphaVal;\n }\n\n /**\n * Sets the value of the alpha to be used for the highlight of the object.\n *\n * @param objAlphaVal the integer value, between 0 and 255, for the alpha to be used for highlighting the object\n */\n public void setObjAlphaVal(int objAlphaVal) {\n this.objAlphaVal = objAlphaVal;\n }\n\n /**\n * Show if the user wants to have the image flipped vertically or not.\n *\n * @return true if the image shall be flipped vertically and false if the image shall not be changed\n */\n public boolean isFlipVertically() {\n return flipVertically;\n }\n\n /**\n * Sets if the user wants to have the image flipped vertically or not.\n *\n * @param flipVertically true if the image shall be flipped vertically and false if the image shall not be changed\n */\n public void setFlipVertically(boolean flipVertically) {\n this.flipVertically = flipVertically;\n }\n\n /**\n * Shows if the user wants to have the image mirrored or not.\n *\n * @return true if the image shall be mirrored and false if the image shall not be changed\n */\n public boolean isMirrorImage() {\n return mirrorImage;\n }\n\n /**\n * Sets if the user wants to have the image mirrored or not.\n *\n * @param mirrorImage true if the image shall be mirrored and false if the image shall not be changed\n */\n public void setMirrorImage(boolean mirrorImage) {\n this.mirrorImage = mirrorImage;\n }\n\n /**\n * Returns the preferred value of the DPI, used for rescaling the screen\n * image.\n *\n * @return the last used value for the DPI\n */\n public int getPreferredDPI() {\n return preferredDPI;\n }\n\n /**\n * Sets the preferred value of the DPI, used for rescaling the screen image.\n *\n * @param preferredDPI the user defined value for the DPI\n */\n public void setPreferredDPI(int preferredDPI) {\n this.preferredDPI = preferredDPI;\n }\n\n /**\n * Shows if the application is running for the first time.\n *\n * @return true if the application is running for the first time and false otherwise\n */\n public boolean isFirstRun() {\n return firstRun;\n }\n\n /**\n * Sets the flag regarding the application running for the first time.\n *\n * @param firstRun true if the application is running for the first time and false otherwise\n */\n public void setFirstRun(boolean firstRun) {\n this.firstRun = firstRun;\n }\n\n /**\n * Get the path where the user prefers to export images.\n *\n * @return the string representing the path where the images should be saved\n */\n public String getImgExportPath() {\n return imgExportPath;\n }\n\n /**\n * Set the path where the user prefers to export images.\n *\n * @param imgExportPath the string representing the path where the images should be saved\n */\n public void setImgExportPath(String imgExportPath) {\n this.imgExportPath = imgExportPath;\n }\n\n /**\n * Get the file type the user prefers for the export of images.\n *\n * @return the string representing the file type used for the saved images\n */\n public String getImgExportExtension() {\n return imgExportExtension;\n }\n\n /**\n * Set the file type the user prefers for the export of images.\n *\n * @param imgExportExtension the string representing the file type used for the saved images\n */\n public void setImgExportExtension(String imgExportExtension) {\n this.imgExportExtension = imgExportExtension;\n }\n\n /**\n * Set the possibility to export a certain type of image, every frame, till\n * the user changes the option.\n *\n * @return true if every frame should be exported; false if no automatic export shall be done\n */\n public boolean isImgAutoExportEveryFrame() {\n return imgAutoExportEveryFrame;\n }\n\n /**\n * Find out if the application should export a certain type of image, every\n * frame, till the user changes the option.\n *\n * @param imgAutoExportEveryFrame true if every frame should be exported; false if no automatic export shall be done\n */\n public void setImgAutoExportEveryFrame(boolean imgAutoExportEveryFrame) {\n this.imgAutoExportEveryFrame = imgAutoExportEveryFrame;\n }\n\n /**\n * Get the type of image to be exported: original, segmented or result\n * image.\n *\n * @return a string representing the type of the image exported every frame\n */\n public String getImgTypeForExport() {\n return imgTypeForExport;\n }\n\n /**\n * Set the type of image to be exported: original, segmented or result\n * image.\n *\n * @param imgTypeForExport a string representing the type of the image exported every frame\n */\n public void setImgTypeForExport(String imgTypeForExport) {\n this.imgTypeForExport = imgTypeForExport;\n }\n\n /**\n * Get the types of images to be joined for export: original + segmented +\n * result image.\n *\n * @return string representing the type of the images to be joined for exporting them every frame\n */\n public String getImgTypeJoinedExport() {\n return imgTypeJoinedExport;\n }\n\n /**\n * Set the types of images to be joined for export: original + segmented +\n * result image.\n *\n * @param imgTypeJoinedExport a string representing the type of the images to be joined for exporting them every frame\n */\n public void setImgTypeJoinedExport(String imgTypeJoinedExport) {\n this.imgTypeJoinedExport = imgTypeJoinedExport;\n }\n\n /**\n * Get the state of the check of frame attributes option (checks if the\n * frame attributes are set to a different value than the default).\n *\n * @return true if the frame attributes should be checked and false otherwise\n */\n public boolean isCheckFrameAnnotations() {\n return checkFrameAnnotations;\n }\n\n /**\n * Enables/Disables the check of frame attributes (checks if the frame\n * attributes are set to a different value than the default).\n *\n * @param checkFrameAnnotations true if the frame attributes should be checked and false otherwise\n */\n public void setCheckFrameAnnotations(boolean checkFrameAnnotations) {\n this.checkFrameAnnotations = checkFrameAnnotations;\n }\n\n /**\n * Get the state of the check of object attributes option (checks if the\n * object attributes are set to a different value than the default).\n *\n * @return true if the object attributes should be checked and false\n * otherwise\n */\n public boolean isCheckObjectAttributes() {\n return checkObjectAttributes;\n }\n\n /**\n * Enables/Disables the check of object attributes (checks if the object\n * attributes are set to a different value than the default).\n *\n * @param checkObjectAttributes true if the frame attributes should be\n * checked and false otherwise\n */\n public void setCheckObjectAttributes(boolean checkObjectAttributes) {\n this.checkObjectAttributes = checkObjectAttributes;\n }\n\n /**\n * Saves into the user preferences file the latest wishes of the user.\n */\n public void saveUserPreferences() {\n try {\n String fileContent = \"\";\n try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(Constants.USER_PREF_FILE_PATH), Charset.forName(\"UTF-8\")))) {\n fileContent += \"lastUsedDirectory=\" + lastDirectory + \"\\r\\n\";\n fileContent += \"mergeBKG=\" + mergeBKG + \"\\r\\n\";\n fileContent += \"showScribbles=\" + showScribbles + \"\\r\\n\";\n fileContent += \"showCrops=\" + showCrops + \"\\r\\n\";\n fileContent += \"showJustCurrentObj=\" + showJustCurrentObj + \"\\r\\n\";\n fileContent += \"popUpObjects=\" + popUpObjects + \"\\r\\n\";\n fileContent += \"playBackward=\" + playBackward + \"\\r\\n\";\n fileContent += \"saveFrameObjMap=\" + saveFrameObjMap + \"\\r\\n\";\n fileContent += \"showObjHighlight=\" + showObjHighlight + \"\\r\\n\";\n fileContent += \"objAlphaVal=\" + objAlphaVal + \"\\r\\n\";\n fileContent += \"flipVertically=\" + flipVertically + \"\\r\\n\";\n fileContent += \"mirrorImage=\" + mirrorImage + \"\\r\\n\";\n fileContent += \"preferredDPI=\" + preferredDPI + \"\\r\\n\";\n fileContent += \"firstRun=\" + false + \"\\r\\n\";\n fileContent += \"imgExportPath=\" + imgExportPath + \"\\r\\n\";\n fileContent += \"imgExportExtension=\" + imgExportExtension + \"\\r\\n\";\n fileContent += \"imgAutoExportEveryFrame=\" + imgAutoExportEveryFrame + \"\\r\\n\";\n fileContent += \"imgTypeForExport=\" + imgTypeForExport + \"\\r\\n\";\n fileContent += \"imgTypeJoinedExport=\" + imgTypeJoinedExport + \"\\r\\n\";\n fileContent += \"checkFrameAnnotations=\" + checkFrameAnnotations + \"\\r\\n\";\n fileContent += \"checkObjectAttributes=\" + checkObjectAttributes + \"\\r\\n\";\n\n bw.write(fileContent, 0, fileContent.length());\n bw.flush();\n }\n } catch (IOException ex) {\n Logger.getLogger(UserPreferences.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n\n /**\n * Set default values for user configuration parameters.\n */\n private void setDefaults() {\n // set some default initialisation values because the configuration file was not found\n lastDirectory = \"\";\n mergeBKG = false;\n showScribbles = true;\n showCrops = true;\n showJustCurrentObj = false;\n popUpObjects = true;\n playBackward = false;\n saveFrameObjMap = false;\n showObjHighlight = true;\n objAlphaVal = 60;\n flipVertically = false;\n mirrorImage = false;\n preferredDPI = 144;\n firstRun = true;\n imgExportPath = Constants.EXPORT_IMGS_PATH;\n imgExportExtension = \"jpeg\";\n imgAutoExportEveryFrame = false;\n imgTypeForExport = Constants.SEGMENTED_IMG;\n imgTypeJoinedExport = Constants.ORIGINAL_IMG + \",\" + Constants.SEGMENTED_IMG;\n checkFrameAnnotations = true;\n checkObjectAttributes = true;\n }\n}", "public class Utils {\n\n /**\n * logger instance\n */\n private static final Logger LOG = LoggerFactory.getLogger(Utils.class);\n\n /**\n * Utility classes, which are collections of static members, are not meant\n * to be instantiated. Even abstract utility classes, which can be extended,\n * should not have public constructors. Java adds an implicit public\n * constructor to every class which does not define at least one explicitly.\n * Hence, at least one non-public constructor should be defined.\n */\n private Utils() {\n throw new IllegalStateException(\"Utility class, do not instantiate!\");\n }\n\n /**\n * Get the image from the specified box.\n *\n * @param origImg - the original image from where the selection shall be\n * copied\n * @param posOrig - the position where the image has to be copied from\n * @return - the image contained in the specified crop\n */\n public static BufferedImage getSelectedImg(BufferedImage origImg, Rectangle posOrig) {\n Rectangle pos = posOrig;\n BufferedImage tempImg = null;\n\n if ((pos != null) && (pos.width > 0) && (pos.height > 0)) {\n tempImg = new BufferedImage(pos.width, pos.height, origImg.getType());\n\n for (int y = pos.y; y < pos.y + pos.height; y++) {\n for (int x = pos.x; x < pos.x + pos.width; x++) {\n tempImg.setRGB(x - pos.x, y - pos.y, origImg.getRGB(x, y));\n }\n }\n }\n\n return tempImg;\n }\n\n /**\n * Compute the l^2-Norm of the input vector.\n * <p>\n * |x| = sqrt(x1^2 + x2^2 + x3^2 + ... + xn^2)\n *\n * @param vector - the input vector\n * @return - the value of the norm of the vector\n */\n public static double computeVectorL2Norm(double[] vector) {\n double sum = 0.0;\n\n // compute the sum of squares\n for (int index = 0; index < vector.length; index++) {\n sum += vector[index] * vector[index];\n }\n\n // compute the compute square root of the sum of squares\n return Math.sqrt(sum);\n }\n\n /**\n * Compute squared euclidian distance double.\n *\n * @param vectorA the vector a\n * @param vectorB the vector b\n * @return the double\n */\n public static double computeSquaredEuclidianDistance(double[] vectorA, double[] vectorB) {\n if (vectorA.length != vectorB.length) {\n LOG.error(\"The input arrays have different sizes!!!\");\n }\n\n double squaredSum = 0.0;\n\n // compute the sum of square differences\n for (int index = 0; index < vectorA.length; index++) {\n squaredSum += (vectorA[index] - vectorB[index]) * (vectorA[index] - vectorB[index]);\n }\n\n return (squaredSum / vectorA.length);\n }\n\n /**\n * Gets the current date and time in the form of \"yyyy-MM-dd HH:mm:ss\".\n *\n * @return - the current date and time in the format: \"yyyy-MM-dd HH:mm:ss\"\n */\n public static String getCurrentTimeStamp() {\n java.util.Date dt = new java.util.Date();\n\n java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n\n return sdf.format(dt);\n }\n\n /**\n * Compute the location of the window relative to the mouse location. The\n * window shall be centered on the mouse location.\n *\n * @param winDim - the dimension of the window to be centered\n * @return - the point where the window shall be located\n */\n public static Point winLocRelativeToMouse(Dimension winDim) {\n Point mouse = MouseInfo.getPointerInfo().getLocation();\n Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();\n\n int x = (int) (mouse.getX() - (winDim.width / 2.0));\n int y = (int) (mouse.getY() - (winDim.height / 2.0));\n\n // check if the window will get out of the image\n x = Math.min(Math.max(0, x), Math.max(0, (screenSize.width - winDim.width)));\n y = Math.min(Math.max(0, y), Math.max(0, (screenSize.height - winDim.height - 100)));\n\n return (new Point(x, y));\n }\n\n /**\n * Check if the component com1 fits inside component comp2.\n *\n * @param comp1 - the size of the component to be checked if it fits\n * @param comp2 - the size of the component where the other component should\n * fit in\n * @return - return true if the component 1 fits in the component 2\n */\n public static boolean checkPlausability(Dimension comp1, Dimension comp2) {\n return ((comp1.width > 0) && (comp1.width <= comp2.width))\n && (comp1.height > 0) && (comp1.height <= comp2.height);\n }\n\n /**\n * Checks the extension of the given file and returns true if it is an image\n * file, or false otherwise.\n *\n * @param fileName - the name of the file to be checked\n * @return - true for image files and false for other file types\n */\n public static boolean isImageFile(String fileName) {\n return checkExtension(fileName, common.Constants.IMG_EXTENSION_LIST);\n }\n\n /**\n * Checks the extension of the given file and returns true if it is a video\n * file, or false otherwise.\n *\n * @param fileName - the name of the file to be checked\n * @return - true for video files and false for other file types\n */\n public static boolean isVideoFile(String fileName) {\n return checkExtension(fileName, common.Constants.VIDEO_EXTENSION_LIST);\n }\n\n /**\n * Get the extension of a file.\n *\n * @param f - the file itself\n * @return - the string representing the extension of the file\n */\n public static String getExtension(File f) {\n String fileName = f.getName();\n return getExtension(fileName);\n }\n\n /**\n * Get the extension of the string representing the name of a file.\n *\n * @param fileName - the name of the file\n * @return - the string representing the extension of the file\n */\n public static String getExtension(String fileName) {\n String ext = null;\n int i = fileName.lastIndexOf('.');\n if ((i > 0) && (i < fileName.length() - 1)) {\n ext = fileName.substring(i + 1).toLowerCase(Locale.ENGLISH);\n }\n return ext;\n }\n\n /**\n * Obtains the data from the raster of the given image as a byte array.\n *\n * @param image The image\n * @return The image data\n * @throws IllegalArgumentException If the given image is not backed by a\n * DataBufferByte. Usually, only BufferedImages of with the types\n * BufferedImage.TYPE_BYTE_* have a DataBufferByte\n */\n public static byte[] getByteData(BufferedImage image) {\n DataBuffer dataBuffer = image.getRaster().getDataBuffer();\n if (!(dataBuffer instanceof DataBufferByte)) {\n throw new IllegalArgumentException(\n \"Image does not contain a DataBufferByte\");\n }\n DataBufferByte dataBufferByte = (DataBufferByte) dataBuffer;\n byte data[] = dataBufferByte.getData();\n return data;\n }\n\n /**\n * Copy one buffered image to another.\n *\n * @param src - source image\n * @param dst - destination image\n */\n public static void copySrcIntoDstAt(final BufferedImage src, final BufferedImage dst) {\n byte[] srcBuf = getByteData(src);\n byte[] dstBuf = getByteData(dst);\n int representationFactor;\n\n // width * hight * 3 because of rgb components and byte representation\n switch (src.getType()) {\n case BufferedImage.TYPE_BYTE_GRAY:\n case BufferedImage.TYPE_BYTE_INDEXED:\n representationFactor = 1;\n break;\n case BufferedImage.TYPE_3BYTE_BGR:\n representationFactor = 3;\n break;\n case BufferedImage.TYPE_4BYTE_ABGR:\n representationFactor = 4;\n break;\n default:\n representationFactor = 3;\n break;\n }\n\n System.arraycopy(srcBuf, 0, dstBuf, 0, src.getWidth() * src.getHeight() * representationFactor);\n }\n\n /**\n * Copy one buffered image to another and return the copied image.\n *\n * @param src - source image\n * @return - the copied image of the original\n */\n public static BufferedImage createImageCopy(final BufferedImage src) {\n BufferedImage dst = new BufferedImage(src.getWidth(), src.getHeight(), src.getType());\n\n byte[] srcBuf = getByteData(src);\n byte[] dstBuf = getByteData(dst);\n int representationFactor;\n\n // width * hight * 3 because of rgb components and byte representation\n switch (src.getType()) {\n case BufferedImage.TYPE_BYTE_GRAY:\n representationFactor = 1;\n break;\n case BufferedImage.TYPE_3BYTE_BGR:\n representationFactor = 3;\n break;\n case BufferedImage.TYPE_4BYTE_ABGR:\n representationFactor = 4;\n break;\n default:\n representationFactor = 3;\n break;\n }\n\n System.arraycopy(srcBuf, 0, dstBuf, 0, src.getWidth() * src.getHeight() * representationFactor);\n\n return dst;\n }\n\n /**\n * Convert a matrix into a gray scale buffered image.\n *\n * @param width - the width of the image\n * @param height - the height of the image\n * @param imageType - the type of image to create\n * @param imgMatrix - the matrix with the pixels of the image\n * @return - a buffered image, based on the input matrix\n */\n public static BufferedImage convertToBuffImage(int width, int height, int imageType, double[][] imgMatrix) {\n BufferedImage bi = new BufferedImage(width, height, imageType);\n for (int y = 0; y < height; y++) {\n for (int x = 0; x < width; x++) {\n int pixel = Utils.limit(0, (int) imgMatrix[x][y], 255);\n bi.setRGB(x, y, new Color(pixel, pixel, pixel).getRGB());\n }\n }\n\n return bi;\n }\n\n /**\n * Apply the histogram equalisation for the input image.\n *\n * @param originalImage - the image to be processed\n * @return - the image with the equalisation of histogram applied - in\n * grayscale\n */\n public static BufferedImage histogramEqGrayscale(BufferedImage originalImage) {\n BufferedImage workImage = new BufferedImage(originalImage.getWidth(), originalImage.getHeight(), originalImage.getType());\n\n int[] rgb;\n int[] meanIntensity = new int[256];\n int[] histCum = new int[256];\n int[] transf = new int[256];\n\n for (int i = 0; i < originalImage.getWidth(); i++) {\n for (int j = 0; j < originalImage.getHeight(); j++) {\n rgb = getRGB(originalImage.getRGB(i, j));\n\n int average = (int) (0.299 * rgb[0] + 0.587 * rgb[1] + 0.114 * rgb[2]);\n\n meanIntensity[average]++;\n }\n }\n histCum[0] = meanIntensity[0];\n\n for (int i = 1; i < 256; i++) {\n histCum[i] = meanIntensity[i] + histCum[i - 1];\n }\n\n for (int i = 0; i < 256; i++) {\n transf[i] = (255 * histCum[i]) / (originalImage.getWidth() * originalImage.getHeight());\n }\n\n for (int i = 0; i < originalImage.getWidth(); i++) {\n for (int j = 0; j < originalImage.getHeight(); j++) {\n rgb = getRGB(originalImage.getRGB(i, j));\n int average = (int) (0.299 * rgb[0] + 0.587 * rgb[1] + 0.114 * rgb[2]);\n workImage.setRGB(i, j, new Color(transf[average], transf[average], transf[average]).getRGB());\n }\n }\n return workImage;\n\n }\n\n /**\n * Apply the histogram equalisation for the input image.\n *\n * @param originalImage - the image to be processed\n * @return - the image with the equalisation of histogram applied - in color\n */\n public static BufferedImage histogramEqColor(BufferedImage originalImage) {\n BufferedImage workImage = new BufferedImage(originalImage.getWidth(), originalImage.getHeight(), originalImage.getType());\n\n int[] rgb;\n int[] meanIntensityR = new int[256];\n int[] histCumR = new int[256];\n int[] transfR = new int[256];\n\n int[] meanIntensityG = new int[256];\n int[] histCumG = new int[256];\n int[] transfG = new int[256];\n\n int[] meanIntensityB = new int[256];\n int[] histCumB = new int[256];\n int[] transfB = new int[256];\n\n for (int i = 0; i < originalImage.getWidth(); i++) {\n for (int j = 0; j < originalImage.getHeight(); j++) {\n rgb = getRGB(originalImage.getRGB(i, j));\n meanIntensityR[rgb[0]]++;\n meanIntensityG[rgb[1]]++;\n meanIntensityB[rgb[2]]++;\n }\n }\n histCumR[0] = meanIntensityR[0];\n histCumG[0] = meanIntensityG[0];\n histCumB[0] = meanIntensityB[0];\n\n for (int i = 1; i < 256; i++) {\n histCumR[i] = meanIntensityR[i] + histCumR[i - 1];\n histCumG[i] = meanIntensityG[i] + histCumG[i - 1];\n histCumB[i] = meanIntensityB[i] + histCumB[i - 1];\n }\n\n for (int i = 0; i < 256; i++) {\n transfR[i] = (255 * histCumR[i]) / (originalImage.getWidth() * originalImage.getHeight());\n transfG[i] = (255 * histCumG[i]) / (originalImage.getWidth() * originalImage.getHeight());\n transfB[i] = (255 * histCumB[i]) / (originalImage.getWidth() * originalImage.getHeight());\n }\n\n for (int i = 0; i < originalImage.getWidth(); i++) {\n for (int j = 0; j < originalImage.getHeight(); j++) {\n rgb = getRGB(originalImage.getRGB(i, j));\n workImage.setRGB(i, j, new Color(transfR[rgb[0]], transfG[rgb[1]], transfB[rgb[2]]).getRGB());\n }\n }\n return workImage;\n }\n\n /**\n * Changes the input color to a similar color, which is not reserved.\n *\n * @param inputColor - the input color\n * @param objColorsList the obj colors list\n * @return - a color which is not reserved and it is similar to the input\n * one\n */\n public static Color changeColor(Color inputColor, List<Color> objColorsList) {\n int[] rgb = getRGB(inputColor.getRGB());\n Random rand = new Random();\n int randRange = 60;\n\n // change the color\n for (int index = 0; index < rgb.length; index++) {\n\n // add random values in the range [-0.5*range; +0.5*range)\n rgb[index] += (rand.nextInt(randRange) - (int) (randRange * 0.5f));\n\n // limit the value to byte\n rgb[index] = limit(0, rgb[index], 255);\n }\n\n // set the new color \n Color color = new Color(rgb[0], rgb[1], rgb[2]);\n\n // make sure that the color is not reserved as well\n if (objColorsList.contains(color) || Constants.COLORS_LIST.contains(color)) {\n changeColor(color, objColorsList);\n }\n\n return color;\n }\n\n /**\n * Parse the given file path and name in order to extract just the file name\n * (with or without the extension, depending on the choice).\n *\n * @param fileNamePath the original file name, including its path\n * @param withExtension true if the returned name should include the file\n * extension; false if just the name of the file alone should be provided\n * @return the name of the file (with or without extension - as specified),\n * without its path\n */\n public static String getFileName(String fileNamePath, boolean withExtension) {\n // extract the name of the file and save it to create a folder there and store the info\n String[] tempStr;\n if (System.getProperty(\"os.name\").toLowerCase(Locale.ENGLISH).contains(\"win\")) {\n tempStr = fileNamePath.split(File.separator + File.separator);\n } else {\n tempStr = fileNamePath.split(File.separator);\n }\n\n if (withExtension) {\n return tempStr[tempStr.length - 1];\n } else {\n // get the name of the file without extension\n return tempStr[tempStr.length - 1].substring(0, tempStr[tempStr.length - 1].lastIndexOf('.'));\n }\n }\n\n /**\n * Adjusts the contrast of the image - NOT TESTED yet - to be checked and\n * optimised.\n *\n * @param workImage the work image\n * @param min the min\n * @param max the max\n * @return buffered image\n */\n public static BufferedImage contrast(BufferedImage workImage, int min, int max) {\n int[] rgb;\n int minimR = 255;\n int maximR = 0;\n int minimG = 255;\n int maximG = 0;\n int minimB = 255;\n int maximB = 0;\n\n // find the minimum and maximum values for R G and B\n for (int i = 0; i < workImage.getWidth(); i++) {\n for (int j = 0; j < workImage.getHeight(); j++) {\n rgb = getRGB(workImage.getRGB(i, j));\n\n minimR = Math.min(minimR, rgb[0]);\n minimG = Math.min(minimG, rgb[1]);\n minimB = Math.min(minimB, rgb[2]);\n\n maximR = Math.max(maximR, rgb[0]);\n maximG = Math.max(maximG, rgb[1]);\n maximB = Math.max(maximB, rgb[2]);\n }\n }\n\n // adjust the intensities\n for (int i = 0; i < workImage.getWidth(); i++) {\n for (int j = 0; j < workImage.getHeight(); j++) {\n rgb = getRGB(workImage.getRGB(i, j));\n int intensR = (rgb[0] - minimR) * (max - min) / (maximR - minimR) + min;\n int intensG = (rgb[1] - minimG) * (max - min) / (maximG - minimG) + min;\n int intensB = (rgb[2] - minimB) * (max - min) / (maximB - minimB) + min;\n workImage.setRGB(i, j, new Color(intensR, intensG, intensB).getRGB());\n }\n }\n return workImage;\n }\n\n /**\n * Extract the RGB information from a pixel.\n *\n * @param pixel - the packed value of the color of the pixel\n * @return - returns an array which represents in this order the values of\n * R, G and B components of the pixel\n */\n public static int[] getRGB(int pixel) {\n int[] rgb = new int[3];\n rgb[0] = ((pixel & 0x00FF0000) >>> 16); //red color\n rgb[1] = ((pixel & 0x0000FF00) >>> 8); //green color\n rgb[2] = (pixel & 0x000000FF); //blue color\n return rgb;\n }\n\n /**\n * Returns a list of all the files (jpg and png) contained by the specified\n * folder.\n *\n * @param folder - the folder for which the list of image files is wanted\n * @return - an array of strings representing all the image files found\n * inside\n */\n public static List<String> listFilesForFolder(final File folder) {\n List<String> filesList = new ArrayList<>();\n\n if (folder.length() > 0) {\n for (final File fileEntry : folder.listFiles()) {\n if (fileEntry.isDirectory()) {\n listFilesForFolder(fileEntry);\n } else if (fileEntry.getName().endsWith(\".jpg\") || fileEntry.getName().endsWith(\".JPG\")\n || fileEntry.getName().endsWith(\".png\") || fileEntry.getName().endsWith(\".PNG\")) {\n filesList.add(fileEntry.getAbsolutePath());\n LOG.trace(fileEntry.getAbsolutePath());\n }\n }\n }\n\n return filesList;\n }\n\n /**\n * Fill in a matrix with a default value.\n *\n * @param width - the width of the matrix\n * @param height - the height of the matrix\n * @param value - the value to be filled in\n * @return - the matrix filled in with the wanted default value\n */\n public static int[][] initMatrix(int width, int height, int value) {\n int[][] array = new int[height][width];\n\n for (int y = 0; y < height; y++) {\n Arrays.fill(array[y], value);\n }\n\n return array;\n }\n\n /**\n * Fill in a matrix with a default value.\n *\n * @param width - the width of the matrix\n * @param height - the height of the matrix\n * @param value - the value to be filled in\n * @return - the matrix containing the wanted default value\n */\n public static float[][] initMatrix(int width, int height, float value) {\n float[][] array = new float[height][width];\n\n for (int y = 0; y < height; y++) {\n Arrays.fill(array[y], value);\n }\n\n return array;\n }\n\n /**\n * Generate a custom mouse icon to have it as preview while drawing\n * scribbles.\n *\n * @param brushOpt - the configuration of the icon to be generated\n * @param actionType - the id of the object for which the icon is created\n * @param objColor the obj color\n * @return - the cursor to be displayed by the mouse\n */\n public static Cursor generateCustomIcon(BrushOptions brushOpt, int actionType, Color objColor) {\n Cursor cursor;\n if (brushOpt.getBrushSize() > Constants.MIN_MOUSE_BRUSH_ICON) {\n Toolkit toolkit = Toolkit.getDefaultToolkit();\n\n Dimension dim = toolkit.getBestCursorSize(brushOpt.getBrushSize(), brushOpt.getBrushSize());\n BufferedImage buffered = new BufferedImage(dim.width, dim.height, BufferedImage.TYPE_INT_ARGB);\n Graphics2D g = buffered.createGraphics();\n float density = brushOpt.getBrushDensity();\n Random rand = new Random();\n byte[][] circleMask = getCircleMask(brushOpt.getBrushSize()); // the mask making the mouse pointer a circle\n\n if (brushOpt.getBrushSize() <= 5) {\n density = 1.0f;\n } else if (brushOpt.getBrushSize() > 5 && brushOpt.getBrushSize() < 10) {\n density = Math.max(0.5f, density);\n }\n\n // objects smaller than 0 are for erase purposes and the density is always full\n if (actionType < 0) {\n density = 1.0f;\n }\n\n // draw the inner part of the brush, the one which will show after a click\n g.setColor(getDrawingColor(actionType, objColor));\n\n for (int x = 1; x <= brushOpt.getBrushSize(); x++) {\n for (int y = 1; y <= brushOpt.getBrushSize(); y++) {\n float randFloat = rand.nextFloat();\n if ((randFloat < density) && (circleMask[x - 1][y - 1] == (byte) 1)) {\n g.drawLine(x, y, x, y);\n }\n }\n }\n\n // draw a white box around the brush for better visibility\n g.setColor(Color.white);\n\n g.drawOval(0, 0, brushOpt.getBrushSize() + 1, brushOpt.getBrushSize() + 1);\n\n g.dispose();\n\n int drawlLocation = (int) (brushOpt.getBrushSize() * 0.5f);\n cursor = toolkit.createCustomCursor(buffered, new Point(drawlLocation, drawlLocation), \"myCursor\");\n\n } else {\n cursor = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR);\n }\n\n return cursor;\n }\n\n /**\n * Choose the best background for text: white for dark text, black for\n * bright text.\n *\n * @param color - the color for which the background shall be computed.\n * @param transparency - the wanted transparency for the returned color\n * @return - the adviced color for the background based on luminance\n */\n public static Color getContrastColor(Color color, int transparency) {\n // no precision needed here\n int y = (299 * color.getRed() + 587 * color.getGreen() + 114 * color.getBlue()) / 1000;\n\n return ((y >= 128) ? new Color(0, 0, 0, transparency) : new Color(255, 255, 255, transparency));\n }\n\n /**\n * Returns the color: 0 = red (bkg), 1 = the color of the current object\n * (object), other: white (eraser).\n *\n * @param id - the value for which the color has to be established\n * @param objColor - the color of the object (object = not bkg , not erase)\n * @return - the corresponding color 0 = red, 1 = the color of the current\n * object, other = white\n */\n public static Color getDrawingColor(int id, Color objColor) {\n switch (id) {\n case 0:\n return Color.red;\n case 1:\n return objColor;\n default:\n return Color.white;\n }\n }\n\n /**\n * Maps the objects to colors.\n *\n * @param id - the id of the object, in the database\n * @return - the color of the object with the specified id\n */\n public static Color getColorOfObjByID(long id) {\n // compute the index of the color based on the object id\n int colorIndex = (int) (id % Constants.COLORS_LIST.size());\n\n return Constants.COLORS_LIST.get(colorIndex);\n }\n\n /**\n * Limit value between specified min and max values\n * <p>\n * value = [min,max]\n *\n * @param min min value\n * @param value value to be limited\n * @param max max value\n * @return returns the bounded value\n */\n public static int limit(int min, int value, int max) {\n return (value < min) ? min : ((value > max) ? max : value);\n }\n\n /**\n * Limit value between specified min and max values\n * <p>\n * value = [min,max]\n *\n * @param min min value\n * @param value value to be limited\n * @param max max value\n * @return returns the bounded value\n */\n public static long limit(long min, long value, long max) {\n return (value < min) ? min : ((value > max) ? max : value);\n }\n\n /**\n * Computes the CRC32 for a specified file\n *\n * @param fileName file for which the CRC32 is calculated\n * @return CRC32 for the specified file in String format\n */\n public static String CRC32(String fileName) {\n try (FileInputStream fi = new FileInputStream(fileName)) {\n\n /* allocates a buffer of 1MB for reading the video file\n this size seems to provide the fastest runtime\n */\n byte[] b = new byte[1024 * 1024];\n int len;\n CRC32 crc = new CRC32();\n\n while ((len = fi.read(b)) >= 0) {\n crc.update(b, 0, len);\n }\n\n // create the hash\n return (new BigInteger(Long.toString(crc.getValue())).toString(16));\n } catch (FileNotFoundException ex) {\n LOG.error(\"File {} not found\", fileName);\n LOG.debug(\"File {} not found exception {}\", fileName, ex);\n } catch (IOException ex) {\n LOG.error(\"File {} not accessible\", fileName);\n LOG.debug(\"File {} not accessible exception {}\", fileName, ex);\n }\n return null;\n }\n\n /**\n * Filter the object map array.\n * <p>\n * The filtering is done by sliding a window over the input array and\n * compute the sum of the values in the window (sum of 1s). If the sum is\n * smaller than a threshold, make the middle value of the window 0, else 1.\n * <p>\n * The filter aims to keep the white pixels which are in a neighbourhood of\n * other white pixels and discard the lonely pixels.\n *\n * @param objMap - the object map to be filtered\n */\n public static void filterObjectMap(byte[][] objMap) {\n if (objMap == null) {\n return;\n }\n\n // run N times the filtering algorithm\n // for (int steps = 0; steps < 10; steps++) {\n int filterSize = 3;\n byte[][] inputMap = new byte[objMap.length][objMap[0].length];\n\n for (int line = 0; line < objMap.length; line++) {\n inputMap[line] = objMap[line].clone();\n }\n\n for (int y = 0; y < inputMap[0].length - 2; y++) {\n for (int x = 0; x < inputMap.length - 2; x++) {\n int sum = 0;\n for (int j = 0; j < filterSize; j++) {\n for (int i = 0; i < filterSize; i++) {\n sum += inputMap[x + i][y + j];\n }\n }\n\n if (sum < Math.ceil(filterSize * filterSize * 0.5)) {\n objMap[x + (int) (filterSize * 0.5f)][y + (int) (filterSize * 0.5f)] = 0;\n } else {\n objMap[x + (int) (filterSize * 0.5f)][y + (int) (filterSize * 0.5f)] = 1;\n }\n }\n }\n\n // filter the first and last line\n for (int x = 0; x < inputMap.length - 2; x++) {\n int sum0 = 0; // sum for the first line\n int sumN = 0; // sum for the last line\n for (int j = 0; j < filterSize - 1; j++) {\n for (int i = 0; i < filterSize; i++) {\n sum0 += inputMap[x + i][j];\n sumN += inputMap[x + i][inputMap[0].length - 1 - j];\n }\n }\n // filter first line\n if (sum0 < Math.ceil((filterSize - 1) * filterSize * 0.5)) {\n objMap[x + (int) (filterSize * 0.5f)][0] = 0;\n } else {\n objMap[x + (int) (filterSize * 0.5f)][0] = 1;\n }\n\n // filter last line\n if (sumN < Math.ceil((filterSize - 1) * filterSize * 0.5)) {\n objMap[x + (int) (filterSize * 0.5f)][inputMap[0].length - 1] = 0;\n } else {\n objMap[x + (int) (filterSize * 0.5f)][inputMap[0].length - 1] = 1;\n }\n }\n\n // filter the first and last column\n for (int y = 0; y < inputMap[0].length - 2; y++) {\n int sum0 = 0; // sum for the first column\n int sumN = 0; // sum for the last column\n for (int j = 0; j < filterSize; j++) {\n for (int i = 0; i < filterSize - 1; i++) {\n sum0 += inputMap[i][y + j];\n sumN += inputMap[inputMap.length - 1 - i][y + j];\n }\n }\n\n // filter first column\n if (sum0 < Math.ceil(filterSize * (filterSize - 1) * 0.5)) {\n objMap[0][y + (int) (filterSize * 0.5f)] = 0;\n } else {\n objMap[0][y + (int) (filterSize * 0.5f)] = 1;\n }\n\n // filter last column\n if (sumN < Math.ceil(filterSize * (filterSize - 1) * 0.5)) {\n objMap[inputMap.length - 1][y + (int) (filterSize * 0.5f)] = 0;\n } else {\n objMap[inputMap.length - 1][y + (int) (filterSize * 0.5f)] = 1;\n }\n }\n\n // filter the corners\n // left - top\n int sum = objMap[0][0] + objMap[0][1] + objMap[1][0] + objMap[1][1];\n objMap[0][0] = (byte) ((sum < 3) ? 0 : 1);\n\n // right - top\n sum = objMap[inputMap.length - 1][0] + objMap[inputMap.length - 1][1] + objMap[inputMap.length - 2][0] + objMap[inputMap.length - 2][1];\n objMap[inputMap.length - 1][0] = (byte) ((sum < 3) ? 0 : 1);\n\n // left - bottom\n sum = objMap[0][inputMap[0].length - 1] + objMap[0][inputMap[0].length - 2] + objMap[1][inputMap[0].length - 1] + objMap[1][inputMap[0].length - 2];\n objMap[0][inputMap[0].length - 1] = (byte) ((sum < 3) ? 0 : 1);\n\n // right - bottom\n sum = objMap[inputMap.length - 1][inputMap[0].length - 1]\n + objMap[inputMap.length - 2][inputMap[0].length - 1]\n + objMap[inputMap.length - 1][inputMap[0].length - 2]\n + objMap[inputMap.length - 2][inputMap[0].length - 2];\n objMap[inputMap.length - 1][inputMap[0].length - 1] = (byte) ((sum < 3) ? 0 : 1);\n\n }\n\n /**\n * Computes the integer logarithm in base 2 of the input number.\n *\n * @param n - the input number\n * @return - the integer value of the log base 2 of n\n */\n public static int log2N(int n) {\n if (n == 0) {\n return 0;\n }\n return (31 - Integer.numberOfLeadingZeros(n));\n }\n\n /**\n * A sigmoid function is a mathematical function having an \"S\" shaped curve\n * (sigmoid curve).\n *\n * @param value the value/point for which the sigmoid function has to be\n * computed\n * @return - the value of the sigmoid function in the given point\n */\n public static double sigmoidFunction(double value) {\n return 1.0 / (1.0 + Math.exp(-value));\n }\n\n /**\n * Based on the size of the generated box, compute a border size to be added\n * to the displayed image.\n *\n * @param box - the original box size\n * @param borderPercentageWidth - the percentage of border to be added on\n * width\n * @param borderPercentageHeight - the percentage of border to be added on\n * height\n * @param minBorder - the min border in pixels\n * @param frameSize - the max size the box can have, after being bordered\n * @return - the size of the possible border for the input box\n */\n public static BoxLRTB getBorderedSize(Rectangle box,\n double borderPercentageWidth,\n double borderPercentageHeight,\n int minBorder,\n Dimension frameSize) {\n\n int borderWidth = (int) (borderPercentageWidth * box.width);\n int borderHeight = (int) (borderPercentageHeight * box.height);\n\n // if the border is too small, make it at least 10 pixels\n if (borderWidth < minBorder) {\n borderWidth = minBorder;\n }\n\n if (borderHeight < minBorder) {\n borderHeight = minBorder;\n }\n\n // set the border as 20% of the size of the box\n BoxLRTB borderSize = new BoxLRTB(borderWidth, borderHeight);\n\n // limit the bordering in such way as to not get out of the image\n if ((box.x - borderWidth) < 0) {\n borderSize.setxLeft(box.x);\n }\n\n if ((box.y - borderHeight) < 0) {\n borderSize.setyTop(box.y);\n }\n\n if ((box.x + box.width + borderWidth) > frameSize.width) {\n borderSize.setxRight(frameSize.width - (box.x + box.width));\n }\n\n if ((box.y + box.height + borderHeight) > frameSize.height) {\n borderSize.setyBottom(frameSize.height - (box.y + box.height));\n }\n\n // return the new size of the border to be added\n return borderSize;\n }\n\n /**\n * Based on the size of the generated box, compute a border size to be added\n * to the displayed image.\n *\n * @param box - the original box size\n * @param targetBorder - the wanted border in pixels\n * @param frameSize - the max size the box can have, after being bordered\n * @return - the size of the possible border for the input box\n */\n public static BoxLRTB getBorderedSize(Rectangle box,\n int targetBorder,\n Dimension frameSize) {\n\n // set the border as 20% of the size of the box\n BoxLRTB borderSize = new BoxLRTB(targetBorder, targetBorder);\n\n // limit the bordering in such way as to not get out of the image\n if ((box.x - targetBorder) < 0) {\n borderSize.setxLeft(box.x);\n }\n\n if ((box.y - targetBorder) < 0) {\n borderSize.setyTop(box.y);\n }\n\n if ((box.x + box.width + targetBorder) > frameSize.width) {\n borderSize.setxRight(frameSize.width - (box.x + box.width));\n }\n\n if ((box.y + box.height + targetBorder) > frameSize.height) {\n borderSize.setyBottom(frameSize.height - (box.y + box.height));\n }\n\n // return the new size of the border to be added\n return borderSize;\n }\n\n /**\n * Check if it is possible to connect to the specified server.\n *\n * @param serverAddress the address of the server where the connection shall\n * be checked\n * @param portNo the number of the port on which the connection shall be\n * done\n * @return true if the server is reachable and false if the address and port\n * does not represent a valid path to a server\n */\n public static boolean isServerOnline(String serverAddress, int portNo) {\n try {\n InetSocketAddress socketAddress = new InetSocketAddress(serverAddress, portNo);\n // conect to the server\n try (Socket socket = new Socket()) {\n // conect to the server\n socket.connect(socketAddress, 100);\n }\n return true;\n } catch (Exception e) {\n LOG.error(\"Communication with the server couldn't be established\");\n LOG.debug(\"Communication with the server couldn't be established {}\", e);\n return false;\n }\n }\n\n /**\n * Generates a mask, representing a circle, of the size specified by the\n * size parameter. The mask contains a circle with 1s and background (as\n * 0s).The mask is to be used in the drawing of the mouse brush and for the\n * scribbles generation.\n * <p>\n * <p>\n * x = cx + r * cos(a)\n * <p>\n * y = cy + r * sin(a)\n * <p>\n * Where r is the radius, cx,cy the origin, and a the angle (in radian).\n *\n * @param size - the size of the mask\n * @return - the mask representing a filled circle, of radius = size / 2\n */\n public static byte[][] getCircleMask(int size) {\n switch (size) {\n case 3:\n return CircleTemplate.CIRCLE_MASK_3X3;\n\n case 4:\n return CircleTemplate.CIRCLE_MASK_4X4;\n\n case 5:\n return CircleTemplate.CIRCLE_MASK_5X5;\n\n case 6:\n return CircleTemplate.CIRCLE_MASK_6X6;\n\n case 7:\n return CircleTemplate.CIRCLE_MASK_7X7;\n\n case 8:\n return CircleTemplate.CIRCLE_MASK_8X8;\n\n case 9:\n return CircleTemplate.CIRCLE_MASK_9X9;\n\n case 10:\n return CircleTemplate.CIRCLE_MASK_10X10;\n\n case 11:\n return CircleTemplate.CIRCLE_MASK_11X11;\n\n case 12:\n return CircleTemplate.CIRCLE_MASK_12X12;\n\n case 13:\n return CircleTemplate.CIRCLE_MASK_13X13;\n\n case 14:\n return CircleTemplate.CIRCLE_MASK_14X14;\n\n case 15:\n return CircleTemplate.CIRCLE_MASK_15X15;\n\n case 16:\n return CircleTemplate.CIRCLE_MASK_16X16;\n\n case 17:\n return CircleTemplate.CIRCLE_MASK_17X17;\n\n case 18:\n return CircleTemplate.CIRCLE_MASK_18X18;\n\n case 19:\n return CircleTemplate.CIRCLE_MASK_19X19;\n\n case 20:\n return CircleTemplate.CIRCLE_MASK_20X20;\n\n case 21:\n return CircleTemplate.CIRCLE_MASK_21X21;\n\n case 22:\n return CircleTemplate.CIRCLE_MASK_22X22;\n\n case 23:\n return CircleTemplate.CIRCLE_MASK_23X23;\n\n case 24:\n return CircleTemplate.CIRCLE_MASK_24X24;\n\n case 25:\n return CircleTemplate.CIRCLE_MASK_25X25;\n\n case 26:\n return CircleTemplate.CIRCLE_MASK_26X26;\n\n case 27:\n return CircleTemplate.CIRCLE_MASK_27X27;\n\n case 28:\n return CircleTemplate.CIRCLE_MASK_28X28;\n\n case 29:\n return CircleTemplate.CIRCLE_MASK_29X29;\n\n case 30:\n return CircleTemplate.CIRCLE_MASK_30X30;\n\n default:\n return CircleTemplate.CIRCLE_MASK_5X5;\n }\n }\n\n /**\n * Returns the capitalised string\n *\n * @param name string to be capitalised\n * @return the capitalised string\n */\n public static String capitalize(String name) {\n if (name == null || name.length() == 0) {\n return name;\n }\n\n return name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase();\n }\n\n /**\n * Create the directories structure for the given path.\n *\n * @param path - the path which has to be created if it does not exist\n */\n public static void createFolderPath(String path) {\n // create the directory structure\n File file = new File(path + \"text.txt\");\n file.getParentFile().mkdirs();\n }\n\n /**\n * Check if the extension of the file is one of the wanted. Only files which\n * represent images can be loaded.\n *\n * @param fileName the name of the current file in the directory structure\n * @param collection the collection which has to be checked for matching\n * (the list of extensions)\n * @return true if the file is a wanted type; false if the file represents a\n * not wanted format\n */\n public static boolean checkExtension(String fileName, List<String> collection) {\n // convert the name of the file to lower case, to avoid missing file types (jpg vs JPG) \n return collection.stream().anyMatch((String extension) -> fileName.toLowerCase().endsWith(\".\" + extension));\n }\n\n /**\n * Get an input string and replace all non alpha numeric characters with a\n * given string.\n *\n * @param inputStr the string to be changed\n * @param replaceStr the character to replace any non alpha numeric\n * character in the input string\n * @return string\n */\n public static String replaceNonAlphaNum(String inputStr, String replaceStr) {\n String output = inputStr.replaceAll(\"[^A-Za-z0-9 ]\", replaceStr);\n\n // if the output string ends with a replace string, remove it\n if (output.endsWith(replaceStr)) {\n output = output.substring(0, output.length() - replaceStr.length());\n }\n\n return output;\n }\n\n /**\n * Converts a number representing bytes to the biggest possible multiple.\n *\n * @param bytes the number to be converted\n * @param si true if the display system should be decimal (kilobyte - kB,\n * megabyte - MB etc.); false if the display system should be binary\n * (kibibyte - KB, mebibyte - MiB, gibibyte - GiB etc.)\n * @return the transformation of the number to the biggest metric\n */\n public static String humanReadableByteCount(long bytes, boolean si) {\n int unit = si ? 1000 : 1024;\n if (bytes < unit) {\n return bytes + \" B\";\n }\n int exp = (int) (Math.log(bytes) / Math.log(unit));\n String pre = (si ? \"kMGTPE\" : \"KMGTPE\").charAt(exp - 1) + (si ? \"\" : \"i\");\n return String.format(\"%.1f %sB\", bytes / Math.pow(unit, exp), pre);\n }\n\n /**\n * Mirror the image/buffer data\n *\n * @param image the image containing the pixel data which has to be\n * mirrored. This function will alter the bytes of the input image, so that\n * after this function the input image will contain the mirrored information\n */\n public static void mirrorImage(BufferedImage image) {\n byte[] bgr = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();\n byte[] mirror = new byte[bgr.length];\n final int multiplier = 3; // BGR\n\n for (int j = 0; j < image.getHeight(); j++) {\n for (int i = 0; i < image.getWidth(); i++) {\n mirror[(j * (image.getWidth() * multiplier)) + ((((image.getWidth() - 1) - i) * multiplier) + 0)] = bgr[(j * (image.getWidth() * multiplier)) + (i * multiplier + 0)]; // R\n mirror[(j * (image.getWidth() * multiplier)) + ((((image.getWidth() - 1) - i) * multiplier) + 1)] = bgr[(j * (image.getWidth() * multiplier)) + (i * multiplier + 1)]; // G\n mirror[(j * (image.getWidth() * multiplier)) + ((((image.getWidth() - 1) - i) * multiplier) + 2)] = bgr[(j * (image.getWidth() * multiplier)) + (i * multiplier + 2)]; // B\n }\n }\n\n System.arraycopy(mirror, 0, bgr, 0, image.getWidth() * image.getHeight() * multiplier);\n }\n\n /**\n * Flip vertically the image\n *\n * @param image the image containing the pixel data which has to be flipped\n * vertically. This function will alter the bytes of input image, so that\n * after this function the input image will contain the flipped information\n */\n public static void flipVerticallyImage(BufferedImage image) {\n byte[] bgr = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();\n byte[] flipped = new byte[bgr.length];\n final int multiplier = 3; // BGR\n\n for (int j = 0; j < image.getHeight(); j++) {\n for (int i = 0; i < image.getWidth(); i++) {\n flipped[((image.getHeight() - 1) - j) * (image.getWidth() * multiplier) + (i * multiplier + 0)] = bgr[(j * (image.getWidth() * multiplier)) + (i * multiplier + 0)]; // R\n flipped[((image.getHeight() - 1) - j) * (image.getWidth() * multiplier) + (i * multiplier + 1)] = bgr[(j * (image.getWidth() * multiplier)) + (i * multiplier + 1)]; // G\n flipped[((image.getHeight() - 1) - j) * (image.getWidth() * multiplier) + (i * multiplier + 2)] = bgr[(j * (image.getWidth() * multiplier)) + (i * multiplier + 2)]; // B\n }\n }\n\n System.arraycopy(flipped, 0, bgr, 0, image.getWidth() * image.getHeight() * multiplier);\n }\n\n /**\n * Export the original image and the result image, concatenated, for demo\n * purpose.\n *\n * @param leftImage the image to be displayed on the left side of the output\n * image\n * @param rightImage the image to be displayed on the right side of the\n * output image\n * @param outputPath the path where to output the image\n * @param fileType the file type/extension for the export\n * @param bkgColor the color used for the background between the images\n */\n public static void exportTwoImages(BufferedImage leftImage, BufferedImage rightImage, String outputPath, String fileType, Color bkgColor) {\n // inform the user if the images are different\n if ((leftImage.getWidth() != rightImage.getWidth()) || (leftImage.getHeight() != rightImage.getHeight())) {\n LOG.info(\"The width or height of the exported images differs! left: {}x{}, right: {}x{}\",\n leftImage.getWidth(), leftImage.getHeight(), rightImage.getWidth(), rightImage.getHeight());\n }\n\n // compute the size of the result image, adding also some space between them\n int width = leftImage.getWidth() + 50 + rightImage.getWidth(); // 50 represents the inset between the images\n int height = Math.max(leftImage.getHeight(), rightImage.getHeight());\n\n // generate a new image composed of proposed images\n BufferedImage resultImg = new BufferedImage(width, height, leftImage.getType());\n Graphics2D g2DResImg = (Graphics2D) resultImg.getGraphics();\n\n g2DResImg.setColor(bkgColor);\n g2DResImg.fillRect(0, 0, width, height);\n\n // put the left image\n g2DResImg.drawImage(leftImage, 0, 0, leftImage.getWidth(), leftImage.getHeight(), null);\n\n // add the right image\n g2DResImg.drawImage(rightImage,\n resultImg.getWidth() - rightImage.getWidth() - 1,\n 0, rightImage.getWidth(), rightImage.getHeight(), null);\n\n g2DResImg.dispose();\n\n // export the image\n ExportImage.exportImage(resultImg, outputPath, fileType);\n }\n\n /**\n * Searches the list of radio buttons of the given button group, for the\n * specified text. When found, the radio button is selected.\n *\n * @param group the group being searched\n * @param text the text being searched\n */\n public static void selectRadioButton(ButtonGroup group, String text) {\n // get the list of elements of the button group\n Enumeration<AbstractButton> elements = group.getElements();\n\n // search in the button group for the user selected value\n while (elements.hasMoreElements()) {\n AbstractButton button = elements.nextElement();\n\n // if the selected value is found, select the corresponding radio button\n if (button.getActionCommand().equals(text)) {\n group.setSelected(button.getModel(), true);\n break;\n }\n }\n }\n\n /**\n * Allow the user to choose a path where to save its files and set it in the\n * path text field.\n *\n * @param currentDirectory the directory where the browser should open\n * @param parent the parent frame/dialog of the browser dialog\n * @return the path selected by the user\n */\n public static String browseFilePath(String currentDirectory, Component parent) {\n String selectedPath = \"\";\n\n JFileChooser chooser = new JFileChooser();\n\n // set the initial directory\n chooser.setCurrentDirectory(new File(currentDirectory));\n\n // allow only the choosing of directories\n chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);\n\n if (chooser.showOpenDialog(parent) == JFileChooser.APPROVE_OPTION) {\n // set the chosen text as the path where to save the file\n try {\n selectedPath = chooser.getSelectedFile().getCanonicalPath();\n } catch (IOException ex) {\n java.util.logging.Logger.getLogger(ExportImagesGUI.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n\n return selectedPath;\n }\n\n /**\n * Check if the sent text equals to the predefined invalid attribute. When\n * this is true, it means the attribute was not correctly chosen.\n *\n * @param text the text where to append the invalid attribute\n * @param attribute the attribute to be checked\n * @param attributeName the name of the attribute being checked\n */\n public static void checkAttributeValid(StringBuilder text, String attribute, String attributeName) {\n if (Constants.INVALID_ATTRIBUTE_TEXT.equalsIgnoreCase(attribute)) {\n text.append(attributeName);\n text.append(\", \");\n }\n }\n\n /**\n * Asks the user to correct the attributes. If the user chooses to correct\n * them, the application does not continue with the saving of data; it will\n * cancel the process and go back to the normal state.\n *\n * @param invalidAttribute a string with the invalid attributes (is any)\n * @param editAttribAvailable true if the edit of attributes is allowed\n * @param parent the parent component of the message window\n * @return the choice of the user, whether he wants to save the data as it\n * is or the saving of data shall not be done yet, because the user wants to\n * correct it (or the attributes)\n */\n public static int messageAttributesSet(String invalidAttribute, boolean editAttribAvailable, Component parent) {\n // if the application is running offline, show the path to the attributes\n String attributesPathMsg = editAttribAvailable ? \"If you do not find the wanted attributes, please go to Menu->Options->Attributes<br>\"\n + \"and define the missing attributes!<br><br>\" : \"\";\n\n // ask the user to correct the missing attributes\n String message = \"<html>There are invalid attributes (or attributes which were not yet set):<br>\"\n + invalidAttribute.toLowerCase(Locale.ENGLISH) + \".<br><br>\"\n + \"<font color=#4d0000>\"\n + \"<b>Do you want to correct them now?</b><br>\"\n + \"</font>\"\n + \"<i>(If you choose No, the current attributes will be saved as ground truth)<br>\"\n + attributesPathMsg\n + \"</i></html>\";\n\n // display the warning dialog\n if (editAttribAvailable) {\n Object[] options = {\"Yes\", \"No\", \"Edit Attributes\"};\n return Messages.showQuestionMessage(parent, message, \"Invalid attributes!!!\", JOptionPane.YES_NO_CANCEL_OPTION, options, options[0]);\n } else {\n Object[] options = {\"Yes\", \"No\"};\n return Messages.showQuestionMessage(parent, message, \"Invalid attributes!!!\", JOptionPane.YES_NO_OPTION, options, options[0]);\n }\n }\n\n /**\n * Opens the folder or file from the specified path, in an explorer window\n * or in a default file specific application.\n *\n * @param path the path to the wanted folder/file\n */\n public static void openFileFolderInExplorer(String path) {\n try {\n if (new File(path).exists()) {\n Desktop.getDesktop().open(new File(path));\n }\n } catch (IOException e) {\n LOG.debug(\"The open file/folder in explorer failed!\");\n LOG.debug(\"The open file/folder in explorer failed! {}\", e);\n }\n }\n\n /**\n * Check if the point is inside the bounds.\n *\n * @param point the point to be checked if it is inside the bounds\n * @param bounds the max values that the point's x and y can have\n * @return return true if the point is inside the bounds or false otherwise\n */\n public static boolean checkBounds(Point point, Dimension bounds) {\n return (point.x >= 0 && point.x < bounds.width)\n && point.y >= 0 && point.y < bounds.height;\n }\n\n /**\n * Clone the input tree; create a new tree, which is the copy of the input\n * one.\n *\n * @param rootNode the root node of the tree to be copied\n * @return a new tree, with new nodes, which represent the deep copy of the\n * input tree\n */\n public static CustomTreeNode cloneTree(CustomTreeNode rootNode) {\n // the list of nodes of the input tree\n List<CustomTreeNode> nodesList = new ArrayList<>();\n // the list of nodes of the cloned tree\n List<CustomTreeNode> clonedList = new ArrayList<>();\n // the new tree, representing the deep copy of the input one\n CustomTreeNode clonedTree = new CustomTreeNode(rootNode.getRoot());\n\n // in the nodes list, add the first nodes\n nodesList.add(rootNode);\n clonedList.add(clonedTree);\n\n // keep track of the size of the list of nodes\n int listLength = nodesList.size();\n\n // take every node and create copies of the children node\n for (int index = 0; index < listLength; index++) {\n CustomTreeNode node = nodesList.get(index);\n // add the list of children to the list of nodes to be copied\n List<CustomTreeNode> children = node.getChildrenNodes();\n nodesList.addAll(children);\n // by adding new chi\n listLength += children.size();\n\n // create new nodes, based on the children of the current node\n clonedList.get(index).addChildrenStr(node.getChildren());\n clonedList.addAll(clonedList.get(index).getChildrenNodes());\n }\n\n return clonedTree;\n }\n\n /**\n * Check if a string is numeric.\n *\n * @param str the string to be checked\n * @return true if the string contains just number specific characters:\n * 0...9 , -\n */\n public static boolean isNumeric(String str) {\n return str.matches(\"-?\\\\d+(\\\\.\\\\d+)?\"); //match a number with optional '-' and decimal.\n }\n\n /**\n * Compute the distance from the point P to the line defined by the points A\n * and B.\n *\n * https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line\n *\n * @param a the point A of the line\n * @param b the point B of the line\n * @param p the point from where the distance is computed\n * @return\n */\n public static float distPointToLine(Point a, Point b, Point p) {\n float nominator = (b.y - a.y) * p.x - (b.x - a.x) * p.y + b.x * a.y - b.y * a.x;\n float denominator = (b.y - a.y) * (b.y - a.y) + (b.x - a.x) * (b.x - a.x);\n\n return (float) (Math.abs(nominator) / Math.sqrt(denominator));\n\n }\n\n /**\n * In analytic geometry, the distance between two points of the xy-plane can\n * be found using the distance formula. The distance between (x1, y1) and\n * (x2, y2) is given by:\n *\n * d = sqrt((Δx)^2 + (Δy)^2) = sqrt((x2 − x1)^2 + (y2 − y1)^2)\n *\n * @param a the point A of the segment\n * @param b the point B of the segment\n * @return The length of the segment formed by the two points, A and B.\n */\n public static float distPointToPoint(Point a, Point b) {\n return (float) Math.sqrt((b.y - a.y) * (b.y - a.y) + (b.x - a.x) * (b.x - a.x));\n }\n\n /**\n *\n * @param a the point A of the triangle\n * @param b the point B of the triangle\n * @param v the point V of the triangle\n * @return\n */\n public static float distPointToSegment(Point a, Point b, Point v) {\n float distVA = distPointToPoint(a, v);\n float distVB = distPointToPoint(b, v);\n float distAB = distPointToPoint(a, b);\n\n return ((distVA + distVB) / distAB);\n\n }\n\n /**\n * Create a deep copy of the polygon.\n *\n * @param poly the polygon to be replicated\n * @return a new polygon, copy of the initial one\n */\n public static Polygon deepCopyPoly(Polygon poly) {\n return new Polygon(poly.xpoints, poly.ypoints, poly.npoints);\n }\n\n /**\n * Open and decode a binary greyscale image. The file shall contain just the\n * bytes of the image.\n *\n * @param chosenFileName the name of the file to be opened\n * @param width the width of the image\n * @param height the height of the image\n * @return the image from the specified file\n */\n public static BufferedImage getBinaryByteImage(String chosenFileName, int width, int height) {\n int value, x, y, pos = 0;\n // create the image\n BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);\n\n try (DataInputStream in = new DataInputStream(new FileInputStream(chosenFileName))) {\n while (in.available() > 0) {\n // read the image byte by byte\n value = in.readByte();\n \n // the data is uint8\n if (value < 0) {\n value += 255;\n }\n // compute the position in the image\n y = pos / width;\n x = pos % width;\n bi.setRGB(x, y, new Color(value, value, value).getRGB());\n \n pos++;\n }\n } catch (IOException ex) {\n java.util.logging.Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);\n }\n\n return bi;\n }\n}", "public class CustomTreeNode<T extends Serializable> implements Serializable {\n\n /**\n * Serial class version in form of MAJOR_MINOR_BUGFIX_DAY_MONTH_YEAR\n */\n private static final long serialVersionUID = 0x00_03_01_11_09_2017L;\n\n /**\n * The data saved in the root of the node.\n */\n private T root;\n\n /**\n * The parent tree of the current node.\n */\n private CustomTreeNode parent;\n\n /**\n * The children of the node.\n */\n private List<CustomTreeNode> children;\n\n /**\n * Create a new node or a new tree.\n *\n * @param root the data saved in the root of the node\n */\n public CustomTreeNode(T root) {\n this.root = root;\n this.children = new LinkedList<>();\n }\n\n /**\n * Return the data saved in the current node.\n *\n * @return the data saved in the root of the node\n */\n public T getRoot() {\n return root;\n }\n\n /**\n * Set the data of the current node.\n *\n * @param root the new data of the current node\n */\n public void setRoot(T root) {\n this.root = root;\n }\n\n /**\n * Get the parent of the current node.\n *\n * @return the parent node of the current one\n */\n public CustomTreeNode getParent() {\n return parent;\n }\n\n /**\n * Set the parent of the current node.\n *\n * @param parent the parent node of the current one\n */\n private void setParent(CustomTreeNode parent) {\n this.parent = parent;\n }\n\n /**\n * Add a child to the current node.\n *\n * @param child the data saved in the root of the child node\n * @return the newly created child\n */\n public CustomTreeNode addChild(T child) {\n CustomTreeNode childNode = new CustomTreeNode(child);\n childNode.parent = this;\n this.children.add(childNode);\n\n return childNode;\n }\n\n /**\n * Add a child to the current node.\n *\n * @param child the child node to be added to the current one\n */\n public void addChild(CustomTreeNode child) {\n child.setParent(this);\n this.children.add(child);\n }\n\n /**\n * Add a list of children nodes to the current node.\n *\n * @param children the list of children nodes to be added to the current one\n */\n public void addChildren(List<CustomTreeNode> children) {\n for (CustomTreeNode child : children) {\n child.setParent(this);\n }\n this.children.addAll(children);\n }\n\n /**\n * Add a list of strings as children of the current node.\n *\n * @param children the list of children strings to be added to the current\n * one (the nodes are created based on the list of input strings)\n */\n public void addChildrenStr(List<T> children) {\n for (T child : children) {\n addChild(child);\n }\n }\n\n /**\n * Return the child node with the given root name.\n *\n * @param rootName the data saved in the root of the searched node\n * @return the child node of the current one, containing the given root node\n */\n public CustomTreeNode getChild(T rootName) {\n for (CustomTreeNode child : children) {\n if (rootName.equals(child.getRoot())) {\n return child;\n }\n }\n return null;\n }\n\n /**\n * Return the child node with the given root name.\n *\n * @param rootName the string saved in the root of the searched node\n * @return the child node of the current one, containing the given root node\n */\n public CustomTreeNode getChild(String rootName) {\n for (CustomTreeNode child : children) {\n if (rootName.equalsIgnoreCase(child.getRoot().toString())) {\n return child;\n }\n }\n return null;\n }\n\n /**\n * Build a list of children, containing just the data from the nodes.\n *\n * @return a list containing the data of all children nodes\n */\n public List<T> getChildren() {\n List<T> childrenList = new ArrayList<>();\n\n children.stream().forEach(child -> childrenList.add((T) child.root));\n\n return childrenList;\n }\n\n /**\n * Build a list of children nodes.\n *\n * @return a list containing the children nodes\n */\n public List<CustomTreeNode<T>> getChildrenNodes() {\n List<CustomTreeNode<T>> childrenList = new ArrayList<>();\n\n children.stream().forEach(child -> childrenList.add(child));\n\n return childrenList;\n }\n\n /**\n * Remove the specified child.\n *\n * @param child the child node to be removed\n */\n public void removeChild(CustomTreeNode child) {\n children.remove(child);\n }\n\n /**\n * Remove all the children of the current node.\n */\n public void removeAllChildren() {\n children = new LinkedList();\n }\n\n /**\n * Check the list of children and return the index of the wanted child.\n *\n * @param child the child for which the index is wanted\n * @return the index of the child, in the list of children of the current\n * node\n */\n public int getIndexOfChild(CustomTreeNode child) {\n return children.indexOf(child);\n }\n\n /**\n * Returns the child from the specified index, from the list of children of\n * the current node.\n *\n * @param index the index of the wanted child\n * @return a node representing the child of the current node, with the\n * specified index\n */\n public CustomTreeNode getChildAt(int index) {\n return children.get(index);\n }\n\n /**\n * Get the number of children of the current node.\n *\n * @return the number of children of the current node\n */\n public int getChildCount() {\n return children.size();\n }\n\n /**\n * Check if the current node is final / leaf.\n *\n * @return true if the current nod is final / has no children; false\n * otherwise\n */\n public boolean isLeaf() {\n return (children.isEmpty());\n }\n\n /**\n * Returns the path from the root to this node. The last element in the path\n * is the current node and the first one is the root of the tree.\n *\n * @return an object array of CustomTreeNode objects specifying the path\n * from the root node to the current node (where the first element in the\n * path is the tree root and the last element is the current node)\n */\n public Object[] getPath() {\n List path = new ArrayList();\n // add the current node\n path.add(this);\n\n // add all the other nodes, till the tree root\n CustomTreeNode father = getParent();\n while (father != null) {\n path.add(father);\n father = father.getParent();\n }\n\n // reverse the list because the tree node has to be first and the current node, last\n Collections.reverse(path);\n\n return path.toArray();\n }\n\n /**\n * Returns the path from the root to this node. The last element in the path\n * is the current node and the first one is the root of the tree.\n *\n * @return the TreePath from the tree root to the current node\n */\n public TreePath getTreePath() {\n return new TreePath(getPath());\n }\n\n @Override\n public String toString() {\n return root.toString();\n }\n}", "public abstract class Objects {\n\n /**\n * The object id in the video - used to track the object in the video\n * (constant for several frames).\n */\n private long objectId;\n\n /**\n * The type of segmentation used: bounding box, scribble etc.\n *\n */\n private String segmentationType;\n\n /**\n * The segmentation source: manual, automatic.\n */\n protected String segmentationSource;\n\n /**\n * The type of segmented object.\n */\n private String objType;\n\n /**\n * The class of segmented object.\n */\n private String objClass;\n\n /**\n * The value of segmented object.\n */\n private String objValue;\n\n /**\n * Shows if the object is occluded or not.\n */\n private String occluded;\n\n /**\n * The color of the displayed object.\n */\n private Color color;\n\n /**\n * The outer bounding box containing all the crops - panel coordinates.\n */\n protected Rectangle outerBBox;\n\n /**\n * The predicted coordinates of the object in the next frame.\n */\n private volatile Rectangle predictedBBox;\n /**\n * The predicted coordinates of the object in the next frame using HOG\n * features.\n */\n private volatile Rectangle hogPredictedBBox;\n /**\n * The predicted coordinates of the object in the next frame using HOG\n * features and openCV SVM.\n */\n private volatile Rectangle svmPredictedBBox;\n\n /**\n * The prediction is valid and can be used.\n */\n private final AtomicBoolean validPrediction;\n\n /**\n * The list of timings needed to complete the segmentation of the object.\n */\n protected List<Timings> labelingDuration;\n\n /**\n * Local user preferences.\n */\n private ObjectPreferences userPreference;\n\n\n /**\n * The thread on which the tracker is running.\n */\n private Thread trackerThread;\n\n /**\n * Create an instance of the Objects class.\n */\n public Objects() {\n this.labelingDuration = new ArrayList<>();\n this.predictedBBox = new Rectangle(0, 0, 0, 0);\n this.hogPredictedBBox = new Rectangle(0, 0, 0, 0);\n this.svmPredictedBBox = new Rectangle(0, 0, 0, 0);\n this.userPreference = new ObjectPreferences();\n this.validPrediction = new AtomicBoolean(false);\n \n // avoid null pointer in the object attributes\n this.objType = \"\";\n this.objClass = \"\";\n this.objValue = \"\";\n this.occluded = \"\";\n }\n\n /**\n * Gets the user preferences for the current object\n *\n * @return user preferences\n */\n public ObjectPreferences getUserPreference() {\n return userPreference;\n }\n\n /**\n * Sets the user preferences for the current object\n *\n * @param userPreference user preferences\n */\n public void setUserPreference(ObjectPreferences userPreference) {\n this.userPreference = userPreference;\n }\n\n /**\n * Returns the id of the object.\n *\n * @return - Returns the id of the object.\n */\n public long getObjectId() {\n return objectId;\n }\n\n /**\n * Sets the id of the object.\n *\n * @param objectId - the id of the object\n */\n public void setObjectId(long objectId) {\n this.objectId = objectId;\n }\n\n /**\n * Returns the type of object: bounding box, scribble, 3D bounding box.\n *\n * @return - the type of object\n */\n public String getSegmentationType() {\n return segmentationType;\n }\n\n /**\n * Sets the type of object: bounding box, scribble, 3D bounding box.\n *\n * @param segmentationType - the type of object\n */\n public void setSegmentationType(String segmentationType) {\n this.segmentationType = segmentationType;\n }\n\n /**\n * Returns the type of segmentation used for the current object: manual,\n * automatic etc.\n *\n * @return - the type of segmentation used for the current object\n */\n public String getSegmentationSource() {\n return segmentationSource;\n }\n\n /**\n * Sets the type of segmentation used for the object.\n *\n * @param segmentationSource - the segmentation used for the object: manual, automatic etc.\n */\n public void setSegmentationSource(String segmentationSource) {\n this.segmentationSource = segmentationSource;\n }\n\n /**\n * Set the type of the object which is being labeled.\n *\n * @param objectType - the name of the object type\n */\n public void setObjectType(String objectType) {\n this.objType = objectType;\n }\n\n /**\n * Return the name of the type of object being labeled.\n *\n * @return - the name of the object type\n */\n public String getObjectType() {\n return this.objType;\n }\n\n /**\n * Set the class of the object which is being labeled.\n *\n * @param objectClass - the name of the object class\n */\n public void setObjectClass(String objectClass) {\n this.objClass = objectClass;\n }\n\n /**\n * Return the name of the class of object being labeled.\n *\n * @return - the name of the object class\n */\n public String getObjectClass() {\n return this.objClass;\n }\n\n /**\n * Set the value of the object which is being labeled.\n *\n * @param objectValue - the name of the object value\n */\n public void setObjectValue(String objectValue) {\n this.objValue = objectValue;\n }\n\n /**\n * Return the name of the value of object being labeled.\n *\n * @return - the name of the object value\n */\n public String getObjectValue() {\n return objValue;\n }\n\n /**\n * Return the occlusion characteristic of the object. It will be defined\n * with the customer every time.\n *\n * @return - the string defining if the object is occluded or not\n */\n public String getOccluded() {\n return occluded;\n }\n\n /**\n * Set the occlusion of the object.\n *\n * @param occluded - the string defining if the object is occluded or not\n */\n public void setOccluded(String occluded) {\n this.occluded = occluded;\n }\n\n /**\n * Returns the color used to draw the object.\n *\n * @return Returns the color used to draw the object.\n */\n public Color getColor() {\n return color;\n }\n\n /**\n * Sets the color of the object.\n *\n * @param color - the color of the object\n */\n public void setColor(Color color) {\n this.color = color;\n }\n\n /**\n * Returns the rectangle which limits the entire object, the outer bounds of\n * the object - image coordinates.\n *\n * @return - the rectangle containing the object\n */\n public Rectangle getOuterBBox() {\n return outerBBox;\n }\n\n /**\n * Return the openCV predicted bounding box.\n *\n * @return the predicted position of the object in the next frame\n */\n public Rectangle getPredictedBBox() {\n return predictedBBox;\n }\n\n /**\n * Return the position of the object in the next frame, based on HOG\n * features template matching.\n *\n * @return - the position of the object in the next frame\n */\n public Rectangle getHogPredictedBBox() {\n return hogPredictedBBox;\n }\n\n /**\n * Set the position of the object in the next frame. The prediction is done\n * based on matching of HOG features.\n *\n * @param hogPredictedBBox - the position of the object in the next frame\n */\n public void setHogPredictedBBox(Rectangle hogPredictedBBox) {\n this.hogPredictedBBox = hogPredictedBBox;\n }\n\n /**\n * Return the position of the object in the next frame, based on openCV SVM\n * with HOG features.\n *\n * @return - the position of the object in the next frame\n */\n public synchronized Rectangle getSvmPredictedBBox() {\n return svmPredictedBBox;\n }\n\n /**\n * Set the position of the object in the next frame. The prediction is done\n * based on openCV SVM with HOG features.\n *\n * @param svmPredictedBBox - the position of the object in the next frame\n */\n public synchronized void setSvmPredictedBBox(Rectangle svmPredictedBBox) {\n this.svmPredictedBBox = svmPredictedBBox;\n }\n\n /**\n * Compares if the given rectangle is the same with the outer box of the\n * object; it checks if there is overlapping.\n *\n * @param rectCompare - the bounding box which will be checked for overlapping\n * @return - true if the bounding boxes overlap and false otherwise\n */\n public boolean isEqualOuterBBox(Rectangle rectCompare) {\n return outerBBox.equals(rectCompare);\n }\n\n /**\n * Creates a new timings object to save the time needed for the object.\n * (position 0 is the segmentation time and all the others are edit times)\n *\n * @return - the last created timing, where to map the duration of the current action (new object, edit)\n */\n public Timings newLabelingDuration() {\n Timings times = new Timings();\n this.labelingDuration.add(times);\n return labelingDuration.get(labelingDuration.size() - 1);\n }\n\n /**\n * *Return the current timer of the object, which is always the last one.\n *\n * @return - the current timer for the object\n */\n public Timings getCurrentLabelingDuration() {\n return labelingDuration.get(labelingDuration.size() - 1);\n }\n\n /**\n * Returns the list of labeling durations for the object. The first entry is\n * the labeling time and the others are coming from the edit mode.\n *\n * @return - the list of times needed for the segmentation of the object\n */\n public String getLabelingDuration() {\n\n StringBuilder durationString = new StringBuilder();\n\n labelingDuration.forEach((times) -> {\n durationString.append(times.getNeededTime()).append(\",\");\n });\n\n // remove the last comma\n if (durationString.length() > 0) {\n durationString.setLength(durationString.length() - 1);\n return durationString.toString();\n }\n return \"\";\n }\n\n /**\n * Set the labeling duration with an existent duration.\n *\n * @param labelingDuration - the new labeling duration\n */\n public void setLabelingDuration(ArrayList<Timings> labelingDuration) {\n this.labelingDuration = labelingDuration;\n }\n\n /**\n * Return the thread on which the tracking is done.\n *\n * @return the thread on which the tracking is done\n */\n public Thread getTrackerThread() {\n return trackerThread;\n }\n\n /**\n * Return true if the prediction of the object is valid and false if not.\n *\n * @return - true if the prediction of the object is valid and false if not.\n */\n public Boolean isValidPrediction() {\n return validPrediction.get();\n }\n\n /**\n * Set the status of the prediction: true if the prediction of the object is\n * valid and false if not.\n *\n * @param validPrediction true if the prediction of the object is valid and false if not\n */\n public void setValidPrediction(Boolean validPrediction) {\n this.validPrediction.set(validPrediction);\n }\n\n /**\n * Moves the whole object, together with the components to the new location\n * specified by the parameter.\n *\n * @param newPositionImg - the new location of the object - image coordinates\n * @param frameSize the size of the original image\n */\n public void move(Point newPositionImg, Dimension frameSize) {\n int xOffset = newPositionImg.x - outerBBox.x;\n int yOffset = newPositionImg.y - outerBBox.y;\n\n move(xOffset, yOffset, outerBBox, new Resize(1.0, 1.0), frameSize);\n }\n\n /**\n * Moves the whole object, together with the components to the new location\n * specified by the parameter.\n *\n * @param newPositionPanel - the new location of the object - image coordinates\n * @param resizeRate - the resize ratio between the image and the panel\n * @param frameSize the size of the original image\n */\n public void move(Point newPositionPanel, Resize resizeRate, Dimension frameSize) {\n Point newPositionImg = resizeRate.resizedToOriginal(newPositionPanel);\n\n int xOffset = newPositionImg.x - outerBBox.x;\n int yOffset = newPositionImg.y - outerBBox.y;\n\n // the coordinates are already image, therefore the resize shall be 1.0.\n move(xOffset, yOffset, outerBBox, new Resize(1.0, 1.0), frameSize);\n }\n\n /**\n * Changes the size of the object to the new specified size (the object\n * outer box is changed!!!).\n *\n * @param newSize the new size of the box\n * @param frameSize the size of the original image\n */\n public void changeSize(Rectangle newSize, Dimension frameSize) {\n int offsetLeft = newSize.x - outerBBox.x;\n int offsetTop = newSize.y - outerBBox.y;\n int offsetRight = (newSize.x + newSize.width) - (outerBBox.x + outerBBox.width);\n int offsetBottom = (newSize.y + newSize.height) - (outerBBox.y + outerBBox.height);\n\n changeSize(offsetLeft, offsetTop, offsetRight, offsetBottom, outerBBox, new Resize(1.0, 1.0), frameSize);\n }\n\n /**\n * Save the object predicted coordinates for the next frame\n *\n * @param newPosition predicted position in the next frame\n */\n public void setPredictedCoordinates(Point newPosition) {\n predictedBBox.setLocation(newPosition.x, newPosition.y);\n }\n\n\n /**\n * Sets the rectangle which limits the entire object, the outer bounds of\n * the object.\n *\n * @param outerBBox - the rectangle containing the object\n */\n public void setOuterBBox(Rectangle outerBBox) {\n this.outerBBox = outerBBox;\n }\n\n\t/**\n * Moves one box with the specified offset and returns the new image\n * coordinates.\n *\n * @param xOffset - how much should the object move on the X axis\n * @param yOffset - how much the object should move on the Y axis\n * @param boxPosOrig - the position of the selected box in image coordinates\n * @return - the new image coordinates of the box\n */\n protected Rectangle moveBox(int xOffset, int yOffset, Rectangle boxPosOrig) {\n boxPosOrig.setLocation(boxPosOrig.x + xOffset, boxPosOrig.y + yOffset);\n\n return boxPosOrig;\n }\n\t\n /**\n * Compute the position and size of the outer bounding box containing the\n * crops of the object.\n */\n public abstract void computeOuterBBoxCurObj();\n\n /**\n * Moves the object completely in the specified direction (crops, scribbles,\n * outer box etc.).\n *\n * @param xOffset - how much should the object move on the X axis\n * @param yOffset - how much the object should move on the Y axis\n * @param coordPanelBox - the coordinates of the selected box in image coordinates\n * @param resizeRate - the resize rate between the image coordinates and the panel coordinates\n * @param frameSize the size of the original image\n */\n public abstract void move(int xOffset, int yOffset, Rectangle coordPanelBox, Resize resizeRate, Dimension frameSize);\n\n\t/**\n * Moves the object completely in the specified direction (crops, scribbles,\n * outer box etc.).\n *\n * @param xOffset - how much should the object move on the X axis\n * @param yOffset - how much the object should move on the Y axis\n * @param frameSize the size of the original image\n */\n public abstract void move(int xOffset, int yOffset, Dimension frameSize);\n\t\n /**\n * Delete the selected box. The method checkd if the box is the same as the\n * whole object. If it is true, it will not delete it. The parent function\n * is responsible for that. This method can manage only the parts of the\n * object, not the object itself.\n *\n * @param coordPanelBox - the coordinates of the selected box in image\n * @param resizeRate - the resize rate between the image coordinates and the panel coordinates\n * @return - true if one of the boxes was erased and false if the whole object shall be erased from outside.\n */\n public abstract boolean remove(Rectangle coordPanelBox, Resize resizeRate);\n\n /**\n * Changes the size of the object in each of the directions, with the amount\n * of specified pixels.\n *\n * @param left - how much should the object be modified on the left side\n * @param top - how much should the object be modified on the top part\n * @param right - how much should the object be modified on the right side\n * @param bottom - how much should the object be modified on the bottom part\n * @param coordPanelBox - the coordinates of the selected box in image coordinates\n * @param resizeRate - the resize rate between the image coordinates and the panel coordinates\n * @param frameSize the size of the original image\n */\n public abstract void changeSize(int left, int top, int right, int bottom, Rectangle coordPanelBox, Resize resizeRate, Dimension frameSize);\n\n /**\n * Verifies if the object contains the given bounding box (as a crop or as\n * the objects outer box).\n *\n * @param coordPanelBox - the coordinates of the box in panel coordinates\n * @param resizeRate - the resize ratio between the image and the panel\n * @return - true if the object contains it; false if not\n */\n public abstract boolean contains(Rectangle coordPanelBox, Resize resizeRate);\n}", "public class BoxLRTB {\n\n /*\n * top\n * ____________________\n * | |\n * | |\n * left | | right\n * | |\n * |____________________|\n * bottom\n */\n /**\n * The left coordinate of the box.\n */\n private int xLeft;\n\n /**\n * The right coordinate of the box.\n */\n private int xRight;\n\n /**\n * The top coordinate of the box.\n */\n private int yTop;\n\n /**\n * The bottom coordinate of the box.\n */\n private int yBottom;\n\n /**\n * Instantiates a new Box lrtb.\n *\n * @param value the value\n */\n public BoxLRTB(int value) {\n this.xLeft = value;\n this.xRight = value;\n this.yTop = value;\n this.yBottom = value;\n }\n\n /**\n * Instantiates a new Box lrtb.\n *\n * @param widthBorder the width border\n * @param heightBorder the height border\n */\n public BoxLRTB(int widthBorder, int heightBorder) {\n this.xLeft = widthBorder;\n this.xRight = widthBorder;\n this.yTop = heightBorder;\n this.yBottom = heightBorder;\n }\n\n /**\n * Gets left.\n *\n * @return the left\n */\n public int getxLeft() {\n return xLeft;\n }\n\n /**\n * Sets left.\n *\n * @param xLeft the x left\n */\n public void setxLeft(int xLeft) {\n this.xLeft = xLeft;\n }\n\n /**\n * Gets right.\n *\n * @return the right\n */\n public int getxRight() {\n return xRight;\n }\n\n /**\n * Sets right.\n *\n * @param xRight the x right\n */\n public void setxRight(int xRight) {\n this.xRight = xRight;\n }\n\n /**\n * Gets top.\n *\n * @return the top\n */\n public int getyTop() {\n return yTop;\n }\n\n /**\n * Sets top.\n *\n * @param yTop the y top\n */\n public void setyTop(int yTop) {\n this.yTop = yTop;\n }\n\n /**\n * Gets bottom.\n *\n * @return the bottom\n */\n public int getyBottom() {\n return yBottom;\n }\n\n /**\n * Sets bottom.\n *\n * @param yBottom the y bottom\n */\n public void setyBottom(int yBottom) {\n this.yBottom = yBottom;\n }\n\n}", "public class ObservedActions {\n\n /**\n * The enum Action.\n */\n public enum Action {\n /**\n * Do nothing.\n */\n DO_NOTHING,\n /**\n * A notification saying that a new crop was drawn and it has to be\n * displayed\n */\n OPEN_CROP_SEGMENTATION,\n /**\n * A bounding box was drawn and an window with the preview has to pop up\n * for further checks and attributes choosing.\n */\n OPEN_BBOX_SEGMENTATION,\n /**\n * A polygon was drawn and an window with the preview has to pop up for\n * further checks and attributes choosing.\n */\n OPEN_POLYGON_SEGMENTATION,\n /**\n * The attributes of the bounding box were chosen and the object has to\n * be saved in the object list.\n */\n SAVE_BOUNDING_BOX,\n /**\n * A new crop was segmented, which belongs to an object. Add it to the\n * parent object.\n */\n ADD_CROP_TO_OBJECT,\n /**\n * Notify that an object was saved and it has to be displayed on the\n * panel of the application.\n */\n ADD_OBJECT_ON_PANEL,\n /**\n * The segmentation for the opened crop was done and the result image is\n * available. Refresh the display in order to have the latest image.\n */\n REFRESH_CROP_RESULT,\n /**\n * The number of the frame changed, refresh the display.\n */\n REFRESH_FRAME_NO,\n /**\n * The size of the brush changed. Refresh the display.\n */\n REFRESH_BRUSH_SIZE,\n /**\n * An object has been removed from the list of objects; remove it from\n * the objects list as well.\n */\n REFRESH_OBJ_LIST_PANEL,\n /**\n * Remove the key event dispatcher because another one has to be used.\n */\n REMOVE_GUI_KEY_EVENT_DISPATCHER,\n /**\n * Remove the object, one crop of the object or the bounding box object.\n */\n REMOVE_SELECTED_OBJECT,\n /**\n * A crop was selected for edit. Notify in order to open a window and\n * edit the crop.\n */\n EDIT_OBJECT_ACTION,\n /**\n * A bounding box object is/was in edit mode and has to be saved.\n */\n UPDATE_BOUNDING_BOX,\n /**\n * A complete scribble object is/was in edit mode and it has to be\n * saved.\n */\n UPDATE_OBJECT_SCRIBBLE,\n /**\n * A crop was edited and now it has to be updated inside the parent\n * object.\n */\n UPDATE_CROP_OF_OBJECT,\n /**\n * A polygon object was edited and now it has to be updated.\n */\n UPDATE_POLYGON,\n /**\n * Add the key event dispatcher.\n */\n ADD_GUI_KEY_EVENT_DISPATCHER,\n /**\n * An object which is under edit mode moved and the operation has to be\n * reflected in the GUI.\n */\n SELECTED_OBJECT_MOVED,\n /**\n * One object was selected and now it is dragged/moved.\n */\n MOVE_OBJECT_DRAG,\n /**\n * An object was selected and the corresponding button on the interface\n * has to be highlighted.\n */\n HIGHLIGHT_OBJECT,\n /**\n * A frame was loaded from the database and its annotations have to be\n * displayed on the gui.\n */\n LOAD_FRAME_ANNOTATION,\n /**\n * Notify that the current object was cancel.\n */\n CANCEL_CURRENT_OBJECT,\n /**\n * Shows that the output object map shall be further filter because\n * there are outliers.\n */\n FILTER_OBJECT_MAP,\n /**\n * The Ctrl + mouse released event happened. Choose how to treat it.\n */\n CTRL_MOUSE_EVENT,\n /**\n * Refresh the application with the current configuration.\n */\n REFRESH_DISPLAY,\n /**\n * There were some changes and the panels should be updated; show/hide\n * some panels based on the existence of a scribble object in the list.\n */\n REFRESH_PANEL_OPTIONS,\n /**\n * The object has to be saved and sent to the ground truth manager.\n */\n SAVE_LABEL,\n /**\n * The object or frame attributes were changed. Reload them.\n */\n RELOAD_ATTRIBUTES,\n /**\n * The user wants to see a preview of the application with another DPI\n * value.\n */\n REFRESH_APPLICATION_VIEW,\n /**\n * The window for the edit of attributes should be shown.\n */\n DISPLAY_EDIT_ATTRIBUTES_WIN,\n /**\n * The vertices of the polygon were changed and the original object has\n * to be updated.\n */\n UPDATE_POLYGON_VERTICES\n }\n}", "public class DrawConstants {\n\n /**\n * Definition of the types of drawing the draw panel supports.\n */\n public enum DrawType {\n /**\n * Do not draw draw type.\n */\n DO_NOT_DRAW, // panel used just to show image, not to draw\n /**\n * Draw point draw type.\n */\n DRAW_POINT, // draw points on the panel\n /**\n * Draw line draw type.\n */\n DRAW_LINE, // draw lines on the panel\n /**\n * Draw bounding box draw type.\n */\n DRAW_BOUNDING_BOX, // draw bounding boxes on the panel\n /**\n * Draw scribble draw type.\n */\n DRAW_SCRIBBLE, // draw scribbles on the panel\n /**\n * Draw crop draw type.\n */\n DRAW_CROP, // crop image\n /**\n * Draw polygon draw type.\n */\n DRAW_POLYGON, // draw a polygon made of n vertices\n\t/**\n * Switch to the edit polygon mode.\n */\n EDIT_POLYGON_VERTICES,\n /**\n * The Edit mode.\n */\n EDIT_MODE // allow the user to edit the crops which were drawen at the previous step\n }\n \n /**\n * Utility classes, which are collections of static members, are not meant\n * to be instantiated. Even abstract utility classes, which can be extended,\n * should not have public constructors.\n *\n * Java adds an implicit public constructor to every class which does not\n * define at least one explicitly. Hence, at least one non-public\n * constructor should be defined.\n */\n private DrawConstants() {\n throw new IllegalStateException(\"Utility class DrawConstants! Do not instantiate!\");\n }\n\n}" ]
import gui.support.CustomTreeNode; import gui.support.Objects; import java.awt.Color; import java.awt.Dimension; import java.awt.Frame; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.util.Arrays; import java.util.List; import java.util.Observable; import library.BoxLRTB; import observers.ObservedActions; import paintpanels.DrawConstants; import common.Constants; import common.ConstantsLabeling; import common.UserPreferences; import common.Utils;
// refresh the displayed image displayImage(); // change the title of the frame setFrameTitle(); // refresh also the image on the GUI observable.notifyObservers(ObservedActions.Action.SELECTED_OBJECT_MOVED); } @Override protected void changeObjColor() { // set the color of the object objectColor = getNewObjColor(objectColor); // set the color on the drawing panel dPPreviewImg.setObjColor(objectColor); // refresh the image on the panel showImage(); // refresh the color of the object id label setObjIdColor(); } @Override protected void displayObjId() { // add the object id // set the text of the object jLObjId.setText("Object id: " + currentObject.getObjectId()); // set the color of the object id label setObjIdColor(); } @Override protected void setFrameTitle() { String title = ""; // add the size of the object (original) title += "Preview " + currentObject.getOuterBBox().width + "x" + currentObject.getOuterBBox().height; // if the work image has different size, show it in brackets (for zooming) if (!dPPreviewImg.getWorkImgSize().equals(dPPreviewImg.getOrigImgSize())) { // compute the size of the box with the zooming factor Rectangle resizedOuterBox = dPPreviewImg.getResize().resizeBox(currentObject.getOuterBBox()); // display the zoomed size title += " (" + resizedOuterBox.width + "x" + resizedOuterBox.height + ")"; } setTitle(title); } @Override protected void updateBorderValue(int value) { // get the value of the border only if it is valid // the border has to be greater than a min value value = Math.max(value, Constants.MIN_BORDER); // the border cannot be more than the distance from the box to the image border value = Math.min(value, getMaxPossibleBorder()); // set the border size borderPX = value; // save the user preference currentObject.getUserPreference().setBorderSize(borderPX); // update text field jTFBorder.setText(Integer.toString(borderPX)); // refresh the displayed image displayImage(); } /** * Compute the distances from the box to the borders and sort it. * * @return the value of the max displayable border */ protected int getMaxPossibleBorder() { // for simplicity, use a shorter name Rectangle objBox = currentObject.getOuterBBox(); // save the borders inside an array int[] maxBorder = new int[4]; // save the max border values (the distance from box to the image border) maxBorder[0] = objBox.x; maxBorder[1] = objBox.y; maxBorder[2] = frameImg.getWidth() - (objBox.x + objBox.width); maxBorder[3] = frameImg.getHeight() - (objBox.y + objBox.height); // sort the array into ascending order, according to the natural ordering of its elements Arrays.sort(maxBorder); // return the greatest value of the array return maxBorder[3]; } @Override protected final void displayImage() { displayBox = getBorderedSize(currentObject.getOuterBBox(), borderPX); displayImage(displayBox); } /** * Display the image with the segmented box. */ @Override protected void showImage() { // get the graphics of the image Graphics2D g2d = workImg.createGraphics(); // draw the outer box of the object drawObjContour(g2d); g2d.dispose();
updatePreview(workImg, DrawConstants.DrawType.DO_NOT_DRAW, currentObject.getUserPreference().getZoomingIndex());
8
corehunter/corehunter3
corehunter-services/corehunter-services-simple/src/main/java/org/corehunter/services/simple/SimpleCoreHunterRunServices.java
[ "public class CoreHunter {\n\n // defaults\n private static final int DEFAULT_MAX_TIME_WITHOUT_IMPROVEMENT = 10000;\n private static final int FAST_MAX_TIME_WITHOUT_IMPROVEMENT = 2000;\n \n // parallel tempering settings\n private static final int PT_NUM_REPLICAS = 10;\n private static final int PT_REPLICA_STEPS = 500;\n private static final double PT_MIN_TEMP = 1e-8;\n private static final double PT_MAX_TEMP = 1e-4;\n \n // execution mode\n private CoreHunterExecutionMode mode;\n \n // search listener\n private CoreHunterListener listener;\n\n // stop conditions\n private long timeLimit = -1;\n private long maxTimeWithoutImprovement = -1;\n private long maxSteps = -1;\n private long maxStepsWithoutImprovement = -1;\n \n // random number generator used to seed other generators\n private final Random seedGenerator;\n\n public CoreHunter() {\n this(CoreHunterExecutionMode.DEFAULT);\n }\n\n /**\n * Create Core Hunter facade with the specified mode.\n * <p>\n * In {@link CoreHunterExecutionMode#DEFAULT} mode, parallel tempering is applied\n * and terminated when no improvement has been made for ten seconds.\n * In {@link CoreHunterExecutionMode#FAST} mode, random descent is applied\n * and terminated when no improvement has been made for two seconds.\n * By default no absolute time limit, nor any step-based stop conditions,\n * are set in any of the two modes.\n * Stop conditions can be altered with {@link #setTimeLimit(long)},\n * {@link #setMaxTimeWithoutImprovement(long)}, {@link #setMaxSteps(long)}\n * and {@link #setMaxStepsWithoutImprovement(long)}. As soon as one or more\n * explicit stop conditions have been specified prior to execution, the default\n * maximum time without improvement will not be applied.\n * <p>\n * In case of a multi-objective configuration with normalization enabled, a preliminary\n * random descent search is executed per objective to determine suitable normalization ranges\n * based on the Pareto minima/maxima. These normalization searches are executed in parallel, with\n * the same stop conditions as used for the main search. In default mode however, any step-based\n * stop conditions are rescaled for the random descent normalization searches, since then the main\n * parallel tempering search executes 500 random descent steps within each replica, in a single step\n * of the main search.\n * \n * @param mode execution mode\n */\n public CoreHunter(CoreHunterExecutionMode mode) {\n // set execution mode\n this.mode = mode;\n // set seed generator\n seedGenerator = new Random();\n }\n\n /**\n * Determine normalization ranges of all objectives in a multi-objective configuration, based on the\n * Pareto minima/maxima. Executes a random descent search per objective (in parallel).\n * For a single-objective setting, or when <code>normalize</code> is set to <code>false</code> in the\n * given <code>arguments</code>, an exception is thrown.\n * \n * @param arguments Core Hunter arguments specifying dataset, core size and objectives\n * @return List with normalization ranges of all objectives, in the same order as the objectives\n * @throws IllegalArgumentException If normalization is disabled in the arguments or in case of a\n * single-objective configuration.\n */\n public List<Range<Double>> normalize(CoreHunterArguments arguments){\n \n // check arguments\n if(arguments == null){\n throw new IllegalArgumentException(\"Arguments not defined!\");\n }\n CoreHunterData data = arguments.getData();\n if(data == null){\n throw new IllegalArgumentException(\"Dataset not defined!\");\n }\n if(!arguments.isNormalized()){\n throw new IllegalArgumentException(\"Normalization supposed to be disabled.\");\n }\n List<CoreHunterObjective> objectives = arguments.getObjectives();\n if(objectives == null || objectives.isEmpty()){\n throw new IllegalArgumentException(\"Objectives not defined!\");\n }\n if(objectives.size() < 2){\n throw new IllegalArgumentException(\"At least two objectives required for Pareto normalization.\");\n }\n\n // precompute seed for each normalization search to get a reproducible parallel execution\n Map<CoreHunterObjective, Long> seeds = new HashMap<>();\n objectives.stream().forEachOrdered(obj -> seeds.put(obj, seedGenerator.nextLong()));\n \n // optimize each objective separately (in parallel)\n List<SubsetSolution> bestSolutions = objectives.parallelStream().map(obj -> {\n Objective<SubsetSolution, CoreHunterData> jamesObj = createObjective(data, obj);\n // create normalization search\n Search<SubsetSolution> normSearch = createRandomDescent(arguments, jamesObj);\n // use random generator with pregenerated seed!\n normSearch.setRandom(new Random(seeds.get(obj)));\n // execute normalization search\n normSearch.run();\n // return best solution\n return normSearch.getBestSolution();\n }\n ).collect(Collectors.toList());\n \n // determine normalization ranges (based on Pareto maxima/minima)\n List<Range<Double>> ranges = new ArrayList<>();\n for(int o = 0; o < objectives.size(); o++){\n Objective<SubsetSolution, CoreHunterData> obj = createObjective(data, objectives.get(o));\n // evaluate all optimal solutions with this objective\n List<Double> allValues = bestSolutions.stream().map(\n sol -> obj.evaluate(sol, data).getValue()\n ).collect(Collectors.toList());\n // take best solution value for the considered objective\n double bestValue = allValues.get(o);\n // set bounds taking into account whether the objective is minimized or maximized\n double min, max;\n if(obj.isMinimizing()){\n // best solution value = lower bound\n min = bestValue;\n // max of all values = upper bound\n max = Collections.max(allValues);\n } else {\n // best solution value = upper bound\n max = bestValue;\n // min of all values = lower bound\n min = Collections.min(allValues);\n }\n // set range\n ranges.add(new Range<>(min, max));\n }\n return ranges;\n \n }\n \n public SubsetSolution execute(CoreHunterArguments arguments) {\n\n if (arguments == null) {\n throw new IllegalArgumentException(\"Arguments not defined!\");\n }\n\n if (arguments.getData() == null) {\n throw new IllegalArgumentException(\"Dataset not defined!\");\n }\n\n // create search from arguments\n Search<SubsetSolution> search = createMainSearch(arguments);\n \n // add search listener (if any)\n if (listener != null) {\n search.addSearchListener(listener);\n }\n\n // start search\n search.start();\n\n // dispose search\n search.dispose();\n\n return search.getBestSolution();\n }\n \n /**\n * Evaluate the given solution with the specified objective. The weight of the objective is ignored.\n * \n * @param sol subset solution\n * @param data Core Hunter data\n * @param objective objective used to evaluate the subset (weight is ignored)\n * @return value of the subset according to the specified objective\n */\n public double evaluate(SubsetSolution sol, CoreHunterData data, CoreHunterObjective objective){\n Objective<SubsetSolution, CoreHunterData> obj = createObjective(data, objective);\n return obj.evaluate(sol, data).getValue();\n }\n\n /**\n * Get execution time limit (milliseconds).\n * \n * @return time limit\n */\n public long getTimeLimit() {\n return timeLimit;\n }\n\n /**\n * Sets the absolute time limit (in milliseconds).\n * A negative value means that no time limit is imposed.\n * \n * @param ms absolute time limit in milliseconds\n */\n public void setTimeLimit(long ms) {\n this.timeLimit = ms;\n }\n \n /**\n * Get the maximum allowed time without finding an improvement (milliseconds).\n * \n * @return maximum time without improvement\n */\n public long getMaxTimeWithoutImprovement(){\n if(timeLimit < 0 && maxTimeWithoutImprovement < 0 && maxSteps < 0 && maxStepsWithoutImprovement < 0){\n // no explicit stop conditions: use default\n return mode == CoreHunterExecutionMode.DEFAULT\n ? DEFAULT_MAX_TIME_WITHOUT_IMPROVEMENT\n : FAST_MAX_TIME_WITHOUT_IMPROVEMENT;\n } else {\n // manually specified improvement time\n return maxTimeWithoutImprovement;\n }\n }\n \n /**\n * Sets the maximum time without finding any improvements (in milliseconds).\n * A negative value means that no such stop condition is set.\n * \n * @param ms maximum time without improvement in milliseconds\n */\n public void setMaxTimeWithoutImprovement(long ms){\n maxTimeWithoutImprovement = ms;\n }\n \n /**\n * Get the maximum number of search steps.\n * \n * @return search step limit\n */\n public long getMaxSteps(){\n return maxSteps;\n }\n \n /**\n * Sets the maximum number of search steps.\n * A negative value means that no such stop condition is set.\n * \n * @param steps search step limit\n */\n public void setMaxSteps(long steps){\n this.maxSteps = steps;\n }\n \n /**\n * Get the maximum allowed number of search steps without finding an improvement.\n * A negative value means that no such stop condition is set.\n * \n * @return maximum number of steps without improvement\n */\n public long getMaxStepsWithoutImprovement(){\n return maxStepsWithoutImprovement;\n }\n \n /**\n * Sets the maximum allowed number of search steps without finding an improvement.\n * \n * @param steps maximum number of steps without improvement\n */\n public void setMaxStepsWithoutImprovement(long steps){\n this.maxStepsWithoutImprovement = steps;\n }\n \n public CoreHunterListener getListener(){\n return listener;\n }\n \n public void setListener(CoreHunterListener listener){\n this.listener = listener;\n }\n \n public void setSeed(long seed){\n seedGenerator.setSeed(seed);\n }\n\n private Search<SubsetSolution> createMainSearch(CoreHunterArguments arguments) {\n\n Objective<SubsetSolution, CoreHunterData> obj = createObjective(arguments);\n\n switch(mode){\n case DEFAULT:\n return createParallelTempering(arguments, obj);\n case FAST:\n return createRandomDescent(arguments, obj);\n default:\n throw new CoreHunterException(\"Unknown execution mode \" + mode + \".\");\n }\n\n }\n\n private Search<SubsetSolution> createRandomDescent(CoreHunterArguments args,\n Objective<SubsetSolution, CoreHunterData> obj){\n LocalSearch<SubsetSolution> rd = new RandomDescent<>(createProblem(args, obj), createNeighbourhood(args));\n rd.setRandom(new Random(seedGenerator.nextLong()));\n return setStopCriteria(rd, mode == CoreHunterExecutionMode.DEFAULT);\n }\n\n private Search<SubsetSolution> createParallelTempering(CoreHunterArguments args,\n Objective<SubsetSolution, CoreHunterData> obj){\n // check running default mode\n if(mode != CoreHunterExecutionMode.DEFAULT){\n throw new CoreHunterException(\"Parallel tempering search should only be used in default mode.\");\n }\n ParallelTempering<SubsetSolution> pt = new ParallelTempering<>(\n createProblem(args, obj), createNeighbourhood(args),\n PT_NUM_REPLICAS, PT_MIN_TEMP, PT_MAX_TEMP,\n // custom Metropolis factory to set seeds\n (p, n, t) -> {\n MetropolisSearch<SubsetSolution> rep = new MetropolisSearch<>(p, n, t);\n rep.setRandom(new Random(seedGenerator.nextLong()));\n return rep;\n }\n );\n pt.setReplicaSteps(PT_REPLICA_STEPS);\n pt.setRandom(new Random(seedGenerator.nextLong()));\n return setStopCriteria(pt, false);\n }\n\n private SubsetProblem<CoreHunterData> createProblem(CoreHunterArguments args,\n Objective<SubsetSolution, CoreHunterData> obj){\n int size = args.getSubsetSize();\n SubsetProblem<CoreHunterData> problem = new SubsetProblem<>(args.getData(), obj, size);\n problem.setRandomSolutionGenerator((rnd, data) -> {\n // create subset solution containing always selected ids\n SubsetSolution sol = new SubsetSolution(data.getIDs(), args.getAlwaysSelected());\n // find remaining candidates for selection\n // (exclude both already selected and never selected ids)\n Set<Integer> candidates = new HashSet<>(sol.getUnselectedIDs());\n candidates.removeAll(args.getNeverSelected());\n // randomly select more items to obtain requested size\n sol.selectAll(SetUtilities.getRandomSubset(candidates, size - sol.getNumSelectedIDs(), rnd));\n // return random initial solution\n return sol;\n });\n return problem;\n }\n\n private Neighbourhood<SubsetSolution> createNeighbourhood(CoreHunterArguments args){\n Set<Integer> fixed = new HashSet<>();\n fixed.addAll(args.getAlwaysSelected());\n fixed.addAll(args.getNeverSelected());\n return new SingleSwapNeighbourhood(fixed);\n }\n\n private Search<SubsetSolution> setStopCriteria(Search<SubsetSolution> search, boolean rescaleSteps){\n if (getTimeLimit() > 0) {\n search.addStopCriterion(new MaxRuntime(getTimeLimit(), TimeUnit.MILLISECONDS));\n }\n if (getMaxTimeWithoutImprovement() > 0){\n search.addStopCriterion(\n new MaxTimeWithoutImprovement(getMaxTimeWithoutImprovement(), TimeUnit.MILLISECONDS)\n );\n }\n if(getMaxSteps() > 0){\n long steps = rescaleSteps ? getMaxSteps() * PT_REPLICA_STEPS : getMaxSteps();\n search.addStopCriterion(new MaxSteps(steps));\n }\n if(getMaxStepsWithoutImprovement() > 0){\n long steps = rescaleSteps\n ? getMaxStepsWithoutImprovement() * PT_REPLICA_STEPS\n : getMaxStepsWithoutImprovement();\n search.addStopCriterion(new MaxStepsWithoutImprovement(steps));\n }\n return search;\n }\n\n private Objective<SubsetSolution, CoreHunterData> createObjective(CoreHunterArguments arguments) {\n // extract data and objectives\n CoreHunterData data = arguments.getData();\n List<CoreHunterObjective> objectives = arguments.getObjectives();\n // compose objective\n if (objectives == null || objectives.isEmpty()) {\n throw new CoreHunterException(\"No objective(s) given.\");\n } else {\n if (objectives.size() == 1) {\n // single objective\n return createObjective(data, objectives.get(0));\n } else {\n // multiple objectives (weighted index)\n WeightedIndex<SubsetSolution, CoreHunterData> weightedIndex = new WeightedIndex<>();\n // create all objectives\n List<Objective<SubsetSolution, CoreHunterData>> jamesObjectives = objectives.stream()\n .map(obj -> createObjective(data, obj))\n .collect(Collectors.toList());\n // normalize if requested\n if(arguments.isNormalized()){\n jamesObjectives = normalizeObjectives(arguments, jamesObjectives);\n }\n // combine in weighted index\n for(int o = 0; o < objectives.size(); o++) {\n weightedIndex.addObjective(jamesObjectives.get(o), objectives.get(o).getWeight());\n }\n return weightedIndex;\n }\n }\n }\n\n private Objective<SubsetSolution, CoreHunterData> createObjective(CoreHunterData data,\n CoreHunterObjective coreHunterObjective) {\n\n Objective<SubsetSolution, CoreHunterData> objective = null;\n DistanceMeasure distanceMeasure = null;\n\n if (coreHunterObjective.getMeasure() != null) {\n switch (coreHunterObjective.getMeasure()) {\n case MODIFIED_ROGERS:\n if (!data.hasGenotypes()) {\n throw new CoreHunterException(\"Genotypes are required for Modified Rogers distance.\");\n }\n distanceMeasure = new ModifiedRogersDistance();\n break;\n case CAVALLI_SFORZA_EDWARDS:\n if (!data.hasGenotypes()) {\n throw new CoreHunterException(\n \"Genotypes are required for Cavalli-Sforza and Edwards distance.\"\n );\n }\n distanceMeasure = new CavalliSforzaEdwardsDistance();\n break;\n case GOWERS:\n if (!data.hasPhenotypes()) {\n throw new CoreHunterException(\"Phenotypes are required for Gower distance.\");\n }\n distanceMeasure = new GowerDistance();\n break;\n case PRECOMPUTED_DISTANCE:\n if (!data.hasDistances()) {\n throw new CoreHunterException(\"No precomputed distance matrix has been defined.\");\n }\n distanceMeasure = new PrecomputedDistance();\n break;\n default:\n // do nothing (not all objectives require a distance measure)\n }\n }\n\n switch (coreHunterObjective.getObjectiveType()) {\n case AV_ACCESSION_TO_NEAREST_ENTRY:\n if (distanceMeasure == null) {\n throw new CoreHunterException(String.format(\n \"No distance measure defined. A distance measure is required for %s\",\n CoreHunterObjectiveType.AV_ACCESSION_TO_NEAREST_ENTRY));\n }\n objective = new AverageAccessionToNearestEntry(distanceMeasure);\n break;\n case AV_ENTRY_TO_ENTRY:\n if (distanceMeasure == null) {\n throw new CoreHunterException(String.format(\n \"No distance measure defined. A distance measure is required for %s\",\n CoreHunterObjectiveType.AV_ENTRY_TO_ENTRY));\n }\n objective = new AverageEntryToEntry(distanceMeasure);\n break;\n case AV_ENTRY_TO_NEAREST_ENTRY:\n if (distanceMeasure == null) {\n throw new CoreHunterException(String.format(\n \"No distance measure defined. A distance measure is required for %s\",\n CoreHunterObjectiveType.AV_ENTRY_TO_NEAREST_ENTRY));\n }\n objective = new AverageEntryToNearestEntry(distanceMeasure);\n break;\n case COVERAGE:\n if (!data.hasGenotypes()) {\n throw new CoreHunterException(\"Genotypes are required for coverage objective.\");\n }\n objective = new Coverage();\n break;\n case HETEROZYGOUS_LOCI:\n if (!data.hasGenotypes()) {\n throw new CoreHunterException(\n \"Genotypes are required for expected proportion of heterozygous loci objective.\"\n );\n }\n objective = new HeterozygousLoci();\n break;\n case SHANNON_DIVERSITY:\n if (!data.hasGenotypes()) {\n throw new CoreHunterException(\"Genotypes are required for Shannon's index.\");\n }\n objective = new Shannon();\n break;\n default:\n throw new IllegalArgumentException(String.format(\"Unknown objective : %s\", coreHunterObjective));\n\n }\n\n return objective;\n }\n \n private List<Objective<SubsetSolution, CoreHunterData>> normalizeObjectives(\n CoreHunterArguments arguments, List<Objective<SubsetSolution, CoreHunterData>> objectives\n ){\n \n if(listener != null){\n listener.preprocessingStarted(\"Normalizing objectives.\");\n }\n \n // get normalization ranges\n List<CoreHunterObjective> chObjectives = arguments.getObjectives();\n List<Range<Double>> ranges;\n if(chObjectives.stream()\n .map(CoreHunterObjective::getNormalizationRange)\n .anyMatch(Objects::isNull)){\n // one or more objective do not have an explicit normalization range set: determine ranges\n ranges = normalize(arguments);\n // overwrite with explicit ranges where specified\n for(int o = 0; o < chObjectives.size(); o++){\n Range<Double> range = chObjectives.get(o).getNormalizationRange();\n if(range != null){\n ranges.set(o, range);\n }\n }\n } else {\n // normalization range predefined for all objectives\n ranges = chObjectives.stream().map(CoreHunterObjective::getNormalizationRange).collect(Collectors.toList());\n }\n \n // normalize objectives\n StringBuilder message = new StringBuilder();\n List<Objective<SubsetSolution, CoreHunterData>> normalizedObjectives = new ArrayList<>();\n for(int o = 0; o < objectives.size(); o++){\n Objective<SubsetSolution, CoreHunterData> obj = objectives.get(o);\n Range<Double> range = ranges.get(o);\n double min = range.getLower();\n double max = range.getUpper();\n normalizedObjectives.add(new NormalizedObjective<>(obj, min, max));\n message.append(String.format(Locale.ROOT, \"%s: [%.3f, %.3f]%n\", obj, min, max));\n }\n \n message.append(\"Finished normalization.\");\n if(listener != null){\n listener.preprocessingStopped(message.toString());\n }\n \n return normalizedObjectives;\n \n }\n \n}", "public class CoreHunterArguments {\n\n private final int subsetSize;\n private final CoreHunterData data;\n private final List<CoreHunterObjective> objectives;\n private final boolean normalize;\n private final Set<Integer> alwaysSelected;\n private final Set<Integer> neverSelected;\n \n /**\n * Creates a single objective configuration with no defined measure.\n * \n * @param data the data for the run\n * @param subsetSize the desired subset size\n * @param objective the objective type \n */\n public CoreHunterArguments(CoreHunterData data, int subsetSize, CoreHunterObjectiveType objective) {\n this(data, subsetSize, objective, null);\n }\n\n /**\n * Creates a single objective configuration.\n * \n * @param data the data for the run\n * @param subsetSize the desired subset size\n * @param objective the objective type \n * @param measure the optional measure required for the objective\n */\n public CoreHunterArguments(CoreHunterData data, int subsetSize,\n CoreHunterObjectiveType objective, CoreHunterMeasure measure) {\n this(data, subsetSize, Collections.singletonList(new CoreHunterObjective(objective, measure)));\n if (objective == null) {\n throw new IllegalArgumentException(\"Objective not defined.\");\n }\n if (measure == null) {\n throw new IllegalArgumentException(\"Measure not defined.\");\n }\n }\n \n /**\n * Creates a single- or multi-objective configuration.\n * Automatic normalization is enabled whenever more than one objective is included.\n * \n * @param data the data for the run\n * @param subsetSize the desired subset size\n * @param objectives the objectives for the run\n */\n public CoreHunterArguments(CoreHunterData data, int subsetSize, List<CoreHunterObjective> objectives) {\n this(data, subsetSize, objectives, Collections.emptySet());\n }\n\n /**\n * Creates a single- or multi-objective configuration with a set of always selected IDs.\n * Automatic normalization is enabled whenever more than one objective is included.\n *\n * @param data the data for the run\n * @param subsetSize the desired subset size\n * @param objectives the objectives for the run\n * @param alwaysSelected set of IDs that will always be selected in the core\n */\n public CoreHunterArguments(CoreHunterData data, int subsetSize,\n List<CoreHunterObjective> objectives,\n Set<Integer> alwaysSelected) {\n this(data, subsetSize, objectives, alwaysSelected, Collections.emptySet());\n }\n \n /**\n * Creates a single- or multi-objective configuration with a set of always and/or never selected IDs.\n * Automatic normalization is enabled whenever more than one objective is included.\n *\n * @param data the data for the run\n * @param subsetSize the desired subset size\n * @param objectives the objectives for the run\n * @param alwaysSelected set of IDs that will always be selected in the core\n * @param neverSelected set of IDs that will never be selected in the core\n */\n public CoreHunterArguments(CoreHunterData data, int subsetSize, List<CoreHunterObjective> objectives,\n Set<Integer> alwaysSelected, Set<Integer> neverSelected) {\n this(data, subsetSize, objectives, alwaysSelected, neverSelected, true);\n }\n \n /**\n * Creates a single- or multi-objective configuration with set of always and/or never selected IDs.\n * If <code>normalize</code> is <code>true</code> automatic normalization is enabled, but\n * only if more than one objective is included. In case of a single objective, this argument\n * is ignored.\n *\n * @param data the data for the run\n * @param subsetSize the desired subset size\n * @param objectives the objectives for the run\n * @param alwaysSelected set of IDs that will always be selected in the core\n * @param neverSelected set of IDs that will never be selected in the core\n * @param normalize indicates whether objectives should be normalized prior to execution\n */\n public CoreHunterArguments(CoreHunterData data, int subsetSize, List<CoreHunterObjective> objectives,\n Set<Integer> alwaysSelected, Set<Integer> neverSelected, boolean normalize) {\n // set data and size\n if (data == null) {\n throw new IllegalArgumentException(\"Data undefined.\");\n }\n if (subsetSize < 2) {\n throw new IllegalArgumentException(\"Requested subset size must at least be 2 or more.\");\n }\n if (subsetSize >= data.getSize()) {\n throw new IllegalArgumentException(\n String.format(\"Requested subset size must be less than total data size %d.\", data.getSize())\n );\n }\n this.data = data ;\n this.subsetSize = subsetSize ;\n // set objectives\n if (objectives == null || objectives.isEmpty()) {\n throw new IllegalArgumentException(\"Objectives not defined.\");\n }\n this.objectives = Collections.unmodifiableList(new ArrayList<>(objectives));\n // store set of always/never selected ids\n if (alwaysSelected == null) {\n throw new IllegalArgumentException(\"Set of always selected IDs can not be null.\");\n }\n if (neverSelected == null) {\n throw new IllegalArgumentException(\"Set of never selected IDs can not be null.\");\n }\n if(alwaysSelected.stream().anyMatch(neverSelected::contains)\n || neverSelected.stream().anyMatch(alwaysSelected::contains)){\n throw new IllegalArgumentException(\"Sets of always and never selected IDs should be disjoint.\");\n }\n if(alwaysSelected.size() > subsetSize){\n throw new IllegalArgumentException(\"Set of always selected IDs can not be larger than subset size.\");\n }\n if(data.getSize() - neverSelected.size() < subsetSize){\n throw new IllegalArgumentException(\"Too many never selected IDs: can not obtain requested subset size.\");\n }\n this.alwaysSelected = Collections.unmodifiableSet(new HashSet<>(alwaysSelected));\n this.neverSelected = Collections.unmodifiableSet(new HashSet<>(neverSelected));\n // set normalization flag\n this.normalize = objectives.size() > 1 && normalize;\n }\n\n public final CoreHunterData getData() {\n return data;\n }\n \n public final List<CoreHunterObjective> getObjectives() {\n return objectives;\n }\n\n public final int getSubsetSize() {\n return subsetSize;\n }\n \n public final Set getAlwaysSelected(){\n return alwaysSelected;\n }\n \n public final Set getNeverSelected(){\n return neverSelected;\n }\n \n public final boolean isNormalized(){\n return normalize;\n }\n \n}", "public class SimpleCoreHunterListener implements CoreHunterListener {\n\n private static final String DEFAULT_PREFIX = \"\";\n\n private String prefix;\n private PrintStream printStream;\n\n public SimpleCoreHunterListener() {\n this(System.err);\n }\n\n public SimpleCoreHunterListener(PrintStream printStream) {\n super();\n\n this.printStream = printStream;\n prefix = DEFAULT_PREFIX;\n }\n\n public final String getPrefix() {\n return prefix;\n }\n\n public final void setPrefix(String prefix) {\n this.prefix = prefix;\n }\n\n @Override\n public void searchStarted(Search<? extends SubsetSolution> search) {\n printStream.format(Locale.US, \"%sSearch : %s started%n\", prefix, search.getName());\n }\n\n @Override\n public void searchStopped(Search<? extends SubsetSolution> search) {\n double t = search.getRuntime() / 1000;\n long s = search.getSteps();\n printStream.format(\n Locale.US,\n \"%sSearch : %s stopped after %.1f seconds and %d steps%n\",\n prefix, search.getName(), t, s\n );\n printStream.format(\n Locale.US,\n \"%sBest solution with evaluation : %f%n\",\n prefix, search.getBestSolutionEvaluation().getValue()\n );\n printStream.format(Locale.US, \"%sBest solution with evaluation : %s%n\", prefix, search.getBestSolution());\n }\n\n @Override\n public void newBestSolution(Search<? extends SubsetSolution> search, SubsetSolution newBestSolution,\n Evaluation newBestSolutionEvaluation, Validation newBestSolutionValidation) {\n printStream.format(Locale.US, \"%sCurrent value: %f%n\", prefix, newBestSolutionEvaluation.getValue());\n }\n\n @Override\n public void preprocessingStarted(String message) {\n printStream.format(Locale.US, \"%s%s%n\", prefix, message);\n }\n\n @Override\n public void preprocessingStopped(String message) {\n printStream.format(\"%s%s%n\", prefix, message);\n }\n}", "public interface CoreHunterRun extends SimpleEntity {\n \n /**\n * Gets the start date of the run\n * @return the start date of the run\n */\n public Instant getStartInstant();\n\n /**\n * Gets the end date of the run\n * @return the end date of the run\n */\n public Instant getEndInstant();\n\n /**\n * Gets the status of the run\n * @return the status of the run\n */\n public CoreHunterRunStatus getStatus();\n}", "public interface CoreHunterRunArguments extends SimpleEntity {\n \n /** \n * Gets the required subset size for the run. The value must\n * be greater than 2 and less than the dataset size\n * \n * @return the required subset size for the run\n */\n public int getSubsetSize() ;\n\n /** \n * Gets the id of the dataset to analysed. This\n * data must be made available to the CoreHunter Run Services \n * @return the id of the dataset to analysed\n */\n public String getDatasetId();\n \n /**\n * Gets the objectives to apply this run. If no objectives \n * are defined the default objective for the \n * CoreHunter Run Services is used\n * @return the objectives to apply this run or an empty list\n */\n public List<CoreHunterObjective> getObjectives() ;\n\n /**\n * Sets the absolute time limit (in seconds).\n * A negative value means that specific no time limit is imposed\n * for this run, however the CoreHunter Run Services implementation\n * may impose such a limit\n * \n * @return seconds absolute time limit in seconds\n */\n long getTimeLimit();\n\n /**\n * Sets the maximum time without finding any improvements (in seconds).\n * A negative value means that no such stop condition is set\n * for this run, however the CoreHunter Run Services implementation\n * may impose such a limit\n * \n * @return seconds maximum time without improvement in seconds\n */\n long getMaxTimeWithoutImprovement();\n}", "public interface CoreHunterRunResult extends SimpleEntity {\n\n String getOutputStream();\n\n String getErrorStream();\n\n String getErrorMessage();\n\n SubsetSolution getSubsetSolution();\n\n Instant getStartInstant();\n\n Instant getEndInstant();\n\n CoreHunterRunStatus getStatus();\n\n CoreHunterRunArguments getArguments();\n\n}", "public interface CoreHunterRunServices {\n\n /**\n * Starts the execution of a Core Hunter run with the given arguments\n * \n * @param arguments\n * the Core Hunter Run Arguments\n * @return The initial CoreHunterRun object containing the current status,\n * arguments and unique identifier of the run\n * @throws IllegalStateException if the service is not running or shutting down\n */\n public CoreHunterRun executeCoreHunter(CoreHunterRunArguments arguments);\n\n /**\n * Gets the current information about the Core Hunter run\n * \n * @param uniqueIdentifier\n * the unique identifier of the run that was provided on\n * execution\n * @return the current information about the Core Hunter run, or\n * <code>null</code> if not such run exists.\n */\n\n public CoreHunterRun getCoreHunterRun(String uniqueIdentifier);\n\n /**\n * Removes the CoreHunterRun and tries to stop the run if it is\n * still running, If the run can not be removed, the client will need to\n * check at later time or use the {@link #deleteCoreHunterRun(String)} method\n * \n * @param uniqueIdentifier\n * the unique identifier of the run that was provided on\n * execution\n * @return <code>true</code> if the CoreHunterRun was successfully removed,\n * <code>false</code> if the run can not be removed.\n * @throws java.util.NoSuchElementException if no such run exists\n */\n public boolean removeCoreHunterRun(String uniqueIdentifier);\n\n /**\n * Deletes the CoreHunterRun and tries to stop the run if it is\n * still running, This method guarantees to be able to delete the run\n * regardless of if it can be stopped.\n * \n * @param uniqueIdentifier\n * the unique identifier of the run that was provided on\n * execution\n * @throws java.util.NoSuchElementException if no such run exists \n */\n public void deleteCoreHunterRun(String uniqueIdentifier);\n \n /**\n * Updates the CoreHunterRun. Only editable fields such as the name can be changed.\n * \n * @param coreHunterRun a CoreHunterRun run of run that was provided on\n * execution\n * @throws java.util.NoSuchElementException if no such run exists\n */\n public void updateCoreHunterRun(CoreHunterRun coreHunterRun);\n\n /**\n * Gets the current information about all Core Hunter runs\n * \n * @return the current information about all Core Hunter runs\n */\n public List<CoreHunterRun> getAllCoreHunterRuns();\n\n /**\n * Gets the current output stream provides by the run \n * \n * @param uniqueIdentifier\n * the unique identifier of the run that was provided on\n * execution\n * @return the current output stream provided by the run \n */\n public String getOutputStream(String uniqueIdentifier);\n\n /**\n * Gets the current error stream provided by the run \n * \n * @param uniqueIdentifier\n * the unique identifier of the run that was provided on\n * execution\n * @return the current error stream provided by the run \n */\n public String getErrorStream(String uniqueIdentifier);\n\n /**\n * Gets the current error message provided by the run \n * \n * @param uniqueIdentifier\n * the unique identifier of the run that was provided on\n * execution\n * @return the current error message provided by the run \n */\n public String getErrorMessage(String uniqueIdentifier);\n\n /**\n * Depending on the status the method returns the solution of the run.\n * If the run is still running the method returns the current solution,\n * if the run is finished it will return the final solution, otherwise\n * the method will return <code>null</code>.\n * \n * @param uniqueIdentifier\n * the unique identifier of the run that was provided on\n * execution\n * @return the current error message provided by the run \n */\n public SubsetSolution getSubsetSolution(String uniqueIdentifier);\n\n /**\n * Gets the arguments provided when the run was executed\n * \n * @param uniqueIdentifier\n * the unique identifier of the run that was provided on\n * execution\n * @return the arguments provided when the run was executed\n */\n CoreHunterRunArguments getArguments(String uniqueIdentifier);\n}", "public enum CoreHunterRunStatus {\n\n NOT_STARTED(\"Not Started\"), RUNNING(\"Running\"), FAILED(\"Failed\"), FINISHED(\"Finished\");\n\n private String name;\n\n private CoreHunterRunStatus(String name) {\n this.name = name;\n }\n\n public final String getName() {\n return name;\n }\n}", "public interface DatasetServices {\n\n /**\n * Gets all databases\n * \n * @return all databases\n */\n public List<Dataset> getAllDatasets();\n\n /**\n * Gets a single dataset by unique dataset identifier\n * \n * @param datasetId\n * the identifier of the dataset\n * @return a single dataset by unique dataset identifier\n */\n public Dataset getDataset(String datasetId);\n \n /**\n * Add a new dataset\n * \n * @param dataset\n * the dataset to be added\n * @throws DatasetException\n * if the dataset is invalid or is already present\n */\n public void addDataset(Dataset dataset) throws DatasetException;\n\n /**\n * Removes a dataset and all associated data\n * \n * @param datasetId\n * the identifier of the dataset to be removed\n * @return <code>true</code> if the dataset was present and was removed,\n * <code>false</code> otherwise\n * @throws DatasetException\n * if the dataset does not exist\n */\n public boolean removeDataset(String datasetId) throws DatasetException;\n \n /**\n * Updates a dataset with information in the supplied dataset, based \n * on the identifier of the dataset\n * \n * @param dataset\n * the dataset to be updated\n * @return <code>true</code> if the dataset was present and was updated,\n * (at least one field was changed) <code>false</code> otherwise.\n * @throws DatasetException\n * if the dataset does not exist or can not be updated\n */\n public boolean updateDataset(Dataset dataset) throws DatasetException;\n \n /**\n * Gets the entry headers associated with a dataset by unique dataset identifier\n * \n * @param datasetId\n * the identifier of the dataset\n * @return the entry headers associated with a dataset by unique dataset identifier\n * @throws DatasetException\n * if the data can not be accessed or the dataset does not exist\n */\n public SimpleEntity[] getHeaders(String datasetId) throws DatasetException;\n \n /**\n * Gets the CoreHunter data associated with a dataset by unique dataset identifier\n * \n * @param datasetId\n * the identifier of the dataset\n * @return the data associated with a dataset by unique dataset identifier\n * @throws DatasetException\n * if the data can not be accessed or the dataset does not exist\n */\n public CoreHunterData getCoreHunterData(String datasetId) throws DatasetException;\n \n /**\n * Loads the data and associates it with a dataset. If the dataset already\n * has data associated with it, an attempt will be made to add to the\n * dataset merging with existing data. \n * \n * <p>Data loading options can include the Genotype Data Format\n * (see {@link org.corehunter.data.GenotypeDataFormat}) for {@link CoreHunterDataType#GENOTYPIC} \n * \n * @param dataset\n * the dataset to which the data will be associated\n * @param path\n * a path where the data file can be found\n * @param fileType\n * the type of file from which the data will be loaded\n * @param dataType\n * the type of data\n * @param options\n * the data loading options. \n * @throws IOException\n * if the is an issue with reading the data from the path\n * @throws DatasetException\n * if the data can not be merged with existing data for a\n * dataset\n */\n public void loadData(Dataset dataset, Path path, FileType fileType, CoreHunterDataType dataType, \n Object... options) throws IOException, DatasetException;\n \n /**\n * Removes the all the data associated with a dataset\n * \n * @param datasetId\n * the identifier of the dataset for which all data will be removed\n * @throws DatasetException\n * if the data can not be accessed or the dataset does not exist\n */\n public void removeData(String datasetId) throws DatasetException;\n \n /**\n * Gets the original data upload by the user\n * @param datasetId\n * the identifier of the dataset\n * @param dataType\n * the type of data\n * @return the original data upload by the user\n * @throws DatasetException if the data can not be accessed or the dataset does not exist\n */\n public Data getOriginalData(String datasetId, CoreHunterDataType dataType) throws DatasetException ;\n\n}" ]
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.apache.commons.lang3.ObjectUtils; import org.corehunter.CoreHunter; import org.corehunter.CoreHunterArguments; import org.corehunter.listener.SimpleCoreHunterListener; import org.corehunter.services.CoreHunterRun; import org.corehunter.services.CoreHunterRunArguments; import org.corehunter.services.CoreHunterRunResult; import org.corehunter.services.CoreHunterRunServices; import org.corehunter.services.CoreHunterRunStatus; import org.corehunter.services.DatasetServices; import org.jamesframework.core.subset.SubsetSolution; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.XStreamException; import com.thoughtworks.xstream.io.xml.PrettyPrintWriter; import com.thoughtworks.xstream.io.xml.StaxDriver; import uno.informatics.data.pojo.SimpleEntityPojo;
/*--------------------------------------------------------------*/ /* Licensed to the Apache Software Foundation (ASF) under one */ /* or more contributor license agreements. See the NOTICE file */ /* distributed with this work for additional information */ /* regarding copyright ownership. The ASF licenses this file */ /* to you under the Apache License, Version 2.0 (the */ /* "License"); you may not use this file except in compliance */ /* with the License. You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, */ /* software distributed under the License is distributed on an */ /* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY */ /* KIND, either express or implied. See the License for the */ /* specific language governing permissions and limitations */ /* under the License. */ /*--------------------------------------------------------------*/ package org.corehunter.services.simple; /** * A simple CoreHunterRunServices implementation. Sub-classes, can use the * {@link #SimpleCoreHunterRunServices(DatasetServices) constructor} provided * path is defined in the overloaded constructor using the * {@link #setPath(Path)} method * * @author daveneti * */ public class SimpleCoreHunterRunServices implements CoreHunterRunServices { Logger logger = LoggerFactory.getLogger(SimpleCoreHunterRunServices.class); private static final String RESULTS_PATH = "RESULTS_PATH"; private DatasetServices datasetServices; private ExecutorService executor; private List<CoreHunterRun> corehunterRuns; private Map<String, CoreHunterRunResult> corehunterResultsMap; public String charsetName = "utf-8"; private boolean shuttingDown; private boolean shutDown; private Path path; /** * Constructor that can be used by sub-classes provided the path is defined * in the overloaded constructor using the {@link #setPath(Path)} method * * @param datasetServices * the dataset services in to be used by these services * @throws IOException * if the path can not be set or is invalid */ protected SimpleCoreHunterRunServices(DatasetServices datasetServices) throws IOException { this.datasetServices = datasetServices; executor = createExecutorService(); corehunterResultsMap = new HashMap<>(); } /** * Constructor that is a path to defined the location of the datasets * * @param path * the location of the datasets * @param datasetServices * the dataset services in to be used by these services * @throws IOException * if the path can not be set or is invalid */ public SimpleCoreHunterRunServices(Path path, DatasetServices datasetServices) throws IOException { this(datasetServices); setPath(path); } public final Path getPath() { return path; } public synchronized final void setPath(Path path) throws IOException { if (path == null) { throw new IOException("Path must be defined!"); } this.path = path; initialise(); } @Override
public CoreHunterRun executeCoreHunter(CoreHunterRunArguments arguments) {
4
eckig/graph-editor
api/src/main/java/de/tesis/dynaware/grapheditor/GraphEditor.java
[ "public interface GConnection extends EObject {\n\t/**\n\t * Returns the value of the '<em><b>Id</b></em>' attribute.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Id</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Id</em>' attribute.\n\t * @see #setId(String)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGConnection_Id()\n\t * @model id=\"true\"\n\t * @generated\n\t */\n\tString getId();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GConnection#getId <em>Id</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Id</em>' attribute.\n\t * @see #getId()\n\t * @generated\n\t */\n\tvoid setId(String value);\n\n\t/**\n\t * Returns the value of the '<em><b>Type</b></em>' attribute.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Type</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Type</em>' attribute.\n\t * @see #setType(String)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGConnection_Type()\n\t * @model\n\t * @generated\n\t */\n\tString getType();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GConnection#getType <em>Type</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Type</em>' attribute.\n\t * @see #getType()\n\t * @generated\n\t */\n\tvoid setType(String value);\n\n\t/**\n\t * Returns the value of the '<em><b>Source</b></em>' reference.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Source</em>' reference isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Source</em>' reference.\n\t * @see #setSource(GConnector)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGConnection_Source()\n\t * @model required=\"true\"\n\t * @generated\n\t */\n\tGConnector getSource();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GConnection#getSource <em>Source</em>}' reference.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Source</em>' reference.\n\t * @see #getSource()\n\t * @generated\n\t */\n\tvoid setSource(GConnector value);\n\n\t/**\n\t * Returns the value of the '<em><b>Target</b></em>' reference.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Target</em>' reference isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Target</em>' reference.\n\t * @see #setTarget(GConnector)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGConnection_Target()\n\t * @model required=\"true\"\n\t * @generated\n\t */\n\tGConnector getTarget();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GConnection#getTarget <em>Target</em>}' reference.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Target</em>' reference.\n\t * @see #getTarget()\n\t * @generated\n\t */\n\tvoid setTarget(GConnector value);\n\n\t/**\n\t * Returns the value of the '<em><b>Joints</b></em>' containment reference list.\n\t * The list contents are of type {@link de.tesis.dynaware.grapheditor.model.GJoint}.\n\t * It is bidirectional and its opposite is '{@link de.tesis.dynaware.grapheditor.model.GJoint#getConnection <em>Connection</em>}'.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Joints</em>' containment reference list isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Joints</em>' containment reference list.\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGConnection_Joints()\n\t * @see de.tesis.dynaware.grapheditor.model.GJoint#getConnection\n\t * @model opposite=\"connection\" containment=\"true\"\n\t * @generated\n\t */\n\tEList<GJoint> getJoints();\n\n} // GConnection", "public interface GModel extends EObject {\n\t/**\n\t * Returns the value of the '<em><b>Nodes</b></em>' containment reference list.\n\t * The list contents are of type {@link de.tesis.dynaware.grapheditor.model.GNode}.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Nodes</em>' containment reference list isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Nodes</em>' containment reference list.\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGModel_Nodes()\n\t * @model containment=\"true\"\n\t * @generated\n\t */\n\tEList<GNode> getNodes();\n\n\t/**\n\t * Returns the value of the '<em><b>Connections</b></em>' containment reference list.\n\t * The list contents are of type {@link de.tesis.dynaware.grapheditor.model.GConnection}.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Connections</em>' containment reference list isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Connections</em>' containment reference list.\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGModel_Connections()\n\t * @model containment=\"true\"\n\t * @generated\n\t */\n\tEList<GConnection> getConnections();\n\n\t/**\n\t * Returns the value of the '<em><b>Type</b></em>' attribute.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Type</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Type</em>' attribute.\n\t * @see #setType(String)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGModel_Type()\n\t * @model\n\t * @generated\n\t */\n\tString getType();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GModel#getType <em>Type</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Type</em>' attribute.\n\t * @see #getType()\n\t * @generated\n\t */\n\tvoid setType(String value);\n\n\t/**\n\t * Returns the value of the '<em><b>Content Width</b></em>' attribute.\n\t * The default value is <code>\"3000\"</code>.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Content Width</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Content Width</em>' attribute.\n\t * @see #setContentWidth(double)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGModel_ContentWidth()\n\t * @model default=\"3000\" required=\"true\"\n\t * @generated\n\t */\n\tdouble getContentWidth();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GModel#getContentWidth <em>Content Width</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Content Width</em>' attribute.\n\t * @see #getContentWidth()\n\t * @generated\n\t */\n\tvoid setContentWidth(double value);\n\n\t/**\n\t * Returns the value of the '<em><b>Content Height</b></em>' attribute.\n\t * The default value is <code>\"2250\"</code>.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Content Height</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Content Height</em>' attribute.\n\t * @see #setContentHeight(double)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGModel_ContentHeight()\n\t * @model default=\"2250\" required=\"true\"\n\t * @generated\n\t */\n\tdouble getContentHeight();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GModel#getContentHeight <em>Content Height</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Content Height</em>' attribute.\n\t * @see #getContentHeight()\n\t * @generated\n\t */\n\tvoid setContentHeight(double value);\n\n} // GModel", "public interface GNode extends EObject {\n\t/**\n\t * Returns the value of the '<em><b>Id</b></em>' attribute.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Id</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Id</em>' attribute.\n\t * @see #setId(String)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGNode_Id()\n\t * @model id=\"true\"\n\t * @generated\n\t */\n\tString getId();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GNode#getId <em>Id</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Id</em>' attribute.\n\t * @see #getId()\n\t * @generated\n\t */\n\tvoid setId(String value);\n\n\t/**\n\t * Returns the value of the '<em><b>Type</b></em>' attribute.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Type</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Type</em>' attribute.\n\t * @see #setType(String)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGNode_Type()\n\t * @model\n\t * @generated\n\t */\n\tString getType();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GNode#getType <em>Type</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Type</em>' attribute.\n\t * @see #getType()\n\t * @generated\n\t */\n\tvoid setType(String value);\n\n\t/**\n\t * Returns the value of the '<em><b>X</b></em>' attribute.\n\t * The default value is <code>\"0\"</code>.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>X</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>X</em>' attribute.\n\t * @see #setX(double)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGNode_X()\n\t * @model default=\"0\" required=\"true\"\n\t * @generated\n\t */\n\tdouble getX();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GNode#getX <em>X</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>X</em>' attribute.\n\t * @see #getX()\n\t * @generated\n\t */\n\tvoid setX(double value);\n\n\t/**\n\t * Returns the value of the '<em><b>Y</b></em>' attribute.\n\t * The default value is <code>\"0\"</code>.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Y</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Y</em>' attribute.\n\t * @see #setY(double)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGNode_Y()\n\t * @model default=\"0\" required=\"true\"\n\t * @generated\n\t */\n\tdouble getY();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GNode#getY <em>Y</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Y</em>' attribute.\n\t * @see #getY()\n\t * @generated\n\t */\n\tvoid setY(double value);\n\n\t/**\n\t * Returns the value of the '<em><b>Width</b></em>' attribute.\n\t * The default value is <code>\"151\"</code>.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Width</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Width</em>' attribute.\n\t * @see #setWidth(double)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGNode_Width()\n\t * @model default=\"151\" required=\"true\"\n\t * @generated\n\t */\n\tdouble getWidth();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GNode#getWidth <em>Width</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Width</em>' attribute.\n\t * @see #getWidth()\n\t * @generated\n\t */\n\tvoid setWidth(double value);\n\n\t/**\n\t * Returns the value of the '<em><b>Height</b></em>' attribute.\n\t * The default value is <code>\"101\"</code>.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Height</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Height</em>' attribute.\n\t * @see #setHeight(double)\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGNode_Height()\n\t * @model default=\"101\" required=\"true\"\n\t * @generated\n\t */\n\tdouble getHeight();\n\n\t/**\n\t * Sets the value of the '{@link de.tesis.dynaware.grapheditor.model.GNode#getHeight <em>Height</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Height</em>' attribute.\n\t * @see #getHeight()\n\t * @generated\n\t */\n\tvoid setHeight(double value);\n\n\t/**\n\t * Returns the value of the '<em><b>Connectors</b></em>' containment reference list.\n\t * The list contents are of type {@link de.tesis.dynaware.grapheditor.model.GConnector}.\n\t * It is bidirectional and its opposite is '{@link de.tesis.dynaware.grapheditor.model.GConnector#getParent <em>Parent</em>}'.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Connectors</em>' containment reference list isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Connectors</em>' containment reference list.\n\t * @see de.tesis.dynaware.grapheditor.model.GraphPackage#getGNode_Connectors()\n\t * @see de.tesis.dynaware.grapheditor.model.GConnector#getParent\n\t * @model opposite=\"parent\" containment=\"true\"\n\t * @generated\n\t */\n\tEList<GConnector> getConnectors();\n\n} // GNode", "public class GraphEditorProperties implements GraphEventManager\n{\n\n /**\n * The default max width of the editor region, set on startup.\n */\n public static final double DEFAULT_MAX_WIDTH = Double.MAX_VALUE;\n /**\n * The default max height of the editor region, set on startup.\n */\n public static final double DEFAULT_MAX_HEIGHT = Double.MAX_VALUE;\n\n public static final double DEFAULT_BOUND_VALUE = 15;\n public static final double DEFAULT_GRID_SPACING = 12;\n\n // The distance from the editor edge at which the objects should stop when dragged / resized.\n private double northBoundValue = DEFAULT_BOUND_VALUE;\n private double southBoundValue = DEFAULT_BOUND_VALUE;\n private double eastBoundValue = DEFAULT_BOUND_VALUE;\n private double westBoundValue = DEFAULT_BOUND_VALUE;\n\n // Off by default.\n private final BooleanProperty gridVisible = new SimpleBooleanProperty(this, \"gridVisible\"); //$NON-NLS-1$\n private final BooleanProperty snapToGrid = new SimpleBooleanProperty(this, \"snapToGrid\"); //$NON-NLS-1$\n private final DoubleProperty gridSpacing = new SimpleDoubleProperty(this, \"gridSpacing\", DEFAULT_GRID_SPACING); //$NON-NLS-1$\n\n private final Map<EditorElement, BooleanProperty> readOnly = new EnumMap<>(EditorElement.class);\n\n private final ObservableMap<String, String> customProperties = FXCollections.observableHashMap();\n\n private final GraphEventManager eventManager = new GraphEventManagerImpl();\n\n /**\n * Creates a new editor properties instance containing a set of default\n * properties.\n */\n public GraphEditorProperties()\n {\n }\n\n /**\n * Copy constructor.\n *\n * <p>\n * Creates a new editor properties instance with all values copied over from\n * an existing instance.\n * </p>\n *\n * @param editorProperties\n * an existing {@link GraphEditorProperties} instance\n */\n public GraphEditorProperties(final GraphEditorProperties editorProperties)\n {\n northBoundValue = editorProperties.getNorthBoundValue();\n southBoundValue = editorProperties.getSouthBoundValue();\n eastBoundValue = editorProperties.getEastBoundValue();\n westBoundValue = editorProperties.getWestBoundValue();\n\n gridVisible.set(editorProperties.isGridVisible());\n snapToGrid.set(editorProperties.isSnapToGridOn());\n gridSpacing.set(editorProperties.getGridSpacing());\n\n for (final Map.Entry<EditorElement, BooleanProperty> entry : editorProperties.readOnly.entrySet())\n {\n readOnly.computeIfAbsent(entry.getKey(), k -> new SimpleBooleanProperty()).set(entry.getValue().get());\n }\n\n customProperties.putAll(editorProperties.getCustomProperties());\n }\n\n /**\n * Gets the value of the north bound.\n *\n * @return the value of the north bound\n */\n public double getNorthBoundValue()\n {\n return northBoundValue;\n }\n\n /**\n * Sets the value of the north bound.\n *\n * @param pNorthBoundValue\n * the value of the north bound\n */\n public void setNorthBoundValue(final double pNorthBoundValue)\n {\n northBoundValue = pNorthBoundValue;\n }\n\n /**\n * Gets the value of the south bound.\n *\n * @return the value of the south bound\n */\n public double getSouthBoundValue()\n {\n return southBoundValue;\n }\n\n /**\n * Sets the value of the south bound.\n *\n * @param pSouthBoundValue\n * the value of the south bound\n */\n public void setSouthBoundValue(final double pSouthBoundValue)\n {\n southBoundValue = pSouthBoundValue;\n }\n\n /**\n * Gets the value of the east bound.\n *\n * @return the value of the east bound\n */\n public double getEastBoundValue()\n {\n return eastBoundValue;\n }\n\n /**\n * Sets the value of the east bound.\n *\n * @param pEastBoundValue\n * the value of the east bound\n */\n public void setEastBoundValue(final double pEastBoundValue)\n {\n eastBoundValue = pEastBoundValue;\n }\n\n /**\n * Gets the value of the west bound.\n *\n * @return the value of the west bound\n */\n public double getWestBoundValue()\n {\n return westBoundValue;\n }\n\n /**\n * Sets the value of the west bound.\n *\n * @param pWestBoundValue\n * the value of the west bound\n */\n public void setWestBoundValue(final double pWestBoundValue)\n {\n westBoundValue = pWestBoundValue;\n }\n\n /**\n * Checks if the background grid is visible.\n *\n * @return {@code true} if the background grid is visible, {@code false} if\n * not\n */\n public boolean isGridVisible()\n {\n return gridVisible.get();\n }\n\n /**\n * Sets whether the background grid should be visible or not.\n *\n * @param pGridVisible\n * {@code true} if the background grid should be visible,\n * {@code false} if not\n */\n public void setGridVisible(final boolean pGridVisible)\n {\n gridVisible.set(pGridVisible);\n }\n\n /**\n * Gets the grid-visible property.\n *\n * @return a {@link BooleanProperty} tracking whether the grid is visible or\n * not\n */\n public BooleanProperty gridVisibleProperty()\n {\n return gridVisible;\n }\n\n /**\n * Checks if snap-to-grid is on.\n *\n * @return {@code true} if snap-to-grid is on, {@code false} if not\n */\n public boolean isSnapToGridOn()\n {\n return snapToGrid.get();\n }\n\n /**\n * Sets whether snap-to-grid should be on.\n *\n * @param pSnapToGrid\n * {@code true} if snap-to-grid should be on, {@code false} if\n * not\n */\n public void setSnapToGrid(final boolean pSnapToGrid)\n {\n snapToGrid.set(pSnapToGrid);\n }\n\n /**\n * Gets the snap-to-grid property.\n *\n * @return a {@link BooleanProperty} tracking whether snap-to-grid is on or\n * off\n */\n public BooleanProperty snapToGridProperty()\n {\n return snapToGrid;\n }\n\n /**\n * Gets the current grid spacing in pixels.\n *\n * @return the current grid spacing\n */\n public double getGridSpacing()\n {\n return gridSpacing.get();\n }\n\n /**\n * Sets the grid spacing to be used if the grid is visible and/or\n * snap-to-grid is enabled.\n *\n * <p>\n * Integer values are recommended to avoid sub-pixel positioning effects.\n * </p>\n *\n * @param pGridSpacing\n * the grid spacing to be used\n */\n public void setGridSpacing(final double pGridSpacing)\n {\n gridSpacing.set(pGridSpacing);\n }\n\n /**\n * Gets the grid spacing property.\n *\n * @return the grid spacing {@link DoubleProperty}.\n */\n public DoubleProperty gridSpacingProperty()\n {\n return gridSpacing;\n }\n\n /**\n * Gets the read only property\n *\n * @param pType\n * {@link EditorElement}\n * @return read only {@link BooleanProperty}\n */\n public BooleanProperty readOnlyProperty(final EditorElement pType)\n {\n Objects.requireNonNull(pType, \"ElementType may not be null!\");\n return readOnly.computeIfAbsent(pType, k -> new SimpleBooleanProperty());\n }\n\n /**\n * Returns whether or not the graph is in read only state.\n *\n * @param pType\n * {@link EditorElement}\n * @return whether or not the graph is in read only state.\n */\n public boolean isReadOnly(final EditorElement pType)\n {\n return pType != null && readOnly.computeIfAbsent(pType, k -> new SimpleBooleanProperty()).get();\n }\n\n /**\n * @param pType\n * {@link EditorElement}\n * @param pReadOnly\n * {@code true} to set the graph editor in read only state or {@code false} (default) for edit state.\n */\n public void setReadOnly(final EditorElement pType, final boolean pReadOnly)\n {\n if (pType != null)\n {\n readOnly.computeIfAbsent(pType, k -> new SimpleBooleanProperty()).set(pReadOnly);\n }\n }\n\n /**\n * Additional properties that may be added and referred to in custom skin\n * implementations.\n *\n * @return a map of custom properties\n */\n public ObservableMap<String, String> getCustomProperties()\n {\n return customProperties;\n }\n\n @Override\n public boolean activateGesture(GraphInputGesture pGesture, Event pEvent, Object pOwner)\n {\n return eventManager.activateGesture(pGesture, pEvent, pOwner);\n }\n\n @Override\n public boolean finishGesture(GraphInputGesture pExpected, Object pOwner)\n {\n return eventManager.finishGesture(pExpected, pOwner);\n }\n}", "public final class RemoveContext\n{\n\n private final Collection<EObject> objectsToDelete = new HashSet<>();\n\n /**\n * Constructor\n *\n * @since 15.02.2019\n */\n public RemoveContext()\n {\n // Auto-generated constructor stub\n }\n\n /**\n * @param pToCheck\n * {@link EObject} to check\n * @return {@code true} if no other involved party has created a delete\n * command for the given object otherwise {@code false}\n * @since 15.02.2019\n */\n public boolean canRemove(final EObject pToCheck)\n {\n return objectsToDelete.add(pToCheck);\n }\n\n /**\n * @param pToCheck\n * {@link EObject} to check\n * @return {@code true} any involved party has created a delete command for\n * the given object otherwise {@code false}\n * @since 15.02.2019\n */\n public boolean contains(final EObject pToCheck)\n {\n return objectsToDelete.contains(pToCheck);\n }\n}" ]
import java.util.Collection; import java.util.function.BiFunction; import java.util.function.Function; import org.eclipse.emf.common.command.Command; import org.eclipse.emf.ecore.EObject; import de.tesis.dynaware.grapheditor.model.GConnection; import de.tesis.dynaware.grapheditor.model.GModel; import de.tesis.dynaware.grapheditor.model.GNode; import de.tesis.dynaware.grapheditor.utils.GraphEditorProperties; import de.tesis.dynaware.grapheditor.utils.RemoveContext; import javafx.beans.property.ObjectProperty; import javafx.scene.layout.Region;
/* * Copyright (C) 2005 - 2014 by TESIS DYNAware GmbH */ package de.tesis.dynaware.grapheditor; /** * Provides functionality for displaying and editing graph-like diagrams in * JavaFX. * * <p> * Example: * * <pre> * <code>GModel model = GraphFactory.eINSTANCE.createGModel(); * * GraphEditor graphEditor = new DefaultGraphEditor(); * graphEditor.setModel(model); * * Region view = graphEditor.getView();</code> * </pre> * * The view is a {@link Region} and can be added to the JavaFX scene graph in * the usual way. For large graphs, the editor can be put inside a pannable * container (see module core) instead. * </p> * * <p> * The editor updates its underlying model via EMF commands. This means any user * action should be undoable. Helper methods for common operations are provided * in the {@link Commands} class, such as: * * <ul> * <li>Add Node</li> * <li>Clear All</li> * <li>Undo</li> * <li>Redo</li> * </ul> * * </p> * * <p> * Look and feel can be customised by setting custom skin classes. The default * skins can also be customised to some extent via CSS. See <b>defaults.css</b> * in the core module for more information. * </p> */ public interface GraphEditor extends GraphEditorSkins { /** * Sets a custom connector validator. * * <p> * This will be used to decide which connections are allowed / forbidden during drag and drop events in the editor. * </p> * * @param validator a custom validator implements {@link GConnectorValidator}, or null to use the default validator */ void setConnectorValidator(final GConnectorValidator validator); /** * Sets the graph model to be edited. * * @param model the {@link GModel} to be edited */ void setModel(final GModel model); /** * Gets the graph model that is currently being edited. * * @return the {@link GModel} being edited, or {@code null} if no model was ever set */ GModel getModel(); /** * Reloads the graph model currently being edited. * * <p> * <b>Note: </b><br> * If the model is updated via EMF commands, as is recommended, it should rarely be necessary to call this method. * The model will be reloaded automatically via a command-stack listener. * </p> */ void reload(); /** * The property containing the graph model being edited. * * @return a property containing the {@link GModel} being edited */ ObjectProperty<GModel> modelProperty(); /** * Gets the view where the graph is displayed and edited. * * <p> * The view is a JavaFX {@link Region}. It should be added to the scene * graph in the usual way. * </p> * * @return the {@link Region} where the graph is displayed and edited */ Region getView(); /** * Gets the properties of the editor. * * <p> * This provides access to global properties such as: * * <ul> * <li>Show/hide alignment grid.</li> * <li>Toggle snap-to-grid on/off.</li> * <li>Toggle editor bounds on/off.</li> * </ul> * * </p> * * @return an {@link GraphEditorProperties} instance containing the properties of the editor */ GraphEditorProperties getProperties(); /** * Gets the skin lookup. * * <p> * The skin lookup is used to get any skin instance associated to a model element instance. * </p> * * @return a {@link SkinLookup} used to lookup skins */ SkinLookup getSkinLookup(); /** * Gets the selection manager. * * <p> * The selection manager keeps track of the selected nodes, connections, * etc. * </p> * * @return the {@link SelectionManager} */ SelectionManager getSelectionManager(); /** * Sets a method to be called when a connection is created in the editor. * * <p> * This can be used to append additional commands to the one that created the connection. * </p> * * @param consumer a consumer to append additional commands */
void setOnConnectionCreated(Function<GConnection, Command> consumer);
0
cert-se/megatron-java
src/se/sitic/megatron/db/ImportSystemData.java
[ "public class AppProperties {\n // -- Keys in properties file --\n\n // Implicit\n public static final String JOB_TYPE_NAME_KEY = \"implicit.jobTypeName\";\n\n // General\n public static final String LOG4J_FILE_KEY = \"general.log4jConfigFile\";\n public static final String LOG_DIR_KEY = \"general.logDir\";\n public static final String JOB_TYPE_CONFIG_DIR_KEY = \"general.jobTypeConfigDir\";\n public static final String SLURP_DIR_KEY = \"general.slurpDir\";\n public static final String OUTPUT_DIR_KEY = \"general.outputDir\";\n public static final String TMP_DIR_KEY = \"general.tmpDir\";\n public static final String INPUT_CHAR_SET_KEY = \"general.inputCharSet\";\n // Deprecated: geoIp.databaseFile (use defaultValuegeoIp.countryDatabaseFile instead)\n public static final String GEO_IP_DATABASE_FILE_KEY = \"geoIp.databaseFile\";\n public static final String GEO_IP_COUNTRY_DATABASE_FILE_KEY = \"geoIp.countryDatabaseFile\";\n public static final String GEO_IP_ASN_DATABASE_FILE_KEY = \"geoIp.asnDatabaseFile\";\n public static final String GEO_IP_CITY_DATABASE_FILE_KEY = \"geoIp.cityDatabaseFile\";\n public static final String GEO_IP_USE_CITY_DATABASE_FOR_COUNTRY_LOOKUPS_KEY = \"geoIp.useCityDatabaseForCountryLookups\";\n public static final String FILENAME_MAPPER_LIST_KEY = \"general.filenameMapperList\";\n public static final String USE_DNS_JAVA_KEY = \"general.useDnsJava\";\n public static final String WHOIS_SERVER_KEY = \"general.whoisServer\";\n public static final String HIGH_PRIORITY_THRESHOLD_KEY = \"general.highPriorityNotification.threshold\";\n public static final String TIMESTAMP_WARNING_MAX_AGE_KEY = \"general.timestampWarning.maxAge\";\n public static final String PRINT_PROGRESS_INTERVAL_KEY = \"general.printProgressInterval\";\n public static final String FILE_ALREADY_PROCESSED_ACTION_KEY = \"general.fileAlreadyProcessedAction\";\n \n // dnsjava\n public static final String DNS_JAVA_USE_DNS_JAVA_KEY = \"dnsJava.useDnsJava\";\n public static final String DNS_JAVA_USE_SIMPLE_RESOLVER_KEY = \"dnsJava.useSimpleResolver\";\n public static final String DNS_JAVA_DNS_SERVERS_KEY = \"dnsJava.dnsServers\";\n public static final String DNS_JAVA_TIME_OUT_KEY = \"dnsJava.timeOut\";\n \n // Database\n public static final String DB_USERNAME_KEY = \"db.username\";\n public static final String DB_PASSWORD_KEY = \"db.password\";\n public static final String DB_SERVER_KEY = \"db.server\";\n public static final String DB_PORT_KEY = \"db.port\";\n public static final String DB_NAME_KEY = \"db.name\";\n public static final String JDBC_URL_KEY = \"db.jdbc.url\";\n public static final String JDBC_DRIVER_CLASS_KEY = \"db.jdbc.driverClassName\";\n\n // BGP\n public static final String BGP_IMPORT_FILE_KEY = \"bgp.importFile\";\n public static final String BGP_HARD_CODED_PREFIXES_KEY = \"bgp.hardCodedPrefixes\";\n \n // Export\n public static final String EXPORT_TEMPLATE_DIR_KEY = \"export.templateDir\";\n public static final String EXPORT_HEADER_FILE_KEY = \"export.headerFile\";\n public static final String EXPORT_ROW_FILE_KEY = \"export.rowFile\";\n public static final String EXPORT_FOOTER_FILE_KEY = \"export.footerFile\";\n public static final String EXPORT_CHAR_SET_KEY = \"export.charSet\";\n public static final String EXPORT_TIMESTAMP_FORMAT_KEY = \"export.timestampFormat\";\n public static final String EXPORT_REWRITERS_KEY = \"export.rewriters\";\n public static final String EXPORT_JOB_TYPE_NAME_MAPPER_KEY = \"export.jobTypeNameMapper\"; \n\n // Mail\n public static final String MAIL_SMTP_HOST_KEY = \"mail.smtpHost\";\n public static final String MAIL_DEBUG_KEY = \"mail.debug\";\n public static final String MAIL_FROM_ADDRESS_KEY = \"mail.fromAddress\";\n public static final String MAIL_TO_ADDRESSES_KEY = \"mail.toAddresses\";\n public static final String MAIL_CC_ADDRESSES_KEY = \"mail.ccAddresses\";\n public static final String MAIL_BCC_ADDRESSES_KEY = \"mail.bccAddresses\";\n public static final String MAIL_ARCHIVE_BCC_ADDRESSES_KEY = \"mail.archiveBccAddresses\";\n public static final String MAIL_SUMMARY_TO_ADDRESSES_KEY = \"mail.mailJobSummary.toAddresses\";\n public static final String MAIL_NOTIFICATION_TO_ADDRESSES_KEY = \"mail.highPriorityNotification.toAddresses\";\n public static final String MAIL_REPLY_TO_ADDRESSES_KEY = \"mail.replyToAddresses\";\n public static final String MAIL_HTML_MAIL_KEY = \"mail.htmlMail\";\n public static final String MAIL_IP_QUARANTINE_PERIOD_KEY = \"mail.ipQuarantinePeriod\";\n \n public static final String MAIL_SUBJECT_TEMPLATE_KEY = \"mail.subjectTemplate\";\n public static final String MAIL_JOB_SUMMARY_SUBJECT_TEMPLATE_KEY = \"mail.mailJobSummary.subjectTemplate\";\n public static final String MAIL_TEMPLATE_DIR_KEY = \"mail.templateDir\";\n public static final String MAIL_DEFAULT_LANGUAGE_CODE_KEY = \"mail.defaultLanguageCode\";\n public static final String MAIL_HEADER_FILE_KEY = \"mail.headerFile\";\n public static final String MAIL_ROW_FILE_KEY = \"mail.rowFile\";\n public static final String MAIL_FOOTER_FILE_KEY = \"mail.footerFile\";\n public static final String MAIL_ATTACHMENT_HEADER_FILE_KEY = \"mail.attachmentHeaderFile\";\n public static final String MAIL_ATTACHMENT_ROW_FILE_KEY = \"mail.attachmentRowFile\";\n public static final String MAIL_ATTACHMENT_FOOTER_FILE_KEY = \"mail.attachmentFooterFile\"; \n public static final String MAIL_ATTACHMENT_NAME_KEY = \"mail.attachmentName\";\n public static final String MAIL_TIMESTAMP_FORMAT_KEY = \"mail.timestampFormat\";\n public static final String MAIL_RAISE_ERROR_FOR_DEBUG_TEMPLATE_KEY = \"mail.raiseErrorForDebugTemplate\";\n \n // Mail Encryption\n public static final String MAIL_ENCRYPTION_TYPE_KEY = \"mail.encryptionType\";\n public static final String MAIL_ENCRYPTION_KEYPATH_KEY = \"mail.encryptionKeyPath\";\n public static final String MAIL_ENCRYPTION_SMIME_PW_KEY = \"mail.enryptionSMIMEpw\";\n public static final String MAIL_ENCRYPTION_PGP_PW_KEY = \"mail.enryptionPGPpw\";\n public static final String MAIL_ENCRYPTION_ENCRYPT_KEY = \"mail.encryptMail\";\n public static final String MAIL_ENCRYPTION_SIGN_KEY = \"mail.signMail\";\n\n // Filters\n public static final String FILTER_PRE_LINE_PROCESSOR_KEY = \"filter.preLineProcessor.classNames\";\n public static final String FILTER_PRE_PARSER_KEY = \"filter.preParser.classNames\";\n public static final String FILTER_PRE_DECORATOR_KEY = \"filter.preDecorator.classNames\";\n public static final String FILTER_PRE_STORAGE_KEY = \"filter.preStorage.classNames\";\n public static final String FILTER_PRE_EXPORT_KEY = \"filter.preExport.classNames\";\n public static final String FILTER_PRE_MAIL_KEY = \"filter.preMail.classNames\";\n public static final String FILTER_EXCLUDE_REG_EXP_KEY = \"filter.regExpLineFilter.excludeRegExp\";\n public static final String FILTER_INCLUDE_REG_EXP_KEY = \"filter.regExpLineFilter.includeRegExp\";\n public static final String FILTER_LINE_NUMBER_EXCLUDE_INTERVALS_KEY = \"filter.lineNumberFilter.excludeIntervals\";\n public static final String FILTER_LINE_NUMBER_INCLUDE_INTERVALS_KEY = \"filter.lineNumberFilter.includeIntervals\";\n public static final String FILTER_PRIORITY_INCLUDE_INTERVALS_KEY = \"filter.priorityFilter.includeIntervals\";\n public static final String FILTER_EXCLUDE_COUNTRY_CODES_KEY = \"filter.countryCodeFilter.excludeCountryCodes\";\n public static final String FILTER_INCLUDE_COUNTRY_CODES_KEY = \"filter.countryCodeFilter.includeCountryCodes\";\n public static final String FILTER_COUNTRY_CODE_ORGANIZATION_KEY = \"filter.countryCodeFilter.organizationToFilter\";\n public static final String FILTER_EXCLUDE_AS_NUMBERS_KEY = \"filter.asnFilter.excludeAsNumbers\";\n public static final String FILTER_INCLUDE_AS_NUMBERS_KEY = \"filter.asnFilter.includeAsNumbers\";\n public static final String FILTER_ASN_ORGANIZATION_KEY = \"filter.asnFilter.organizationToFilter\";\n public static final String FILTER_ATTRIBUTE_NAME_KEY = \"filter.attributeFilter.attributeName\";\n public static final String FILTER_ATTRIBUTE_EXCLUDE_REG_EXP_KEY = \"filter.attributeFilter.excludeRegExp\";\n public static final String FILTER_ATTRIBUTE_INCLUDE_REG_EXP_KEY = \"filter.attributeFilter.includeRegExp\";\n public static final String FILTER_OCCURRENCE_ATTRIBUTE_NAMES_KEY = \"filter.occurrenceFilter.attributeNames\"; \n public static final String FILTER_OCCURRENCE_EXCLUDE_INTERVALS_KEY = \"filter.occurrenceFilter.excludeIntervals\";\n public static final String FILTER_OCCURRENCE_INCLUDE_INTERVALS_KEY = \"filter.occurrenceFilter.includeIntervals\";\n public static final String FILTER_OCCURRENCE_FILE_SORTED_KEY = \"filter.occurrenceFilter.fileSorted\";\n public static final String FILTER_MATCH_IP_ADDRESS_KEY = \"filter.organizationFilter.matchIpAddress\";\n public static final String FILTER_MATCH_HOSTNAME_KEY = \"filter.organizationFilter.matchHostname\";\n public static final String FILTER_MATCH_ASN_KEY = \"filter.organizationFilter.matchAsn\";\n \n // File Processor\n public static final String FILE_PROCESSOR_CLASS_NAME_KEY = \"fileProcessor.className\";\n public static final String FILE_PROCESSOR_CLASS_NAMES_KEY = \"fileProcessor.classNames\";\n public static final String FILE_PROCESSOR_DELETE_TMP_FILES_KEY = \"fileProcessor.deleteTmpFiles\";\n public static final String FILE_PROCESSOR_OS_COMMAND_KEY = \"fileProcessor.osCommandProcessor.command\";\n public static final String FILE_PROCESSOR_DIFF_COMMAND_KEY = \"fileProcessor.diffProcessor.command\";\n public static final String FILE_PROCESSOR_DIFF_OLD_FILES_DIR_KEY = \"fileProcessor.diffProcessor.oldFilesDir\";\n public static final String FILE_PROCESSOR_DIFF_NO_OF_BACKUPS_TO_KEEP_KEY = \"fileProcessor.diffProcessor.noOfBackupsToKeep\";\n public static final String FILE_PROCESSOR_XML_TO_ROW_START_ELEMENT_KEY = \"fileProcessor.xmlToRowFileProcessor.startElement\";\n public static final String FILE_PROCESSOR_XML_TO_ROW_ELEMENTS_TO_SAVE_KEY = \"fileProcessor.xmlToRowFileProcessor.elementsToSave\";\n public static final String FILE_PROCESSOR_XML_TO_ROW_OUTPUT_SEPARATOR_KEY = \"fileProcessor.xmlToRowFileProcessor.outputSeparator\";\n // Deprecated: fileProcessor.xmlToRowFileProcessor.deleteOutputFile (use fileProcessor.deleteTmpFiles instead)\n public static final String FILE_PROCESSOR_XML_TO_ROW_DELETE_OUTPUT_FILE_KEY = \"fileProcessor.xmlToRowFileProcessor.deleteOutputFile\";\n public static final String FILE_PROCESSOR_DNS_NO_OF_THREADS_KEY = \"fileProcessor.multithreadedDnsProcessor.noOfThreads\";\n public static final String FILE_PROCESSOR_DNS_REVERSE_DNS_LOOKUP_KEY = \"fileProcessor.multithreadedDnsProcessor.reverseDnsLookup\";\n public static final String FILE_PROCESSOR_DNS_REG_EXP_IP_KEY = \"fileProcessor.multithreadedDnsProcessor.regExpIp\";\n public static final String FILE_PROCESSOR_DNS_REG_EXP_HOSTNAME_KEY = \"fileProcessor.multithreadedDnsProcessor.regExpHostname\";\n \n // Line Processor\n public static final String LINE_PROCESSOR_CLASS_NAME_KEY = \"lineProcessor.className\";\n public static final String LINE_MERGER_START_REG_EXP_KEY = \"lineProcessor.merger.startRegExp\";\n public static final String LINE_MERGER_END_REG_EXP_KEY = \"lineProcessor.merger.endRegExp\";\n public static final String LINE_MERGER_RESTART_IF_START_FOUND_KEY = \"lineProcessor.merger.restartIfStartFound\";\n public static final String LINE_MERGER_SEPARATOR_KEY = \"lineProcessor.merger.separator\";\n public static final String LINE_SPLITTER_SEPARATOR_REG_EXP_KEY = \"lineProcessor.splitter.separatorRegExp\";\n public static final String LINE_SPLITTER_ITEM_REG_EXP_KEY = \"lineProcessor.splitter.itemRegExp\";\n public static final String LINE_SPLITTER_APPEND_ORIGINAL_LOG_ROW_KEY = \"lineProcessor.splitter.appendOriginalLogRow\";\n \n // Decorators\n public static final String DECORATOR_CLASS_NAMES_KEY = \"decorator.classNames\";\n public static final String DECORATOR_PRE_EXPORT_CLASS_NAMES_KEY = \"decorator.preExport.classNames\";\n public static final String DECORATOR_PRE_MAIL_CLASS_NAMES_KEY = \"decorator.preMail.classNames\";\n public static final String DECORATOR_COMBINED_DECORATOR_CLASS_NAMES_KEY = \"decorator.combinedDecorator.classNames\";\n public static final String DECORATOR_USE_ORGANIZATION_MATCHER_KEY = \"decorator.useOrganizationMatcher\";\n public static final String DECORATOR_MATCH_IP_ADDRESS_KEY = \"decorator.organizationMatcher.matchIpAddress\";\n public static final String DECORATOR_MATCH_HOSTNAME_KEY = \"decorator.organizationMatcher.matchHostname\";\n public static final String DECORATOR_MATCH_ASN_KEY = \"decorator.organizationMatcher.matchAsn\";\n public static final String DECORATOR_COUNTRY_CODES_TO_ADD_KEY = \"decorator.countryCodeFromHostnameDecorator.countryCodesToAdd\";\n public static final String DECORATOR_USE_ASN_IN_LOG_ENTRY_KEY = \"decorator.asnGeoIpDecorator.useAsnInLogEntry\";\n public static final String DECORATOR_ADD_AS_NAME_KEY = \"decorator.asnGeoIpDecorator.addAsName\";\n public static final String DECORATOR_URL_TO_HOSTNAME_USE_PRIMARY_ORG_KEY = \"decorator.urlToHostnameDecorator.usePrimaryOrg\";\n public static final String DECORATOR_GEOLOCATION_FIELDS_TO_ADD_KEY = \"decorator.geolocationDecorator.fieldsToAdd\";\n \n // Parser\n public static final String PARSER_CLASS_NAME_KEY = \"parser.className\";\n public static final String PARSER_PARSE_ERROR_THRESHOLD_KEY = \"parser.parseErrorThreshold\";\n public static final String PARSER_MAX_NO_OF_PARSE_ERRORS = \"parser.maxNoOfParseErrors\";\n public static final String PARSER_TIME_STAMP_FORMAT_KEY = \"parser.timestampFormat\";\n public static final String PARSER_ADD_CURRENT_DATE_TO_TIMESTAMP_KEY = \"parser.addCurrentDateToTimestamp\";\n public static final String PARSER_DEFAULT_TIME_ZONE_KEY = \"parser.defaultTimeZone\";\n public static final String PARSER_CHECK_UNUSED_VARIABLES_KEY = \"parser.checkUnusedVariables\";\n public static final String PARSER_LINE_REG_EXP_KEY = \"parser.lineRegExp\";\n public static final String PARSER_ITEM_PREFIX = \"parser.item.\";\n public static final String PARSER_ADDITIONAL_ITEM_PREFIX = \"parser.item.additionalItem.\";\n public static final String PARSER_FREE_TEXT_KEY = \"parser.item.freeText\";\n public static final String PARSER_TRIM_VALUE_KEY = \"parser.trimValue\";\n public static final String PARSER_REMOVE_ENCLOSING_CHARS_FROM_VALUE_KEY = \"parser.removeEnclosingCharsFromValue\";\n public static final String PARSER_REWRITERS_KEY = \"parser.rewriters\";\n public static final String PARSER_REMOVE_TRAILING_SPACES_KEY = \"parser.removeTrailingSpaces\";\n public static final String PARSER_EXPAND_IP_RANGE_WITH_ZERO_OCTETS_KEY = \"parser.expandIpRangeWithZeroOctets\";\n \n // RSS\n public static final String RSS_FACTORY_CLASS_NAME_KEY = \"rss.factoryClassName\";\n public static final String RSS_FORMAT_KEY = \"rss.format\";\n // Job RSS\n public static final String RSS_JOB_ENABLED_KEY = \"rss.job.enabled\";\n public static final String RSS_JOB_FILE_KEY = \"rss.job.file\";\n public static final String RSS_JOB_CONTENT_TITLE_KEY = \"rss.job.content.title\";\n public static final String RSS_JOB_CONTENT_LINK_KEY = \"rss.job.content.link\";\n public static final String RSS_JOB_CONTENT_DESCRIPTION_KEY = \"rss.job.content.description\";\n public static final String RSS_JOB_CONTENT_AUTHOR_KEY = \"rss.job.content.author\";\n public static final String RSS_JOB_CONTENT_COPYRIGHT_KEY = \"rss.job.content.copyright\";\n public static final String RSS_JOB_MAX_NO_OF_ITEMS_KEY = \"rss.job.maxNoOfItems\";\n public static final String RSS_JOB_ITEM_EXPIRE_TIME_IN_MINUTES_KEY = \"rss.job.itemExpireTimeInMinutes\";\n // Stats RSS\n public static final String RSS_STATS_FORMAT_KEY = \"rss.stats.format\";\n public static final String RSS_STATS_FILE_KEY = \"rss.stats.file\";\n public static final String RSS_STATS_CONTENT_TITLE_KEY = \"rss.stats.content.title\";\n public static final String RSS_STATS_CONTENT_LINK_KEY = \"rss.stats.content.link\";\n public static final String RSS_STATS_CONTENT_DESCRIPTION_KEY = \"rss.stats.content.description\";\n public static final String RSS_STATS_CONTENT_AUTHOR_KEY = \"rss.stats.content.author\";\n public static final String RSS_STATS_CONTENT_COPYRIGHT_KEY = \"rss.stats.content.copyright\";\n public static final String RSS_STATS_MAX_NO_OF_ITEMS_KEY = \"rss.stats.maxNoOfItems\";\n public static final String RSS_STATS_ITEM_EXPIRE_TIME_IN_MINUTES_KEY = \"rss.stats.itemExpireTimeInMinutes\";\n\n // Report\n // Deprecated: flash.outputDir (use report.outputDir instead)\n public static final String FLASH_NO_OF_WEEKS_KEY = \"flash.noOfWeeks\";\n // Deprecated: flash.noOfWeeks (use report.statistics.noOfWeeks instead)\n public static final String FLASH_OUTPUT_DIR_KEY = \"flash.outputDir\";\n public static final String REPORT_CLASS_NAMES_KEY = \"report.classNames\";\n public static final String REPORT_OUTPUT_DIR_KEY = \"report.outputDir\";\n public static final String REPORT_TEMPLATE_DIR_KEY = \"report.templateDir\";\n public static final String REPORT_STATISTICS_NO_OF_WEEKS_KEY = \"report.statistics.noOfWeeks\";\n public static final String REPORT_GEOLOCATION_NO_OF_WEEKS_KEY = \"report.geolocation.noOfWeeks\";\n public static final String REPORT_GEOLOCATION_GENERATE_INTERNAL_REPORT_KEY = \"report.geolocation.generateInternalReport\";\n public static final String REPORT_GEOLOCATION_NO_OF_ENTRIES_IN_CITY_REPORT_KEY = \"report.geolocation.noOfEntriesInCityReport\";\n public static final String REPORT_GEOLOCATION_JOB_TYPE_KILL_LIST_KEY = \"report.geolocation.jobTypeKillList\";\n public static final String REPORT_GEOLOCATION_ORGANIZATION_TYPE_KILL_LIST_KEY = \"report.geolocation.organizationTypeKillList\";\n public static final String REPORT_GEOLOCATION_ORGANIZATION_TYPE_NAME_MAPPER_KEY = \"report.geolocation.organizationTypeNameMapper\";\n public static final String REPORT_ORGANIZATION_NO_OF_HOURS_KEY = \"report.organization.noOfHours\";\n public static final String REPORT_ORGANIZATION_JOB_TYPES_KEY = \"report.organization.jobTypes\";\n public static final String REPORT_ORGANIZATION_RECIPIENTS_KEY = \"report.organization.recipients\";\n \n // Import\n public static final String CONTACTS_IMPORT_FILE_KEY = \"import.dataFile\";\n \n // UI (management command line user interface)\n public static final String UI_DEFAULT_CC_KEY = \"ui.organizationHandler.defaultCountryCode\";\n public static final String UI_DEFAULT_LC_KEY = \"ui.organizationHandler.defaultLanguageCode\";\n public static final String UI_OUTPUT_DIR_KEY = \"ui.organizationHandler.outputDir\";\n public static final String UI_VALID_ROLES_KEY = \"ui.organizationHandler.validRoles\";\n public static final String UI_TIMESTAMP_FORMAT_KEY = \"ui.organizationHandler.timestampFormat\";\n \n // TicketHandler\n public static final String TICKET_HANDLER_CLASS = \"ticketHandler.className\";\n public static final String TICKET_HANDLER_CREATE_CHILD = \"ticketHandler.createChild\";\n public static final String TICKET_HANDLER_VALUE_KEYS = \"ticketHandler.valueKeys\";\n public static final String TICKET_HANDLER_SENDS_MAIL = \"ticketHandler.sendsMail\";\n public static final String TICKET_HANDLER_QUEUE_NAME = \"ticketHandler.queueName\";\n public static final String TICKET_HANDLER_USER = \"ticketHandler.user\";\n public static final String TICKET_HANDLER_PASSWORD = \"ticketHandler.password\";\n public static final String TICKET_HANDLER_TICKET_OWNER = \"ticketHandler.ticketOwner\";\n public static final String TICKET_HANDLER_URL = \"ticketHandler.url\";\n public static final String TICKET_HANDLER_RESOLVE_AFTER_SEND = \"ticketHandler.resolveAfterSend\";\n public static final String TICKET_HANDLER_RESOLVED_STATUS = \"ticketHandler.resolvedStatus\";\n public static final String TICKET_HANDLER_RESOLVE_SLEEP_TIME = \"ticketHandler.resolveSleepTime\";\n public static final String TICKET_HANDLER_TO_ADDRESS = \"ticketHandler.toAddress\";\n public static final String TICKET_HANDLER_FROM_ADDRESS = \"ticketHandler.fromAddress\";\n public static final String TICKET_HANDLER_ARCHIVE_ADDRESS = \"ticketHandler.archiveAddress\";\n \n \n\n /** Filename for Megatron global properties. */\n public static final String GLOBALS_PROPS_FILE = \"/etc/megatron/megatron-globals.properties\";\n\n /** Key in system properties for global properties file. */\n public static final String MEGATRON_CONFIG_FILE_KEY = \"megatron.configfile\";\n\n // Cannot use logging becuse it's not yet initialized.\n // private static final Logger log = Logger.getLogger(GlobalProperties.class);\n\n private static final String TRUE = \"true\";\n\n private static AppProperties singleton;\n\n private Map<String, String> globalProps;\n private TypedProperties globalTypedProps;\n private List<File> jobTypeFiles;\n private List<String> jobTypeNames;\n private List<String> inputFiles;\n\n\n /**\n * Returns singleton.\n */\n public static synchronized AppProperties getInstance() {\n if (singleton == null) {\n singleton = new AppProperties();\n }\n return singleton;\n }\n\n\n /**\n * Constructor. Private due to singleton.\n */\n private AppProperties() {\n // empty\n }\n\n\n /**\n * Loads properties file and parses specified command line arguments.\n */\n public void init(String[] args) throws MegatronException, CommandLineParseException {\n // -- Hard-coded properties\n // Use US as default locale. Dates with names, e.g. 04/Jul/2009, may otherwise be incorrect.\n Locale.setDefault(Locale.US);\n \n // Use UTC as default time-zone. All time-stamps in db are in UTC-time.\n TimeZone.setDefault(TimeZone.getTimeZone(\"UTC\"));\n\n // -- Read global properties and parse command line\n this.globalProps = loadGlobalProperties();\n parseCommandLine(args);\n this.globalTypedProps = new TypedProperties(globalProps, null);\n\n // -- init jobTypeFiles and jobTypeNames\n this.jobTypeFiles = listJobTypeFiles();\n this.jobTypeNames = new ArrayList<String>();\n for (Iterator<File> iterator = jobTypeFiles.iterator(); iterator.hasNext(); ) {\n String filename = iterator.next().getName();\n this.jobTypeNames.add(StringUtil.removeSuffix(filename, \".properties\"));\n }\n }\n\n\n /**\n * Returns global properties.<p>\n * Note: This method should be used sparsely. Use TypedProperties-object created by\n * createTypedPropertiesForCli or createTypedPropertiesForWeb instead.\n */\n public TypedProperties getGlobalProperties() {\n return globalTypedProps;\n }\n\n \n /**\n * Maps specified filename (without path) to a job-type.\n * \n * @return found job-type, or null if not found.\n */\n public String mapFilenameToJobType(String filename, boolean ignoreCliArgument) {\n String result = null;\n Logger log = Logger.getLogger(getClass());\n\n if (!ignoreCliArgument) { \n result = globalTypedProps.getString(TypedProperties.CLI_JOB_TYPE_KEY, null);\n if (result != null) {\n log.debug(\"Using job-type specified in CLI-argument: \" + result);\n return result;\n }\n }\n \n List<NameValuePair> nvList = globalTypedProps.getNameValuePairList(FILENAME_MAPPER_LIST_KEY, null);\n if (nvList != null) {\n for (Iterator<NameValuePair> iterator = nvList.iterator(); (result == null) && iterator.hasNext(); ) {\n NameValuePair nv = iterator.next();\n try {\n if (filename.matches(nv.getName())) {\n log.debug(\"Job-type found: \" + nv.getValue() + \". Filename '\" + filename + \"' matches reg-exp '\" + nv.getName() + \"'.\");\n result = nv.getValue();\n }\n } catch(PatternSyntaxException e) {\n log.error(\"Invalid reg-exp in filename mapper: \" + nv.getName());\n }\n }\n } else {\n log.error(\"Filename mapper not defined in config. Property name: \" + FILENAME_MAPPER_LIST_KEY);\n }\n \n return result;\n }\n\n \n /**\n * Creates properties for specified job-type, which includes CLI-arguments and global properties.\n * Use this method in the CLI application.\n */\n public TypedProperties createTypedPropertiesForCli(String jobType) throws MegatronException {\n try {\n Map<String, String> jobTypeProps = loadJobTypeProperties(jobType);\n return new TypedProperties(jobTypeProps, Collections.singletonList(globalProps));\n } catch (MegatronException e) {\n throw new MegatronException(\"Invalid job-type name: \" + jobType, e);\n } \n }\n\n \n /**\n * Creates properties for specified job-type, which includes specifed CLI-arguments and global properties.\n * CLI-properties are used in the web application, but assigned for each run.\n * Use this method in the web application.\n * \n * @param jobType job-type name, e.g. \"shadowserver-ddos\".\n * @param cliArgs CLI-arguments. Key: CLI-consts, e.g. CLI_NO_DB. Value: argument value, e.g. \"true\". \n */\n public TypedProperties createTypedPropertiesForWeb(String jobType, Map<String, String> cliArgs) throws MegatronException {\n try {\n Map<String, String> jobTypeProps = loadJobTypeProperties(jobType);\n for (Iterator<String> iterator = cliArgs.keySet().iterator(); iterator.hasNext(); ) {\n String key = iterator.next();\n String value = cliArgs.get(key);\n jobTypeProps.put(key, value);\n }\n return new TypedProperties(jobTypeProps, Collections.singletonList(globalProps));\n } catch (MegatronException e) {\n throw new MegatronException(\"Invalid job-type name: \" + jobType, e);\n } \n }\n\n\n /**\n * Returns input filenames specified at the command line.\n */\n public List<String> getInputFiles() {\n return this.inputFiles;\n }\n\n \n public List<File> getJobTypeFiles() {\n return this.jobTypeFiles;\n }\n\n\n public List<String> getJobTypeNames() {\n return this.jobTypeNames;\n }\n\n\n public String getJobTypeConfigDir() {\n return globalTypedProps.getString(JOB_TYPE_CONFIG_DIR_KEY, null);\n }\n \n \n public String getJdbcUrl() {\n // Format: jdbc:mysql://{db.server}:{db.port}/{db.name}\n String result = globalTypedProps.getString(JDBC_URL_KEY, \"jdbc:mysql://{db.server}:{db.port}/{db.name}\");\n String dbServer = globalTypedProps.getString(DB_SERVER_KEY, \"127.0.0.1\");\n String dbPort = globalTypedProps.getString(DB_PORT_KEY, \"3306\");\n String dbName = globalTypedProps.getString(DB_NAME_KEY, \"ossec\");\n\n result = StringUtil.replace(result, \"{db.server}\", dbServer);\n result = StringUtil.replace(result, \"{db.port}\", dbPort);\n result = StringUtil.replace(result, \"{db.name}\", dbName);\n\n return result;\n }\n\n \n /**\n * Loads global properties.\n *\n * @throws MegatronException if global properties cannot be read.\n */\n private Map<String, String> loadGlobalProperties() throws MegatronException {\n String filename = System.getProperty(MEGATRON_CONFIG_FILE_KEY);\n filename = (filename != null) ? filename : GLOBALS_PROPS_FILE;\n return loadPropertiesFile(filename);\n }\n\n\n /**\n * Loads job-type properties.\n *\n * @throws IOException if properties cannot be read.\n */\n private Map<String, String> loadJobTypeProperties(String jobTypeName) throws MegatronException {\n String filename = FileUtil.concatPath(getJobTypeConfigDir(), jobTypeName + \".properties\");\n Map<String, String> result = loadPropertiesFile(filename); \n result.put(JOB_TYPE_NAME_KEY, jobTypeName);\n return result;\n }\n\n\n /**\n * Loads specified properties file.\n *\n * @throws MegatronException if global properties cannot be read.\n */\n private Map<String, String> loadPropertiesFile(String filename) throws MegatronException {\n // The class Properties cannot be used:\n // 1. Back-slashes in regular expressions are removed.\n // 2. Order is not preserved.\n\n // LinkedHashMap preserves insertion order.\n Map<String, String> result = new LinkedHashMap<String, String>();\n\n final String nameValueSeparator = \"=\";\n\n File file = new File(filename);\n BufferedReader in = null;\n try {\n in = new BufferedReader(new InputStreamReader(new FileInputStream(file), \"UTF-8\"));\n\n int lineNo = 0;\n String line = null;\n while ((line = in.readLine()) != null) {\n ++lineNo;\n String trimmedLine = line.trim();\n if ((trimmedLine.length() == 0) || trimmedLine.startsWith(Constants.CONFIG_COMMENT_PREFIX)) {\n continue;\n }\n\n // split line into name-value\n int index = line.indexOf(nameValueSeparator);\n if ((index == -1) || (index == 0)) {\n String msg = \"Parse error at line \" + lineNo + \": Separator not found.\";\n throw new IOException(msg);\n }\n String name = line.substring(0, index);\n String value = ((index + 1) < line.length()) ? line.substring(index + 1, line.length()) : \"\";\n result.put(name, value);\n }\n } catch (IOException e) {\n String msg = \"Cannot read properties file: \" + file.getAbsolutePath();\n System.err.println(msg);\n throw new MegatronException(msg, e);\n } finally {\n if (in != null) {\n try {\n in.close();\n } catch (IOException e) {\n String msg = \"Cannot close properties file: \" + file.getAbsolutePath();\n System.err.println(msg);\n throw new MegatronException(msg, e);\n }\n }\n }\n\n return result;\n }\n\n\n /**\n * Parsers specified command line arguments and adds them to properties map.\n */\n @SuppressWarnings(\"unused\")\n private void parseCommandLine(String[] args) throws MegatronException, CommandLineParseException {\n if (args == null) {\n return;\n }\n\n inputFiles = new ArrayList<String>();\n for (int i = 0; i < args.length; i++) {\n String arg = args[i].trim();\n\n if (arg.startsWith(\"-\")) {\n if (arg.equals(\"--version\") || arg.equals(\"-v\")) {\n throw new CommandLineParseException(CommandLineParseException.SHOW_VERSION_ACTION);\n } else if (arg.equals(\"--help\") || arg.equals(\"-h\")) {\n throw new CommandLineParseException(CommandLineParseException.SHOW_USAGE_ACTION);\n } else if (arg.equals(\"--slurp\") || arg.equals(\"-s\")) {\n globalProps.put(TypedProperties.CLI_SLURP_KEY, TRUE);\n } else if (arg.equals(\"--export\") || arg.equals(\"-e\")) {\n globalProps.put(TypedProperties.CLI_EXPORT_KEY, TRUE);\n } else if (arg.equals(\"--delete\") || arg.equals(\"-d\") || arg.equals(\"--delete-all\") || arg.equals(\"-D\")) {\n // job specified after delete switch? \n int nextIndex = i + 1;\n if ((nextIndex < args.length) && !args[nextIndex].startsWith(\"-\")) {\n i = nextIndex;\n globalProps.put(TypedProperties.CLI_JOB_KEY, args[i]);\n } else {\n // otherwise --job must be present\n List<String> argList = new ArrayList<String>(Arrays.asList(args));\n if (!(argList.contains(\"--job\") || argList.contains(\"--j\"))) {\n throw new CommandLineParseException(\"Job name not specified.\");\n }\n }\n \n if (arg.equals(\"--delete\") || arg.equals(\"-d\")) {\n globalProps.put(TypedProperties.CLI_DELETE_KEY, TRUE);\n } else {\n globalProps.put(TypedProperties.CLI_DELETE_ALL_KEY, TRUE); \n }\n } else if (arg.equals(\"--job\") || arg.equals(\"-j\")) {\n ++i;\n if (i == args.length) {\n throw new CommandLineParseException(\"Missing argument to \" + arg);\n }\n globalProps.put(TypedProperties.CLI_JOB_KEY, args[i]);\n } else if (arg.equals(\"--job-type\") || arg.equals(\"-t\")) {\n ++i;\n if (i == args.length) {\n throw new CommandLineParseException(\"Missing argument to \" + arg);\n }\n globalProps.put(TypedProperties.CLI_JOB_TYPE_KEY, args[i]);\n } else if (arg.equals(\"--output-dir\") || arg.equals(\"-o\")) {\n ++i;\n if (i == args.length) {\n throw new CommandLineParseException(\"Missing argument to \" + arg);\n }\n String outputDirStr = args[i];\n File outputDir = new File(outputDirStr);\n if (!outputDir.isDirectory()) {\n throw new MegatronException(\"Output directory not found: \" + outputDir.getAbsolutePath());\n }\n globalProps.put(TypedProperties.CLI_OUTPUT_DIR_KEY, outputDirStr);\n } else if (arg.equals(\"--id\") || arg.equals(\"-i\")) {\n ++i;\n if (i == args.length) {\n throw new CommandLineParseException(\"Missing argument to \" + arg);\n }\n String idStr = args[i];\n try {\n long id = Long.parseLong(idStr);\n if (id <= 0L) {\n throw new NumberFormatException(\"Id is zero or negative.\"); \n }\n } catch (NumberFormatException e) {\n throw new CommandLineParseException(\"Invalid RTIR id (--id): \" + idStr, e);\n }\n globalProps.put(TypedProperties.CLI_ID_KEY, idStr);\n } else if (arg.equals(\"--prio\") || arg.equals(\"-p\")) {\n ++i;\n if (i == args.length) {\n throw new CommandLineParseException(\"Missing argument to \" + arg);\n }\n String prioStr = args[i];\n// Skip check. OK with a list of intervals, e.g. --prio 55-60,70-75\n// try {\n// long prio = Long.parseLong(prioStr);\n// if ((prio < 0L) || (prio > 100L)) {\n// throw new NumberFormatException(\"Prio is not in range.\"); \n// }\n// } catch (NumberFormatException e) {\n// String msg = \"Invalid prio (--prio): \" + prioStr + \". Use --list-prios to list priorities.\";\n// throw new CommandLineParseException(msg, e);\n// }\n globalProps.put(TypedProperties.CLI_PRIO_KEY, prioStr);\n } else if (arg.equals(\"--list-prios\") || arg.equals(\"-P\")) {\n globalProps.put(TypedProperties.CLI_LIST_PRIOS_KEY, TRUE);\n } else if (arg.equals(\"--list-jobs\") || arg.equals(\"-l\")) {\n globalProps.put(TypedProperties.CLI_LIST_JOBS_KEY, TRUE);\n // days specified after switch?\n int nextIndex = i + 1;\n if ((nextIndex < args.length) && !args[nextIndex].startsWith(\"-\")) {\n i = nextIndex;\n String val = args[i];\n try {\n int days = Integer.parseInt(val);\n if ((days <= 0) || (days > 1000)) {\n throw new NumberFormatException(\"No. of days must be in the range 1-1000.\"); \n }\n } catch (NumberFormatException e) {\n throw new CommandLineParseException(\"Invalid no. of days (--list-jobs): \" + val, e);\n }\n globalProps.put(TypedProperties.CLI_DAYS_IN_LIST_JOBS_KEY, val);\n }\n } else if (arg.equals(\"--whois\") || arg.equals(\"-w\")) {\n globalProps.put(TypedProperties.CLI_WHOIS_KEY, TRUE);\n if (++i >= args.length) {\n throw new CommandLineParseException(\"Missing list of IPs and hostnames (or file) to argument \" + arg);\n }\n while (i < args.length) {\n inputFiles.add(args[i]); \n ++i;\n }\n } else if (arg.equals(\"--job-info\") || arg.equals(\"-I\")) {\n // job specified after switch? \n int nextIndex = i + 1;\n if ((nextIndex < args.length) && !args[nextIndex].startsWith(\"-\")) {\n i = nextIndex;\n globalProps.put(TypedProperties.CLI_JOB_KEY, args[i]);\n } else {\n // otherwise --job must be present\n List<String> argList = new ArrayList<String>(Arrays.asList(args));\n if (!(argList.contains(\"--job\") || argList.contains(\"--j\"))) {\n throw new CommandLineParseException(\"Job name not specified.\");\n }\n }\n globalProps.put(TypedProperties.CLI_JOB_INFO_KEY, TRUE);\n } else if (arg.equals(\"--no-db\") || arg.equals(\"-n\")) {\n globalProps.put(TypedProperties.CLI_NO_DB_KEY, TRUE);\n } else if (arg.equals(\"--stdout\") || arg.equals(\"-S\")) {\n globalProps.put(TypedProperties.CLI_STDOUT_KEY, TRUE);\n } else if (arg.equals(\"--import-contacts\")) {\n globalProps.put(TypedProperties.CLI_IMPORT_CONTACTS_KEY, TRUE);\n } else if (arg.equals(\"--import-bgp\")) {\n globalProps.put(TypedProperties.CLI_IMPORT_BGP_KEY, TRUE);\n } else if (arg.equals(\"--update-netname\")) {\n globalProps.put(TypedProperties.CLI_UPDATE_NETNAME_KEY, TRUE);\n } else if (arg.equals(\"--add-addresses\") || arg.equals(\"--delete-addresses\")) {\n if (arg.equals(\"--delete-addresses\")) {\n globalProps.put(TypedProperties.CLI_DELETE_ADDRESSES_KEY, TRUE);\n } else {\n globalProps.put(TypedProperties.CLI_ADD_ADDRESSES_KEY, TRUE);\n }\n ++i;\n if ((i < args.length) && !args[i].startsWith(\"-\")) {\n globalProps.put(TypedProperties.CLI_ADDRESSES_FILE_KEY, args[i]);\n } else {\n throw new CommandLineParseException(\"Missing address file to argument \" + arg);\n }\n } else if (arg.equals(\"--create-rss\")) {\n globalProps.put(TypedProperties.CLI_CREATE_STATS_RSS_KEY, TRUE);\n } else if (arg.equals(\"--create-xml\")) {\n // --create-xml is deprecated. Use --create-reports instead. \n globalProps.put(TypedProperties.CLI_CREATE_FLASH_XML_KEY, TRUE);\n } else if (arg.equals(\"--create-reports\")) {\n globalProps.put(TypedProperties.CLI_CREATE_REPORTS_KEY, TRUE);\n } else if (arg.equals(\"--create-report\")) {\n ++i;\n if (i == args.length) {\n throw new CommandLineParseException(\"Missing argument to \" + arg);\n }\n String className = args[i];\n try {\n Class<?> reportGeneratorClass = Class.forName(className);\n IReportGenerator reportGenerator = (IReportGenerator)reportGeneratorClass.newInstance();\n } catch (Exception e) {\n // ClassNotFoundException, InstantiationException, IllegalAccessException\n String msg = \"Argument for --create-report must be a Java-class that implements IReportGenerator: \" + className;\n throw new MegatronException(msg, e);\n }\n globalProps.put(TypedProperties.CLI_CREATE_REPORT_KEY, className);\n } else if (arg.equals(\"--ui-org\")) {\n globalProps.put(TypedProperties.CLI_UI_ORGANIZATIONS, TRUE); \n } else if (arg.equals(\"--mail-dry-run\") || arg.equals(\"-1\")) {\n globalProps.put(TypedProperties.CLI_MAIL_DRY_RUN_KEY, TRUE);\n } else if (arg.equals(\"--mail-dry-run2\") || arg.equals(\"-2\")) {\n globalProps.put(TypedProperties.CLI_MAIL_DRY_RUN2_KEY, TRUE);\n } else if (arg.equals(\"--mail\") || arg.equals(\"-m\")) {\n globalProps.put(TypedProperties.CLI_MAIL_KEY, TRUE);\n } else if (arg.equals(\"--use-org2\") || arg.equals(\"-b\")) {\n globalProps.put(TypedProperties.CLI_USE_ORG2_KEY, TRUE);\n } else {\n throw new CommandLineParseException(\"Unrecognized option: \" + arg);\n }\n } else {\n File file = new File(arg);\n if (!file.canRead()) {\n throw new MegatronException(\"Cannot read input file: \" + file.getAbsolutePath());\n }\n inputFiles.add(arg);\n }\n }\n }\n\n\n private List<File> listJobTypeFiles() throws MegatronException {\n String dirStr = globalProps.get(JOB_TYPE_CONFIG_DIR_KEY);\n if (StringUtil.isNullOrEmpty(dirStr)) {\n throw new MegatronException(\"Job-type config dir not specified in global properties.\");\n }\n File file = new File(dirStr);\n File[] files = file.listFiles(new FileFilter() {\n @Override\n public boolean accept(File pathname) {\n return pathname.getName().endsWith(\".properties\");\n }\n });\n if (files == null) {\n throw new MegatronException(\"Cannot list job-type config files in directory: \" + file.getAbsolutePath());\n }\n\n List<File> result = new ArrayList<File>(Arrays.asList(files));\n return result;\n }\n\n}", "public class TypedProperties {\n // Keys for CLI arguments. \n public static final String CLI_SLURP_KEY = \"cli.slurp\";\n public static final String CLI_EXPORT_KEY = \"cli.export\";\n public static final String CLI_DELETE_KEY = \"cli.delete\"; \n public static final String CLI_DELETE_ALL_KEY = \"cli.deleteAll\"; \n public static final String CLI_JOB_KEY = \"cli.job\";\n public static final String CLI_JOB_TYPE_KEY = \"cli.jobType\";\n public static final String CLI_OUTPUT_DIR_KEY = \"cli.outputDir\";\n public static final String CLI_ID_KEY = \"cli.id\";\n public static final String CLI_PRIO_KEY = \"cli.prio\"; \n public static final String CLI_LIST_PRIOS_KEY = \"cli.listPrios\";\n public static final String CLI_LIST_JOBS_KEY = \"cli.listJobs\";\n public static final String CLI_WHOIS_KEY = \"cli.whois\"; \n public static final String CLI_DAYS_IN_LIST_JOBS_KEY = \"cli.daysInListJobs\";\n public static final String CLI_JOB_INFO_KEY = \"cli.jobInfo\";\n public static final String CLI_NO_DB_KEY = \"cli.noDb\";\n public static final String CLI_STDOUT_KEY = \"cli.stdout\";\n public static final String CLI_IMPORT_CONTACTS_KEY = \"cli.importContacts\";\n public static final String CLI_IMPORT_BGP_KEY = \"cli.importBgp\";\n public static final String CLI_UPDATE_NETNAME_KEY = \"cli.updateNetname\";\n public static final String CLI_ADD_ADDRESSES_KEY = \"cli.addAddresses\";\n public static final String CLI_DELETE_ADDRESSES_KEY = \"cli.deleteAddresses\";\n public static final String CLI_ADDRESSES_FILE_KEY = \"cli.addressFileKey\";\n public static final String CLI_CREATE_STATS_RSS_KEY = \"cli.createStatsRss\";\n public static final String CLI_CREATE_FLASH_XML_KEY = \"cli.createFlashXml\";\n public static final String CLI_CREATE_REPORTS_KEY = \"cli.createReports\";\n public static final String CLI_CREATE_REPORT_KEY = \"cli.createReport\"; \n public static final String CLI_UI_ORGANIZATIONS = \"cli.uiOrganizations\"; \n public static final String CLI_MAIL_DRY_RUN_KEY = \"cli.mailDryRun\";\n public static final String CLI_MAIL_DRY_RUN2_KEY = \"cli.mailDryRun2\";\n public static final String CLI_MAIL_KEY = \"cli.mail\";\n public static final String CLI_USE_ORG2_KEY = \"cli.useOrg2\";\n\n private static final Logger log = Logger.getLogger(TypedProperties.class);\n\n /** Strings that is converted to \"true\" (case insensitive). */\n private static final String[] TRUE_STRINGS = { \"1\", \"true\", \"on\" };\n\n /** Main properies. */\n private Map<String, String> props;\n\n /** Properties to look in if value is missing in props. Starts from the end. May be null. */\n private LinkedList<Map<String, String>> additionalPropsList;\n\n\n /**\n * Constructor.\n *\n * @param props Properties (not null).\n * @param additionalPropsList Properties to look in if value is missing in props. Starts from the end. May be null.\n */\n public TypedProperties(Map<String, String> props, List<Map<String, String>> additionalPropsList) {\n if (props == null) {\n throw new NullPointerException(\"Argument is null: props\");\n }\n\n this.props = props;\n if (additionalPropsList != null) {\n this.additionalPropsList = new LinkedList<Map<String, String>>(additionalPropsList);\n }\n }\n\n \n /**\n * Adds specified additional properties, which will override already \n * defined properties. Use this method to add or modified properties. \n */\n public void addAdditionalProps(Map<String, String> props) {\n this.additionalPropsList.add(props);\n }\n \n \n /**\n * Returns property value for specified key. If property is not found in\n * properties, or in additional properties, specifed default value is\n * returned.\n *\n * @param key name of property.\n * @param defaultValue value returned if property was not found, or in\n * case of exception.\n */\n public String getString(String key, String defaultValue) {\n String result = props.get(key);\n\n if ((result == null) && (additionalPropsList != null)) {\n for (ListIterator<Map<String, String>> iterator = additionalPropsList.listIterator(additionalPropsList.size()); iterator.hasPrevious(); ) {\n Map<String, String> map = iterator.previous();\n result = map.get(key);\n if (result != null) {\n break;\n }\n }\n }\n\n return (result != null) ? result : defaultValue;\n }\n\n\n /**\n * Returns string array for specified key.<p>\n * Format in properties file:<pre>\n * name.0=value0\n * name.1=value1\n * [...]\n * </pre>\n *\n * @param key name of property.\n * @param defaultValue value returned if property was not found.\n */\n public String[] getStringList(String key, String[] defaultValue) {\n String[] result = null;\n\n // find map that contains list\n Map<String, String> map = null;\n if (props.containsKey(key + \".0\") || props.containsKey(key + \".1\")) {\n map = props;\n } else if (additionalPropsList != null) {\n for (ListIterator<Map<String, String>> iterator = additionalPropsList.listIterator(additionalPropsList.size()); iterator.hasPrevious(); ) {\n Map<String, String> candidateMap = iterator.previous();\n if (candidateMap.containsKey(key + \".0\") || candidateMap.containsKey(key + \".1\")) {\n map = candidateMap;\n break;\n }\n }\n }\n\n // create result from list in map\n if (map != null) {\n List<String> resultList = new ArrayList<String>();\n int i = map.containsKey(key + \".0\") ? 0 : 1;\n while (true) {\n String value = map.get(key + \".\" + Integer.toString(i++));\n if (value != null) {\n resultList.add(value);\n } else {\n break;\n }\n }\n result = resultList.toArray(new String[resultList.size()]);\n }\n\n return (result != null) ? result : defaultValue;\n }\n\n \n /**\n * Returns string array for property value that is comma separated.\n */\n public String[] getStringListFromCommaSeparatedValue(String key, String[] defaultValue, boolean trim) {\n String str = getString(key, null);\n if (str == null) {\n return defaultValue;\n }\n\n String[] result = str.split(\",\");\n if (result != null) {\n for (int i = 0; i < result.length; i++) {\n result[i] = result[i].trim();\n }\n } else {\n result = defaultValue;\n }\n \n return result;\n }\n\n \n /**\n * @see #getStringList(String, String[])\n */\n public List<NameValuePair> getNameValuePairList(String key, List<NameValuePair> defaultList) {\n List<NameValuePair> result = null;\n\n final String delim = \"=\";\n String[] strList = getStringList(key, null);\n if (strList != null) {\n result = new ArrayList<NameValuePair>(strList.length);\n for (int i = 0; i < strList.length; i++) {\n String[] headTail = StringUtil.splitHeadTail(strList[i], delim, false);\n if (StringUtil.isNullOrEmpty(headTail[0]) || StringUtil.isNullOrEmpty(headTail[1])) {\n String msg = \"Cannot parse NameValuePair-list property: \" + key + \", value: \" + Arrays.toString(strList);\n log.error(msg);\n result = defaultList;\n break;\n }\n result.add(new NameValuePair(headTail[0], headTail[1]));\n }\n }\n\n return result;\n }\n\n\n /**\n * @see #getString(String, String)\n */\n public long getLong(String key, long defaultValue) {\n String longStr = getString(key, null);\n\n long result = defaultValue;\n if (longStr != null) {\n try {\n result = Long.parseLong(longStr.trim());\n } catch (NumberFormatException e) {\n String msg = \"Cannot parse integer property: \" + key + \", value: \" + longStr;\n log.error(msg, e);\n result = defaultValue;\n }\n }\n\n return result;\n }\n\n\n /**\n * @see #getString(String, String)\n */\n public int getInt(String key, int defaultValue) {\n return (int)getLong(key, defaultValue);\n }\n\n\n /**\n * @see #getString(String, String)\n */\n public double getDouble(String key, double defaultValue) {\n String doubleStr = getString(key, null);\n\n double result = defaultValue;\n if (doubleStr != null) {\n try {\n result = Double.parseDouble(doubleStr.trim());\n } catch (NumberFormatException e) {\n String msg = \"Cannot parse decimal number property: \" + key + \", value: \" + doubleStr;\n log.error(msg, e);\n result = defaultValue;\n }\n }\n\n return result;\n }\n\n\n /**\n * @see #getString(String, String)\n */\n public float getFloat(String key, float defaultValue) {\n return (float)getDouble(key, defaultValue);\n }\n\n\n /**\n * @see #getString(String, String)\n */\n public boolean getBoolean(String key, boolean defaultValue) {\n String booleanStr = getString(key, null);\n\n boolean result = false;\n if (booleanStr != null) {\n booleanStr = booleanStr.trim();\n for (int i = 0; i < TRUE_STRINGS.length; i++) {\n if (TRUE_STRINGS[i].equalsIgnoreCase(booleanStr)) {\n result = true;\n break;\n }\n }\n } else {\n result = defaultValue;\n }\n\n return result;\n }\n\n\n /**\n * @see #getString(String, String)\n * @see se.sitic.megatron.util.DateUtil#DATE_TIME_FORMAT_WITH_SECONDS\n */\n public Date getDate(String key, String format, Date defaultValue) {\n String dateStr = getString(key, null);\n\n Date result = defaultValue;\n if (dateStr != null) {\n try {\n result = DateUtil.parseDateTime(format, dateStr);\n } catch (ParseException e) {\n String msg = \"Cannot parse date property: \" + key + \", value: \" + dateStr;\n log.error(msg, e);\n result = defaultValue;\n }\n }\n\n return result;\n }\n\n\n /**\n * Returns true if specified property exists.\n *\n * @param key name of property.\n */\n public boolean existsProperty(String key) {\n return (getString(key, null) != null);\n }\n\n \n /**\n * Returns all property keys. \n */\n public Set<String> keySet() {\n Set<String> result = new HashSet<String>();\n\n result.addAll(props.keySet());\n for (Iterator<Map<String, String>> iterator = additionalPropsList.iterator(); iterator.hasNext(); ) {\n result.addAll(iterator.next().keySet());\n }\n return result;\n }\n\n \n /**\n * Returns CLI switch: --slurp\n */\n public boolean isSlurp() {\n return getBoolean(CLI_SLURP_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --export\n */\n public boolean isExport() {\n return getBoolean(CLI_EXPORT_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --delete\n */\n public boolean isDelete() {\n return getBoolean(CLI_DELETE_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --delete-all\n */\n public boolean isDeleteAll() {\n return getBoolean(CLI_DELETE_ALL_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --job\n */\n public String getJob() {\n return getString(CLI_JOB_KEY, \"\");\n }\n\n \n /**\n * Returns CLI switch: --job-type\n */\n public String getJobType() {\n return getString(CLI_JOB_TYPE_KEY, \"\");\n }\n\n \n /**\n * Returns CLI switch: --output-dir\n */\n public String getOutputDir() {\n String result = getString(CLI_OUTPUT_DIR_KEY, \"\");\n if (result.length() == 0) {\n result = getString(AppProperties.OUTPUT_DIR_KEY, \"tmp/export\");\n }\n return result;\n }\n\n \n /**\n * Returns CLI switch: --id\n */\n public String getParentTicketId() {\n return getString(CLI_ID_KEY, \"\");\n }\n\n \n /**\n * Returns CLI switch: --prio\n */\n public String getPrio() {\n return getString(CLI_PRIO_KEY, \"\");\n }\n\n \n /**\n * Returns CLI switch: --list-prios\n */\n public boolean isListPrios() {\n return getBoolean(CLI_LIST_PRIOS_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --list-jobs\n */\n public boolean isListJobs() {\n return getBoolean(CLI_LIST_JOBS_KEY, false);\n }\n\n \n /**\n * Returns no of days (if specified) for --list-jobs. \n */\n public int getDaysInListJobs() {\n int defaultVal = 2;\n String val = getString(CLI_DAYS_IN_LIST_JOBS_KEY, defaultVal + \"\");\n try {\n return Integer.parseInt(val);\n } catch (NumberFormatException e) {\n log.error(\"Cannot not parse --list-jobs integer value: \" + val);\n return defaultVal;\n }\n }\n\n \n /**\n * Returns CLI switch: --job-info\n */\n public boolean isJobInfo() {\n return getBoolean(CLI_JOB_INFO_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --whois\n */\n public boolean isWhois() {\n return getBoolean(CLI_WHOIS_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --no-db\n */\n public boolean isNoDb() {\n return getBoolean(CLI_NO_DB_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --stdout\n */\n public boolean isStdout() {\n return getBoolean(CLI_STDOUT_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --import-contacts\n */\n public boolean isImportContacts() {\n return getBoolean(CLI_IMPORT_CONTACTS_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --import-bgp\n */\n public boolean isImportBgp() {\n return getBoolean(CLI_IMPORT_BGP_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --update-netname\n */\n public boolean isUpdateNetname() {\n return getBoolean(CLI_UPDATE_NETNAME_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --add-addresses\n */\n public boolean isAddAddresses() {\n return getBoolean(CLI_ADD_ADDRESSES_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --delete-addresses\n */\n public boolean isDeleteAddresses() {\n return getBoolean(CLI_DELETE_ADDRESSES_KEY, false);\n }\n\n \n /**\n * Returns address file for CLI switch --add-addresses or --delete-addresses. \n */\n public String getAddressesFile() {\n return getString(CLI_ADDRESSES_FILE_KEY, \"\");\n }\n\n \n /**\n * Returns CLI switch: --create-rss\n */\n public boolean isCreateStatsRss() {\n return getBoolean(CLI_CREATE_STATS_RSS_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --create-xml\n * <p>\n * --create-xml is deprecated. Use --create-reports instead.\n */\n public boolean isCreateFlashXml() {\n return getBoolean(CLI_CREATE_FLASH_XML_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --create-reports\n */\n public boolean isCreateReports() {\n return getBoolean(CLI_CREATE_REPORTS_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --create-report\n */\n public String getCreateReport() {\n return getString(CLI_CREATE_REPORT_KEY, null);\n }\n\n \n /**\n * Returns CLI switch: --ui-org\n */\n public boolean isUiOrg() {\n return getBoolean(CLI_UI_ORGANIZATIONS, false);\n }\n\n\n /**\n * Returns CLI switch: --mail-dry-run\n */\n public boolean isMailDryRun() {\n return getBoolean(CLI_MAIL_DRY_RUN_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --mail-dry-run2\n */\n public boolean isMailDryRun2() {\n return getBoolean(CLI_MAIL_DRY_RUN2_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --mail\n */\n public boolean isMail() {\n return getBoolean(CLI_MAIL_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --use-org2\n */\n public boolean isUseOrg2() {\n return getBoolean(CLI_USE_ORG2_KEY, false);\n }\n\n}", "public class Organization extends BaseOrganization {\n private static final long serialVersionUID = 1L;\n\n /*[CONSTRUCTOR MARKER BEGIN]*/\n public Organization () {\n super();\n }\n\n /**\n * Constructor for primary key\n */\n public Organization (java.lang.Integer id) {\n super(id);\n }\n\n /**\n * Constructor for required fields\n */\n public Organization (\n java.lang.Integer id,\n java.lang.String name,\n boolean enabled,\n java.lang.Long created,\n java.lang.Long lastModified,\n java.lang.String modifiedBy,\n boolean autoUpdateMatchFields) {\n\n super (\n id,\n name,\n enabled,\n created,\n lastModified,\n modifiedBy, \n autoUpdateMatchFields);\n }\n\n /*[CONSTRUCTOR MARKER END]*/\n\n\n // Overloaded method from the base class that adds organization id to the Contact.\n @Override\n public void addToContacts (se.sitic.megatron.entity.Contact contact) {\n if (null == getContacts()) setContacts(new java.util.TreeSet<se.sitic.megatron.entity.Contact>());\n\n contact.setOrganizationId(this.getId()); \n super.addToContacts(contact); \n } \n // Overloaded method from the base class that adds organization id to the IP-range.\n @Override\n public void addToIpRanges (se.sitic.megatron.entity.IpRange ipRange) {\n if (null == getIpRanges()) setIpRanges(new java.util.TreeSet<se.sitic.megatron.entity.IpRange>());\n\n ipRange.setOrganizationId(this.getId()); \n super.addToIpRanges(ipRange); \n }\n // Overloaded method from the base class that adds organization id to the DomainName.\n @Override\n public void addToDomainNames (se.sitic.megatron.entity.DomainName domainName) {\n if (null == getDomainNames()) setDomainNames(new java.util.TreeSet<se.sitic.megatron.entity.DomainName>());\n\n domainName.setOrganizationId(this.getId());\n super.addToDomainNames(domainName); \n }\n // Overloaded method from the base class that adds organization id to the ASNumber.\n @Override\n public void addToASNumbers (se.sitic.megatron.entity.ASNumber asNumber) {\n if (null == getASNumbers()) setASNumbers(new java.util.TreeSet<se.sitic.megatron.entity.ASNumber>());\n\n asNumber.setOrganizationId(this.getId());\n super.addToASNumbers(asNumber);\n }\n \n // Returning all enabled email addresses\n public String getEmailAddresses(){ \n return this.getEmailAddresses(null, true);\n }\n\n // This method returns all email addresses for the organization that matches the given email type and \n // the enabledOnly flag. If the email type is null or empty, all addresses matching the enabledOnly\n // flag are returned.\n\n public String getEmailAddresses(String emailType, boolean enabledOnly){\n\n java.util.Set<se.sitic.megatron.entity.Contact> allContacts = getContacts();\n java.util.Set<String> addresses = new java.util.TreeSet<String>(); \n\n for (se.sitic.megatron.entity.Contact contact : allContacts) {\n if (contact.isEnabled() == true || enabledOnly == false) {\n if (emailType == null) {\n addresses.add(contact.getEmailAddress());\n }\n else if (contact.getEmailType().toLowerCase().equals(emailType.toLowerCase())) { \n addresses.add(contact.getEmailAddress()); \n } \n }\n }\n if (addresses.isEmpty()) {\n return \"\";\n }\n else {\n String emails = java.util.Arrays.toString(addresses.toArray()); \n return emails.substring(1, emails.length()-1);\n }\n }\n}", "public abstract class Constants {\n\n /** Line break in files etc. */\n public static final String LINE_BREAK = \"\\n\";\n\n /** UTF-8 character-set in Java core API. */\n public static final String UTF8 = \"UTF-8\";\n\n /** ISO-8859 character-set in Java core API. */\n public static final String ISO8859 = \"ISO-8859-1\";\n\n /** MIME-type for plain text. */\n public static final String MIME_TEXT_PLAIN = \"text/plain\";\n \n /** Comments in config files starts with this string. */\n public static final String CONFIG_COMMENT_PREFIX = \"#\";\n\n /** Hash algoritm to use. */\n public static final String DIGEST_ALGORITHM = \"md5\";\n\n /** Job type name to use when name is missing in the job_type table. */\n public static final String DEFAULT_JOB_TYPE = \"default\";\n \n // Values for the property filter.countryCodeFilter.organizationToFilter\n // and filter.asnFilter.organizationToFilter\n public static final String ORGANIZATION_PRIMARY = \"primary\";\n public static final String ORGANIZATION_SECONDARY = \"secondary\";\n public static final String ORGANIZATION_BOTH = \"both\";\n\n // Additional format strings for parser.timestampFormat.\n public static final String TIME_STAMP_FORMAT_EPOCH_IN_SEC = \"epochInSec\";\n public static final String TIME_STAMP_FORMAT_EPOCH_IN_MS = \"epochInMs\";\n public static final String TIME_STAMP_FORMAT_WINDOWS_EPOCH = \"windowsEpoch\";\n \n}", "public abstract class IpAddressUtil {\n private static final Logger log = Logger.getLogger(IpAddressUtil.class);\n private static final int HOST_NAME_CACHE_MAX_ENTRIES = 2048;\n \n private static Map<Long, String> hostNameCache;\n private static boolean useDnsJava;\n private static boolean useSimpleResolver; \n private static SimpleResolver simpleResolver;\n \n private static final Matcher IP_ADDRESS_MATCHER = Pattern.compile(\"(\\\\d{1,3})\\\\.(\\\\d{1,3})\\\\.(\\\\d{1,3})\\\\.(\\\\d{1,3})\").matcher(\"\");\n \n \n static {\n TypedProperties globalProps = AppProperties.getInstance().getGlobalProperties();\n\n if (globalProps.existsProperty(AppProperties.USE_DNS_JAVA_KEY) && !globalProps.existsProperty(AppProperties.DNS_JAVA_USE_DNS_JAVA_KEY)) {\n // use deprecated property\n useDnsJava = globalProps.getBoolean(AppProperties.USE_DNS_JAVA_KEY, true);\n } else {\n useDnsJava = globalProps.getBoolean(AppProperties.DNS_JAVA_USE_DNS_JAVA_KEY, true);\n }\n if (useDnsJava) {\n String dnsServers = globalProps.getString(AppProperties.DNS_JAVA_DNS_SERVERS_KEY, null);\n if (dnsServers != null) {\n System.getProperties().put(\"dns.server\", dnsServers);\n }\n int timeOut = globalProps.getInt(AppProperties.DNS_JAVA_TIME_OUT_KEY, 4);\n useSimpleResolver = globalProps.getBoolean(AppProperties.DNS_JAVA_USE_SIMPLE_RESOLVER_KEY, true);\n if (useSimpleResolver) {\n try {\n simpleResolver = new SimpleResolver();\n simpleResolver.setTimeout(timeOut);\n } catch (UnknownHostException e) {\n log.error(\"Cannot initialize DNS service (SimpleResolver). Bad DNS server?\", e);\n }\n }\n Lookup.getDefaultResolver().setTimeout(timeOut);\n } \n \n hostNameCache = Collections.synchronizedMap(new LinkedHashMap<Long, String>(HOST_NAME_CACHE_MAX_ENTRIES, .75F, true) {\n private static final long serialVersionUID = 1L;\n\n @Override\n protected boolean removeEldestEntry(Map.Entry<Long, String> eldest) {\n return size() > HOST_NAME_CACHE_MAX_ENTRIES;\n }\n });\n }\n\n \n /**\n * Converts specified IP-range as a string to numeric values.\n * <p>\n * Supported formats:<ul>\n * <li>192.121.218.4\n * <li>192.121.218.0/20\n * <li>192.121.x.x\n * <li>192.121.218.0-255\n * <li>192.121.218.0-192.121.220.255\n * </li>\n * \n * @return IP-range in an array with two elements (start address, end address).\n */\n public static long[] convertIpRange(String ipRange) throws MegatronException {\n // param check\n if (StringUtil.isNullOrEmpty(ipRange) || (ipRange.trim().length() < \"0.0.0.0\".length())) {\n throw new MegatronException(\"IP-range is null or too small: \" + ipRange);\n }\n \n if (ipRange.toLowerCase().contains(\"x\")) {\n ipRange = expandWildCardOctets(ipRange.toLowerCase().trim(), \"x\");\n }\n \n long[] result = null;\n try {\n if (ipRange.contains(\"/\")) {\n // format: 192.121.218.0/20\n result = convertBgpPrefix(ipRange, 32);\n } else if (ipRange.contains(\"-\")) {\n result = new long[2];\n String[] headTail = StringUtil.splitHeadTail(ipRange.trim(), \"-\", false);\n if ((headTail[0].length() == 0) || (headTail[1].length() == 0)) {\n throw new MegatronException(\"Invalid format for IP-range: \" + ipRange);\n }\n if (headTail[1].contains(\".\")) {\n // format: 192.121.218.0-192.121.220.255\n result[0] = convertIpAddress(headTail[0]);\n result[1] = convertIpAddress(headTail[1]);\n } else {\n // format: 192.121.218.0-255\n String[] ipAddressHeadTail = StringUtil.splitHeadTail(headTail[0].trim(), \".\", true);\n if ((ipAddressHeadTail[0].length() == 0) || (ipAddressHeadTail[1].length() == 0)) {\n throw new MegatronException(\"Invalid start IP-address in IP-range: \" + ipRange);\n }\n String endIpAddress = ipAddressHeadTail[0] + \".\" + headTail[1];\n result[0] = convertIpAddress(headTail[0]);\n result[1] = convertIpAddress(endIpAddress);\n }\n } else {\n // format: 192.121.218.4\n result = new long[2];\n result[0] = convertIpAddress(ipRange);\n result[1] = convertIpAddress(ipRange);\n }\n } catch (UnknownHostException e) {\n throw new MegatronException(\"Cannot convert IP-address in IP-range: \" + ipRange, e);\n }\n \n // check range\n if (result[0] > result[1]) {\n throw new MegatronException(\"Start address is greater than end address in IP-range: \" + ipRange);\n }\n \n return result;\n }\n\n \n /**\n * As convertIpRange(String) but with the option to expand trailing \n * zero octets.\n * \n * @param expandZeroOctets expand trailing zero octets? If true, e.g. \n * \"202.131.0.0\" will be expanded to \"202.131.0.0/16\".\n */\n public static long[] convertIpRange(String ipRange, boolean expandZeroOctets) throws MegatronException {\n if (!expandZeroOctets) {\n return convertIpRange(ipRange);\n }\n \n // param check\n if (StringUtil.isNullOrEmpty(ipRange) || (ipRange.trim().length() < \"0.0.0.0\".length())) {\n throw new MegatronException(\"IP-range is null or too small: \" + ipRange);\n }\n\n if (ipRange.contains(\".0\")) {\n ipRange = expandWildCardOctets(ipRange, \"0\");\n } else if (ipRange.contains(\".000\")) {\n ipRange = expandWildCardOctets(ipRange, \"000\");\n }\n \n return convertIpRange(ipRange);\n }\n\n \n /**\n * Converts a BGP-prefix to an IP-range.\n * \n * @param bgpPrefix may include slash or not. Example: \"202.88.48.0/20\" or \"202.131.0.0\".\n * \n * @return IP-range in an array with two elements (start address, end address).\n */\n public static long[] convertBgpPrefix(String bgpPrefix) throws MegatronException {\n return convertBgpPrefix(bgpPrefix, 24);\n }\n \n\n /**\n * Converts specified integer IP-address to an InetAddress-object.\n * \n * @throws UnknownHostException if specified IP-address is invalid.\n */\n public static InetAddress convertIpAddress(long ipAddress) throws UnknownHostException {\n // How to convert ip-number to integer:\n // http://www.aboutmyip.com/AboutMyXApp/IP2Integer.jsp\n \n // ff.ff.ff.ff = 256*16777216 + 256*65536 + 256*256 + 256 = 4311810304\n if ((ipAddress <= 0L) || (ipAddress >= 4311810304L)) {\n throw new UnknownHostException(\"IP-address out of range: \" + ipAddress);\n }\n \n byte[] ip4Address = convertLongAddressToBuf(ipAddress);\n return InetAddress.getByAddress(ip4Address);\n }\n\n \n /**\n * Converts specified integer IP-address in the format XX.XX.XX.XX to an InetAddress-object.\n * \n * @throws UnknownHostException if specified IP-address is invalid.\n */\n public static long convertIpAddress(String ipAddress) throws UnknownHostException {\n if (ipAddress == null) {\n throw new UnknownHostException(\"Invalid IP-address; is null.\");\n }\n \n String[] tokens = ipAddress.trim().split(\"\\\\.\");\n if ((tokens == null) || (tokens.length != 4)) {\n throw new UnknownHostException(\"Invalid IP-address: \" + ipAddress);\n }\n \n long result = 0L;\n long factor = 1;\n for (int i = 3; i >= 0; i--) {\n try {\n int intToken = Integer.parseInt(tokens[i]);\n if ((intToken < 0) || (intToken > 255)) {\n throw new UnknownHostException(\"Invalid IP-address: \" + ipAddress);\n }\n result += intToken*factor;\n factor = factor << 8;\n } catch (NumberFormatException e) {\n throw new UnknownHostException(\"Invalid IP-address: \" + ipAddress);\n }\n }\n \n return result;\n }\n\n\n /**\n * Converts specified integer IP-address to its string representation.\n * \n * @param includeHostName will do a reverse name lookup and append host \n * name to result if lookup successful.\n * \n * @return ip-adress, or empty string if specified address is invalid or\n * in case of an exception. Example: \"130.239.8.25 (wsunet.umdc.umu.se)\". \n */\n public static String convertIpAddress(long ipAddress, boolean includeHostName) {\n if (ipAddress == 0L) {\n return \"\";\n }\n\n String hostAddress = null;\n try {\n hostAddress = convertIpAddressToString(ipAddress);\n } catch (UnknownHostException e) {\n String msg = \"Cannot convert IP-address (address probably invalid): \" + ipAddress;\n log.warn(msg, e);\n hostAddress = \"\";\n }\n \n String hostName = null;\n if (includeHostName) {\n hostName = reverseDnsLookupInternal(ipAddress, true);\n }\n \n StringBuilder result = new StringBuilder(256); \n result.append(hostAddress);\n if (!StringUtil.isNullOrEmpty(hostName)) {\n result.append(\" (\").append(hostName).append(\")\");\n }\n\n return result.toString();\n }\n\n \n /**\n * Converts specified integer IP-address and mask the two last octets.\n * <p>Note: This method is not thread-safe.\n * \n * @return ip-adress, or empty string if specified address is invalid or\n * in case of an exception. Example: \"130.239.x.x\". \n */\n public static String convertAndMaskIpAddress(long ipAddress) {\n String result = convertIpAddress(ipAddress, false);\n if (!StringUtil.isNullOrEmpty(result)) {\n // keep first two numbers in ip-address\n String replaceStr = \"$1.$2.x.x\";\n IP_ADDRESS_MATCHER.reset(result);\n String resultMasked = IP_ADDRESS_MATCHER.replaceFirst(replaceStr);\n if (result.equals(resultMasked)) {\n // may be some error if not masked at all; mask everything\n resultMasked = \"x.x.x.x\";\n }\n // log.debug(\"Masked IP-address: \" + result + \" --> \" + resultMasked);\n result = resultMasked;\n }\n \n return result;\n }\n \n \n /**\n * Returns IP-address as an integer for specified hostname, or 0L\n * if lookup fails.\n */\n public static long dnsLookup(String hostname) {\n long result = 0L;\n String hostAddress = null;\n\n try {\n hostname = hostname.trim();\n InetAddress inetAddress = null;\n if (useDnsJava) {\n inetAddress = Address.getByName(hostname);\n } else {\n inetAddress = InetAddress.getByName(hostname);\n }\n hostAddress = inetAddress.getHostAddress();\n } catch (UnknownHostException e) {\n String msg = \"DNS lookup failed for hostname: \" + hostname;\n log.debug(msg, e);\n }\n \n try {\n if (hostAddress != null) {\n result = convertIpAddress(hostAddress);\n }\n } catch (UnknownHostException e) {\n String msg = \"Connot convert IP-address to an integer: \" + hostAddress;\n log.warn(msg, e);\n }\n\n return result;\n }\n\n \n /**\n * Returns hostname from specified ip-address, or empty string\n * if lookup fails. \n */\n public static String reverseDnsLookup(long ipAddress) {\n return reverseDnsLookupInternal(ipAddress, true);\n }\n\n \n /**\n * As reverseDnsLookup(long), but without cache.\n */\n public static String reverseDnsLookupWithoutCache(long ipAddress) {\n return reverseDnsLookupInternal(ipAddress, false);\n }\n\n \n private static String reverseDnsLookupInternal(long ipAddress, boolean useCache) {\n String result = null;\n \n // -- Cache lookup\n Long cacheKey = null;\n if (useCache) {\n cacheKey = new Long(ipAddress);\n result = hostNameCache.get(cacheKey);\n if (result != null) {\n // log.debug(\"Cache hit: \" + ipAddress + \":\" + result);\n return result;\n }\n }\n \n // -- Reverse DNS lookup \n try {\n if (useDnsJava) {\n if (useSimpleResolver) {\n result = reverseDnsLookupUsingDnsJavaSimpleResolver(ipAddress);\n } else {\n result = reverseDnsLookupUsingDnsJavaExtendedResolver(ipAddress);\n }\n } else {\n result = reverseDnsLookupUsingJdk(ipAddress);\n }\n // -- Validate hostname\n validateHostname(result);\n } catch(IOException e) {\n // UnknownHostException, IOException\n result = \"\";\n if (log.isDebugEnabled()) {\n String ipAddressStr = null;\n try {\n ipAddressStr = convertIpAddressToString(ipAddress);\n } catch (UnknownHostException e2) {\n ipAddressStr = Long.toString(ipAddress);\n }\n String msg = \"Reverse DNS lookup failed for IP-address: \" + ipAddressStr;\n log.debug(msg, e);\n }\n }\n \n // -- Add to cache (even empty entries)\n if (useCache) {\n if (log.isDebugEnabled()) {\n String ipAddressStr = null;\n try {\n ipAddressStr = convertIpAddressToString(ipAddress);\n } catch (UnknownHostException e2) {\n ipAddressStr = Long.toString(ipAddress);\n }\n log.debug(\"Adds hostname to cache: \" + ipAddress + \" [\" + ipAddressStr + \"]:\" + result);\n }\n hostNameCache.put(cacheKey, result);\n }\n \n return result;\n }\n\n \n private static String reverseDnsLookupUsingJdk(long ipAddress) throws UnknownHostException {\n // -- Convert ip-address (long) to string\n InetAddress inetAddress = convertIpAddress(ipAddress);\n String hostAddress = inetAddress.getHostAddress();\n if (StringUtil.isNullOrEmpty(hostAddress)) {\n throw new UnknownHostException(\"Cannot convert IP-address: \" + ipAddress);\n }\n\n // -- Reverse DNS lookup \n log.debug(\"Making a reverse DNS lookup for \" + ipAddress);\n String result = inetAddress.getHostName();\n log.debug(\"Lookup result: \" + result);\n if (StringUtil.isNullOrEmpty(result) || result.equals(hostAddress)) {\n throw new UnknownHostException(\"Reverse DNS lookup failed: \" + hostAddress);\n }\n return result;\n }\n\n \n private static String reverseDnsLookupUsingDnsJavaExtendedResolver(long ipAddress) throws UnknownHostException {\n byte[] address = convertLongAddressToBuf(ipAddress);\n Name name = ReverseMap.fromAddress(InetAddress.getByAddress(address));\n Record[] records = new Lookup(name, Type.PTR).run();\n if (records == null) {\n throw new UnknownHostException();\n }\n String result = ((PTRRecord)records[0]).getTarget().toString();\n // remove trailing \".\"\n result = result.endsWith(\".\") ? result.substring(0, result.length() - 1) : result;\n return result;\n }\n\n \n private static String reverseDnsLookupUsingDnsJavaSimpleResolver(long ipAddress) throws IOException {\n String result = null;\n byte[] address = convertLongAddressToBuf(ipAddress);\n Name name = ReverseMap.fromAddress(InetAddress.getByAddress(address));\n Record record = Record.newRecord(name, Type.PTR, DClass.IN);\n Message query = Message.newQuery(record);\n Message response = simpleResolver.send(query);\n Record[] answers = response.getSectionArray(Section.ANSWER);\n if (answers.length != 0) {\n // If PTR-record exists this will be at index 1 or above (more than one PTR-record may exist)\n Record answer = (answers.length > 1) ? answers[1] : answers[0]; \n result = answer.rdataToString();\n // remove trailing \".\"\n result = result.endsWith(\".\") ? result.substring(0, result.length() - 1) : result;\n } else {\n throw new IOException(\"Empty DNS response.\");\n }\n return result;\n }\n \n \n private static String convertIpAddressToString(long ipAddress) throws UnknownHostException {\n InetAddress inetAddress = convertIpAddress(ipAddress);\n String result = inetAddress.getHostAddress();\n if (StringUtil.isNullOrEmpty(result)) {\n throw new UnknownHostException(\"Cannot convert IP-address: \" + ipAddress);\n }\n return result;\n }\n \n \n private static byte[] convertLongAddressToBuf(long ipAddress) {\n byte[] result = new byte[4];\n result[0] = (byte)((ipAddress >> 24) & 0xFF);\n result[1] = (byte)((ipAddress >> 16) & 0xFF);\n result[2] = (byte)((ipAddress >> 8) & 0xFF);\n result[3] = (byte)((ipAddress >> 0) & 0xFF);\n return result;\n }\n\n \n /**\n * Validates specified hostname.\n * \n * @throws UnknownHostException if hostname contain malicious or invalid content.\n */\n private static void validateHostname(String hostName) throws UnknownHostException {\n // More info: http://en.wikipedia.org/wiki/Hostname\n \n // Valid letters: a..z, A..Z, 0..9, -\n for (int i = 0; i < hostName.length(); i++) {\n char ch = hostName.charAt(i);\n if (!((('a' <= ch) && (ch <= 'z')) || (('A' <= ch) && (ch <= 'Z')) || (('0' <= ch) && (ch <= '9')) || (((ch == '-') || (ch == '.')) && (i > 0)))) {\n throw new UnknownHostException(\"Host name contains illegal character: \" + ch + \". Host name: \" + hostName);\n }\n }\n // Validate total length\n if (hostName.length() > 255) {\n throw new UnknownHostException(\"Host name too long: \" + hostName);\n }\n // Exists empty labels?\n if (hostName.indexOf(\"..\") != -1) {\n throw new UnknownHostException(\"Host name contains an empty label: \" + hostName);\n }\n // Validate label length\n String[] labels = hostName.split(\"\\\\.\");\n for (int i = 0; i < labels.length; i++) {\n if (StringUtil.isNullOrEmpty(labels[i])) {\n throw new UnknownHostException(\"Host name contains an empty label: \" + hostName);\n }\n if (labels[i].length() > 63) {\n throw new UnknownHostException(\"Host name contains an label that is too long: \" + hostName);\n }\n }\n }\n\n \n /**\n * Expands trailing octets that contains specified wildcard. \n * A BGP prefix is returned.\n * <p>\n * Example: (\"202.131.x.x\", \"x\") returns \"202.131.0.0/16\", \n * (\"202.131.101.0\", \"0\") returns \"202.131.101.0/24\".\n */\n private static String expandWildCardOctets(String ipRange, String wildCard) throws MegatronException {\n String result = ipRange;\n int mask = 32;\n boolean wildcardFound = true;\n while (wildcardFound) {\n int lengthBefore = result.length();\n result = StringUtil.removeSuffix(result, \".\" + wildCard);\n wildcardFound = result.length() < lengthBefore;\n if (wildcardFound) {\n mask -= 8;\n }\n }\n if (mask == 32) {\n result = ipRange;\n } else if ((mask < 8) || result.equals(wildCard)) {\n throw new MegatronException(\"Cannot expand wildcard IP-range: \" + ipRange);\n } else {\n String suffix = StringUtil.nCopyString(\".0\", (32 - mask) / 8);\n result = result + suffix + \"/\" + mask;\n }\n \n return result;\n }\n\n \n private static long[] convertBgpPrefix(String bgpPrefix, int maxMask) throws MegatronException {\n // param check\n if (StringUtil.isNullOrEmpty(bgpPrefix) || (bgpPrefix.trim().length() < \"0.0.0.0\".length())) {\n throw new MegatronException(\"BGP-prefix is null or too small: \" + bgpPrefix);\n }\n \n long[] result = new long[2];\n bgpPrefix = bgpPrefix.trim(); \n bgpPrefix = bgpPrefix.endsWith(\"/\") ? bgpPrefix.substring(0, bgpPrefix.length()-1) : bgpPrefix;\n int slashIndex = bgpPrefix.indexOf(\"/\");\n if (slashIndex != -1) {\n // Format: 202.88.48.0/20 (endAddress: 202.88.63.255)\n // 202 . 88 . 48 . 0\n // =\n // 11001010 . 01011000 . 00110000 . 00000000\n // and\n // 11111111 . 11111111 . 11110000 . 00000000 mask with 20 1's; bitMaskHead\n // =\n // 11001010 . 01011000 . 0011\n // or\n // 1111 . 11111111 bitMaskTail\n //\n // 11001010 . 01011000 . 00111111 . 11111111 (= 202.88.63.255)\n \n String startAddressStr = bgpPrefix.substring(0, slashIndex);\n try {\n result[0] = convertIpAddress(startAddressStr);\n } catch (UnknownHostException e) {\n throw new MegatronException(\"Cannot convert IP-address in BGP-prefix: \" + bgpPrefix, e);\n }\n String maskStr = bgpPrefix.substring(slashIndex+1);\n int mask = 0;\n try {\n mask = Integer.parseInt(maskStr);\n } catch (NumberFormatException e) {\n throw new MegatronException(\"Cannot parse mask in BGP-prefix: \" + maskStr + \" (\" + bgpPrefix + \").\", e);\n }\n if ((mask <= 1) || (mask > maxMask)) {\n throw new MegatronException(\"Invalid BGP-prefix mask: \" + mask + \" (\" + bgpPrefix + \").\");\n }\n long bitMaskHead = ((1L << mask) - 1) << (32 - mask);\n long bitMaskTail = (1L << (32 - mask)) - 1;\n result[1] = (result[0] & bitMaskHead) | bitMaskTail; \n } else {\n // Format: 202.131.0.0 (endAddress: 202.131.255.255)\n try {\n result[0] = convertIpAddress(bgpPrefix);\n } catch (UnknownHostException e) {\n throw new MegatronException(\"Cannot convert IP-address in BGP-prefix: \" + bgpPrefix, e);\n }\n // add \"#\" as suffix temporary, e.g. \"202.131.0.0#\"\n String endAddressStr = bgpPrefix + \"#\";\n endAddressStr = StringUtil.replace(endAddressStr, \".0.0.0#\", \".255.255.255#\");\n endAddressStr = StringUtil.replace(endAddressStr, \".0.0#\", \".255.255#\");\n endAddressStr = StringUtil.replace(endAddressStr, \".0#\", \".255#\");\n endAddressStr = endAddressStr.substring(0, endAddressStr.length()-1);\n try {\n result[1] = convertIpAddress(endAddressStr);\n } catch (UnknownHostException e) {\n throw new MegatronException(\"Cannot convert end IP-address in BGP-prefix: \" + bgpPrefix, e);\n }\n }\n return result;\n }\n\n}" ]
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.Logger; import se.sitic.megatron.core.AppProperties; import se.sitic.megatron.core.MegatronException; import se.sitic.megatron.core.TypedProperties; import se.sitic.megatron.entity.Organization; import se.sitic.megatron.util.Constants; import se.sitic.megatron.util.IpAddressUtil;
package se.sitic.megatron.db; public class ImportSystemData { private static final Logger log = Logger.getLogger(ImportSystemData.class);
private TypedProperties props;
1
loehndorf/scengen
src/main/java/scengen/paper/QuantizationGridBench.java
[ "public class Generator {\n\t\n\tstatic long _seed = 191;\n\t\n\t/**\n\t * <p>Generate a reduced set of scenarios from a normal, log-normal, or uniform, probability distribution with given parameters.</br>\n\t * Use the following arguments to run the program:</p>\n\t * <ul><li>dist=(Normal, Lognormal, Student, Uniform)</li>\n\t * <li>dim=int</li>\n\t * <li>mean=double,...,double</li>\n\t * <li>cov=double,...double</li>\n\t * <li>scen=int</li>\n\t * <li>seed=int</li>\n\t * <li>alt uniform: min=double,...,double max=double,...,double correl=double,...double</li>\n\t * <li>alt student: mean=double,...,double scale=double,...,double df=double,...,double correl=double,...double</li>\n\t * <li>optional: method=(MonteCarlo, QuasiMonteCarlo, MomentMatching, QuantizationGrids, QuantizationLearning, VoronoiCellSampling)</li>\n\t * <p>Example usage to generate 20 scenarios from a 2-dimensional normal distribution with mean (5,10) and \n\t * covariance ((50,25),(25,100)) using quasi Quasi-Monte Carlo as scenario reduction method:</br>\n\t * 'java -jar scengen.jar dist=Normal dim=2 mean=5,10 cov=50,25,25,100 scen=20 method=QuasiMonteCarlo'</p>\n\t * @param args \n\t */\n\tpublic static void main (String... args) {\n\t\t_seed = new Xorshift().nextLong();\n\t\tMap<String,String> table = makeTable(args);\n\t\tif (!table.containsKey(\"dist\"))\n\t\t\tthrow new IllegalArgumentException(\"Use keyword 'dist=Lognormal,Normal,Student,Uniform' to specify distribution.\");\n\t\tif (!table.containsKey(\"dim\"))\n\t\t\tthrow new IllegalArgumentException(\"Use keyword 'dim=int' to define distribution dimension.\");\n\t\tif (!table.containsKey(\"scen\"))\n\t\t\tthrow new IllegalArgumentException(\"Use keyword 'scen=int' to specify the number of scenarios.\");\n\t\tif (!((table.containsKey(\"mean\") && table.containsKey(\"cov\")) || (table.get(\"dist\").matches(\"Uniform\") && table.containsKey(\"min\") && table.containsKey(\"max\") && table.containsKey(\"correl\")) || (table.get(\"dist\").matches(\"Student\") && table.containsKey(\"mean\") && table.containsKey(\"scale\") && table.containsKey(\"correl\"))))\n\t\t\tthrow new IllegalArgumentException(\"Use keywords 'mean=double,...double cov=double,...double' to specify distribution parameters.\");\n\t\tString distName = table.get(\"dist\");\n\t\tint dim = Integer.parseInt(table.get(\"dim\"));\n\t\tlong seed = new Xorshift().nextLong();\n\t\tif (table.containsKey(\"seed\"))\n\t\t\tseed = Long.parseLong(table.get(\"seed\"));\n\t\tif (table.containsKey(\"seed\"))\n\t\t\tseed = Integer.parseInt(table.get(\"seed\"));\n\t\tMultivariateNormal dist = null;\n\t\tswitch (distName) {\n\t\tcase \"Normal\": {\n\t\t\t\tString[] smean = table.get(\"mean\").split(\",\");\n\t\t\t\tif (smean.length!=dim)\n\t\t\t\t\tthrow new ArrayIndexOutOfBoundsException(\"Size of a parameter vector does not match distribution dimension.\");\n\t\t\t\tdouble[] mean = new double[dim];\n\t\t\t\tfor (int i=0; i<dim; i++)\n\t\t\t\t\tmean[i] = Double.parseDouble(smean[i]);\n\t\t\t\tString[] scov = table.get(\"cov\").split(\",\");\n\t\t\t\tif (scov.length!=dim*dim)\n\t\t\t\t\tthrow new ArrayIndexOutOfBoundsException(\"Size of a parameter vector does not match distribution dimension.\");\n\t\t\t\tdouble[][]cov = new double[dim][dim];\n\t\t\t\tfor (int i=0; i<dim; i++)\n\t\t\t\t\tfor (int j=0; j<dim; j++)\n\t\t\t\t\t\tcov[i][j] = Double.parseDouble(scov[j+i*dim]);\n\t\t\t\tdist = new MultivariateNormal(mean,cov,new Xorshift(seed));}\n\t\t\t\tbreak;\n\t\tcase \"Lognormal\": {\n\t\t\tString[] smean = table.get(\"mean\").split(\",\");\n\t\t\tif (smean.length!=dim)\n\t\t\t\tthrow new ArrayIndexOutOfBoundsException(\"Size of a parameter vector does not match distribution dimension.\");\n\t\t\tdouble[] mean = new double[dim];\n\t\t\tfor (int i=0; i<dim; i++)\n\t\t\t\tmean[i] = Double.parseDouble(smean[i]);\n\t\t\tString[] scov = table.get(\"cov\").split(\",\");\n\t\t\tif (scov.length!=dim*dim)\n\t\t\t\tthrow new ArrayIndexOutOfBoundsException(\"Size of a parameter vector does not match distribution dimension.\");\n\t\t\tdouble[][]cov = new double[dim][dim];\n\t\t\tfor (int i=0; i<dim; i++)\n\t\t\t\tfor (int j=0; j<dim; j++)\n\t\t\t\t\tcov[i][j] = Double.parseDouble(scov[j+i*dim]);\n\t\t\tdist = new MultivariateLognormal(mean,cov,new Xorshift(seed));}\n\t\t\tbreak;\n\t\tcase \"Student\": {\n\t\t\tif (table.containsKey(\"mean\") && table.containsKey(\"cov\")) {\n\t\t\t\tString[] smean = table.get(\"mean\").split(\",\");\n\t\t\t\tif (smean.length!=dim)\n\t\t\t\t\tthrow new ArrayIndexOutOfBoundsException(\"Size of a parameter vector does not match distribution dimension.\");\n\t\t\t\tdouble[] mean = new double[dim];\n\t\t\t\tfor (int i=0; i<dim; i++)\n\t\t\t\t\tmean[i] = Double.parseDouble(smean[i]);\n\t\t\t\tint[] df = new int[dim];\n\t\t\t\tfor (int i=0; i<dim; i++)\n\t\t\t\t\tdf[i] = 5;\n\t\t\t\tString[] scov = table.get(\"cov\").split(\",\");\n\t\t\t\tif (scov.length!=dim*dim)\n\t\t\t\t\tthrow new ArrayIndexOutOfBoundsException(\"Size of a parameter vector does not match distribution dimension.\");\n\t\t\t\tdouble[][] cov = new double[dim][dim];\n\t\t\t\tfor (int i=0; i<dim; i++)\n\t\t\t\t\tfor (int j=0; j<dim; j++)\n\t\t\t\t\t\tcov[i][j] = Double.parseDouble(scov[j+i*dim]);\n\t\t\t\tdouble[] scale = new double[dim];\n\t\t\t\tfor (int i=0; i<dim; i++) \n\t\t\t\t\tscale[i] = Math.sqrt(cov[i][i]*3./5.);\n\t\t\t\tdist = new MultivariateStudent(mean,scale,getCorrelationMatrix(cov),df,new Xorshift(seed));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tString[] smean = table.get(\"mean\").split(\",\");\n\t\t\t\tif (smean.length!=dim)\n\t\t\t\t\tthrow new ArrayIndexOutOfBoundsException(\"Size of a parameter vector does not match distribution dimension.\");\n\t\t\t\tdouble[] mean = new double[dim];\n\t\t\t\tfor (int i=0; i<dim; i++)\n\t\t\t\t\tmean[i] = Double.parseDouble(smean[i]);\n\t\t\t\tString[] sdf = table.get(\"df\").split(\",\");\n\t\t\t\tif (smean.length!=dim)\n\t\t\t\t\tthrow new ArrayIndexOutOfBoundsException(\"Size of a parameter vector does not match distribution dimension.\");\n\t\t\t\tint[] df = new int[dim];\n\t\t\t\tfor (int i=0; i<dim; i++)\n\t\t\t\t\tdf[i] = Integer.parseInt(sdf[i]);\n\t\t\t\tString[] scov = table.get(\"correl\").split(\",\");\n\t\t\t\tif (scov.length!=dim*dim)\n\t\t\t\t\tthrow new ArrayIndexOutOfBoundsException(\"Size of a parameter vector does not match distribution dimension.\");\n\t\t\t\tdouble[][]cor = new double[dim][dim];\n\t\t\t\tfor (int i=0; i<dim; i++)\n\t\t\t\t\tfor (int j=0; j<dim; j++)\n\t\t\t\t\t\tcor[i][j] = Double.parseDouble(scov[j+i*dim]);\n\t\t\t\tString[] sscale = table.get(\"scale\").split(\",\");\n\t\t\t\tif (sscale.length!=dim)\n\t\t\t\t\tthrow new ArrayIndexOutOfBoundsException(\"Size of a parameter vector does not match distribution dimension.\");\n\t\t\t\tdouble[] scale = new double[dim];\n\t\t\t\tfor (int i=0; i<dim; i++)\n\t\t\t\t\tscale[i] = Double.parseDouble(sscale[i]);\n\t\t\t\tdist = new MultivariateStudent(mean,scale,cor,df,new Xorshift(seed));\n\t\t\t}}\n\t\t\tbreak;\n\t\tcase \"Uniform\": {\n\t\t\tif (table.containsKey(\"mean\") && table.containsKey(\"cov\")) {\n\t\t\t\tString[] smean = table.get(\"mean\").split(\",\");\n\t\t\t\tif (smean.length!=dim)\n\t\t\t\t\tthrow new ArrayIndexOutOfBoundsException(\"Size of a parameter vector does not match distribution dimension.\");\n\t\t\t\tdouble[] mean = new double[dim];\n\t\t\t\tfor (int i=0; i<dim; i++)\n\t\t\t\t\tmean[i] = Double.parseDouble(smean[i]);\n\t\t\t\tString[] scov = table.get(\"cov\").split(\",\");\n\t\t\t\tif (scov.length!=dim*dim)\n\t\t\t\t\tthrow new ArrayIndexOutOfBoundsException(\"Size of a parameter vector does not match distribution dimension.\");\n\t\t\t\tdouble[][]cov = new double[dim][dim];\n\t\t\t\tfor (int i=0; i<dim; i++)\n\t\t\t\t\tfor (int j=0; j<dim; j++)\n\t\t\t\t\t\tcov[i][j] = Double.parseDouble(scov[j+i*dim]);\n\t\t\t\tdist = new MultivariateUniform(mean,cov,new Xorshift(seed));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tString[] smin = table.get(\"min\").split(\",\");\n\t\t\t\tif (smin.length!=dim)\n\t\t\t\t\tthrow new ArrayIndexOutOfBoundsException(\"Size of a parameter vector does not match distribution dimension.\");\n\t\t\t\tdouble[] min = new double[dim];\n\t\t\t\tfor (int i=0; i<dim; i++)\n\t\t\t\t\tmin[i] = Double.parseDouble(smin[i]);\n\t\t\t\tString[] smax = table.get(\"max\").split(\",\");\n\t\t\t\tif (smax.length!=dim)\n\t\t\t\t\tthrow new ArrayIndexOutOfBoundsException(\"Size of a parameter vector does not match distribution dimension.\");\n\t\t\t\tdouble[] max = new double[dim];\n\t\t\t\tfor (int i=0; i<dim; i++)\n\t\t\t\t\tmax[i] = Double.parseDouble(smax[i]);\n\t\t\t\tString[] scorrel = table.get(\"correl\").split(\",\");\n\t\t\t\tif (scorrel.length!=dim*dim)\n\t\t\t\t\tthrow new ArrayIndexOutOfBoundsException(\"Size of a parameter vector does not match distribution dimension.\");\n\t\t\t\tdouble[][]correl = new double[dim][dim];\n\t\t\t\tfor (int i=0; i<dim; i++) {\n\t\t\t\t\tfor (int j=0; j<dim; j++) {\n\t\t\t\t\t\tcorrel[i][j] = Double.parseDouble(scorrel[j+i*dim]);\n\t\t\t\t\t\tif (correl[i][j]>1 || correl[i][j]<-1)\n\t\t\t\t\t\t\tthrow new IllegalArgumentException(\"Correlation matrix for uniform distribution invalid.\");\n\t\t\t\t\t}\n\t\t\t\t\tif (correl[i][i]!=1)\n\t\t\t\t\t\tthrow new IllegalArgumentException(\"Not all diagonal entries of correlation matrix are equal to 1.\");\n\t\t\t\t}\n\t\t\t\tdist = new MultivariateUniform(min,max,correl,new Xorshift(seed));\n\t\t\t}}\n\t\t\tbreak;\n\t\tdefault: \n\t\t\tthrow new IllegalArgumentException(String.format(\"Distribution %s unknown. Use 'Normal', 'Lognormal', or 'Uniform'.\",args[0]));\n\t\t}\n\t\tint numScen = Integer.parseInt(table.get(\"scen\"));\n\t\t//optional parameters\n\t\tMETHOD method = null;\n\t\tif (table.containsKey(\"method\"))\n\t\t\tmethod = METHOD.valueOf(table.get(\"method\"));\n\t\telse {\n\t\t\tif (dim<=2) \n\t\t\t\tmethod = METHOD.QuantizationLearning;\n\t\t\telse \n\t\t\t\tmethod = METHOD.VoronoiCellSampling;\n\t\t}\n\t\tMap<double[],Double> scen = runScenarioGenerator(numScen,method,dist,seed);\n\t\tprintf(\"Multivariate distribution:\\t%s \\n\",dist.getType());\n\t\tprintf(\"Random vector dimenensionality:\\t%s \\n\",dim);\n\t\tprintf(\"Number of scenarios:\\t%s \\n\",numScen);\n\t\tprintf(\"Scenario generation method:\\t%s \\n\",method);\n\t\tprintf(\"Generated scenarios by row:\\n\");\n\t\tprintf(\"probability\");\n\t\tfor (int i=0; i<dim; i++)\n\t\t\tprintf(String.format(\"\\tvalue(%d)\",i));\n\t\tprintf(\"\\n\");\n\t\tfor (double[] x : scen.keySet()) {\n\t\t\tprintf(\"%f\",scen.get(x));\n\t\t\tfor (int i=0; i<dim; i++)\n\t\t\t\tprintf(\"\\t%f\",x[i]);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t}\n\t\n\tstatic Map<String,String> makeTable(String... args) {\n\t\tMap<String,String> map = new HashMap<>();\n\t\tfor (String s : args) {\n\t\t\tString[] ar = s.split(\"=\");\n\t\t\tmap.put(ar[0],ar[1]);\n\t\t}\n\t\treturn map;\n\t}\n\t\n\tstatic void printf(String s, Object... args) {\n\t\tSystem.out.printf(s,args);\n\t}\n\t\n\tpublic static Map<double[],Double> runScenarioGenerator(int numScen, METHOD method, MultivariateDistribution mvDist, long seed) {\n\t\tReductionMethod scenred = null;\n\t\tswitch (method) {\n\t\tcase MomentMatching: \n\t\t\tscenred = new MomentMatching(mvDist.getMean(),mvDist.getCov(),mvDist.getSkewness(),mvDist.getKurtosis(),seed);\n\t\t\tbreak;\n\t\tcase QuasiMonteCarlo: \n\t\t\tscenred = new QuasiMonteCarlo(mvDist);\n\t\t\tbreak;\n\t\tcase QuantizationGrids: \n\t\t\tscenred = new QuantizationGrids(mvDist);\n\t\t\tbreak;\n\t\tcase QuantizationLearning: \n\t\t\tscenred = new QuantizationLearning(mvDist);\n\t\t\tbreak;\n\t\tcase MonteCarlo: \n\t\t\tscenred = new MonteCarlo(mvDist);\n\t\t\tbreak;\n\t\tcase Scenred2:\n\t\t\tscenred = new Scenred2(new MonteCarlo(mvDist).getScenarios(10000),mvDist.getDim());\n\t\t\tbreak;\n\t\tcase VoronoiCellSampling:\n\t\t\tscenred = new VoronoiCellSampling(mvDist);\n\t\t\tbreak;\n\t\t}\n\t\treturn scenred.getScenarios(numScen);\n\t}\n\t\n\tpublic static double[][] getCorrelationMatrix(double[][] covariance) {\n\t\tif (covariance.length!=covariance[0].length)\n\t\t\tthrow new IllegalArgumentException(\"No sqaure matrix.\");\n\t\tint dim = covariance.length;\n\t\tdouble[][] correlation = new double[dim][dim];\n\t\tfor (int i=0; i<dim; i++) {\n\t\t\tcorrelation[i][i] = 1;\n\t\t\tfor (int j=i+1; j<dim; j++) {\n\t\t\t\tcorrelation[i][j] = covariance[i][j]/Math.sqrt(covariance[i][i]*covariance[j][j]);\n\t\t\t\tcorrelation[j][i] = correlation[i][j];\n\t\t\t}\n\t\t}\n\t\treturn correlation;\n\t}\n \t\n\t\n\n\t\n}", "public interface MultivariateDistribution {\n\t\n\tpublic double[] getRealization();\n\t\n\tpublic double[] getRealization(double[] u);\n\t\n\tpublic int getDim();\n\t\n\tpublic List<double[]> getSample(int size);\n\t\n\tpublic void setGenerator(Random generator);\n\t\n\tpublic Random getGenerator();\n\t\n\tpublic double[] getMean();\n\t\n\tpublic double[] getVariance();\n\t\n\tpublic double[][] getCov();\n\t\n\tpublic double[] getSkewness();\n\t\n\tpublic double[] getKurtosis();\n\t\n\tpublic DISTRIBUTION getType();\n\n}", "public class MultivariateNormal implements MultivariateDistribution {\n\t\n\tdouble[][] _chol;\n\tdouble[][] _cov;\n\tdouble[] _var;\n\tdouble[] _mean;\n\tint _dim;\n\tRandom _generator;\n\t\n\tpublic MultivariateNormal(double[] mean, double[][] covariance, Random generator) {\n\t\tif (covariance.length != mean.length || covariance[0].length != mean.length)\n\t throw new IllegalArgumentException(\"Covariance matrix dimensions invalid.\");\n\t\t_mean = mean;\n\t\t_chol = choleskyDecomposition(covariance);\n\t\t_cov = covariance;\n\t\t_dim = mean.length;\n\t\t_var = new double[_dim];\n\t\tfor (int i=0; i<_dim; i++)\n\t\t\t_var[i] = _cov[i][i];\n\t\t_generator = generator;\n\t}\n\t\n\tpublic static void main (String... args) {\n\t\tint dim = 1;\n\t\tdouble[] mean = new double[dim];\n\t\tdouble[][] correl = new double[dim][dim];\n\t\tfor (int i=0; i<dim; i++) {\n\t\t\tmean[i] = 10;\n\t\t\tcorrel[i][i] = 2.5*2.5;\n\t\t}\n\t\tReductionMethod mm = new MonteCarlo(new MultivariateNormal(mean,correl,new Random()));\n\t\tMap<double[],Double> map = mm.getScenarios(20);\n\t\tfor (double[] x : map.keySet()) {\n\t\t\tfor (int i=0; i<x.length; i++)\n\t\t\t\tSystem.out.print(x[i]+\"\\t\");\n\t\t\tSystem.out.println();\n\t\t}\n\t}\n\t\n\t\n\tpublic void setSeed(long n) {\n\t\t_generator.setSeed(n);\n\t}\n\t\n\t//cholesky-banachiewicz algorithm\n\tstatic double[][] choleskyDecomposition(double[][] a){\n\t\tint m = a.length;\n\t\tdouble[][] l = new double[m][m]; //automatically initialzed to 0's\n\t\tfor(int i = 0; i< m; i++){\n\t\t\tfor(int k = 0; k < (i+1); k++){\n\t\t\t\tdouble sum = 0;\n\t\t\t\tfor(int j = 0; j < k; j++){\n\t\t\t\t\tsum += l[i][j] * l[k][j];\n\t\t\t\t}\n\t\t\t\tl[i][k] = (i == k) ? Math.sqrt(a[i][i] - sum) :\n\t\t\t\t\t(1.0 / l[k][k] * (a[i][k] - sum));\n\t\t\t}\n\t\t}\n\t\treturn l;\n\t}\n\t\n\tpublic double[] getRealization() {\n\t\tdouble[] z = new double[_dim];\n\t\tfor (int i=0; i<_dim; i++)\n\t\t\tz[i] = _generator.nextGaussian();\n\t\treturn transform(z);\n\t}\n\t\n\tpublic double[] transform(double[] z) {\n\t\tdouble[] x = new double[_chol.length];\n\t\tfor (int i=0; i<_dim; i++) {\n\t\t\tdouble sum = 0.0;\n\t\t\tfor (int j=0; j<i+1; j++)\n\t\t\t\tsum += z[j]*_chol[i][j];\n\t\t\tx[i] = _mean[i] + sum;\n\t\t}\n\t\treturn x;\n\t}\n\n\t@Override\n\tpublic int getDim() {\n\t\treturn _dim;\n\t}\n\n\t@Override\n\tpublic List<double[]> getSample(int size) {\n\t\tList<double[]> list = new LinkedList<>();\n\t\tfor (int i=0; i<size; i++)\n\t\t\tlist.add(getRealization());\n\t\treturn list;\n\t}\n\n\t@Override\n\tpublic void setGenerator(Random generator) {\n\t\t_generator = generator;\n\t}\n\n\t@Override\n\tpublic Random getGenerator() {\n\t\treturn _generator;\n\t}\n\n\t@Override\n\tpublic double[] getMean() {\n\t\treturn _mean;\n\t}\n\n\t@Override\n\tpublic double[][] getCov() {\n\t\treturn _cov;\n\t}\n\t\n\tpublic double[][] getCholesky() {\n\t\treturn _chol;\n\t}\n\n\t@Override\n\tpublic double[] getSkewness() {\n\t\treturn new double[_dim];\n\t}\n\n\t@Override\n\tpublic double[] getKurtosis() {\n\t\treturn new double[_dim];\n\t}\n\n\t@Override\n\tpublic DISTRIBUTION getType() {\n\t\treturn DISTRIBUTION.Normal;\n\t}\n\n\t@Override\n\tpublic double[] getRealization(double[] u) {\n\t\tdouble[] z = new double[_dim];\n\t\tfor (int i=0; i<_dim; i++)\n\t\t\tz[i] = NormalDistQuick.inverseF01(u[i]);\n\t\treturn transform(z);\n\t}\n\n\t@Override\n\tpublic double[] getVariance() {\n\t\treturn _var;\n\t}\n\t\n\tpublic boolean isIndependent() {\n\t\tfor (int i=0; i<_dim; i++) {\n\t\t\tfor (int j=i+1; j<_dim; j++) {\n\t\t\t\tif (_cov[i][j]!=0)\n\t\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n}", "public class WassersteinDistance {\n\t\n\tstatic String fileToString(String filename) {\n\t\tStringBuilder sb = new StringBuilder();\n\t\ttry {\n\t\t\tFileInputStream in = new FileInputStream(filename);\n\t\t\tBufferedReader br = new BufferedReader(new InputStreamReader(in));\n\t\t\tString s;\n\t\t\twhile ((s = br.readLine())!=null) {\n\t\t\t\tsb.append(s).append(\"\\n\");\n\t\t\t}\n\t\t\tbr.close();\n\t\t\tin.close();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn sb.toString();\n\t}\n\t\n//\tpublic static double getExactDistance(Map<double[],Double> scenarios, Collection<double[]> sample) {\n//\t\tEnv env = null;\n//\t\tModel model = null;\n////\t\tdouble time = 0;\n//\t\ttry {\n//\t\t\tint sampleSize = sample.size();\n//\t\t\tenv = new Env();\n////\t\t\tenv.PutLicenseString(\"<\"+fileToString(\"lib/sulum/sulumlp.lic\")+\">\");\n//\t\t\tmodel = new Model(env);\n//\t\t\tmodel.SetIntParam(SlmParamInt.SlmPrmIntPresolve,SlmOnOff.SlmOff.get());\n////\t\t\tmodel.SetIntParam(SlmParamInt.SlmPrmIntSimMaxIter,1000);\n////\t\t\tmodel.SetIntParam(SlmParamInt.SlmPrmIntUpdateSolQuality,SlmOnOff.SlmOn.get());\n//\t\t\tmodel.SetIntParam(SlmParamInt.SlmPrmIntSimUseNetwork,SlmOnOff.SlmOn.get());\n//\t\t\tmodel.SetIntParam(SlmParamInt.SlmPrmIntLogLevel,0);\n////\t\t\tmodel.SetIntParam(SlmParamInt.SlmPrmIntDebug,SlmOnOff.SlmOn.get());\n//\t\t\tint numScen = scenarios.size();\n//\t\t\tint cons = sampleSize+numScen;\n//\t\t\tint vars = sampleSize*numScen;\n//\t\t\t//constraints\n//\t\t\tSlmBoundKey[] cbnd = new SlmBoundKey[cons];\n//\t\t\tint[] abegin = new int[cons+1];\n//\t\t\tint[] aidxj = new int[vars*2];\n//\t\t\tdouble[] avalj = new double[vars*2];\n//\t\t\tArrays.fill(avalj, 1.0);\n//\t\t\tdouble[] clo = new double[cons];\n//\t\t\tdouble[] cup = clo;\n//\t\t\tfor (int i=0; i<cons; i++) {\n//\t\t\t\tcbnd[i] = SlmBoundKey.SlmBndFx;\n//\t\t\t\tif (i<numScen){\n//\t\t\t\t\tabegin[i] = (i>0?abegin[i-1]+sampleSize:0);\n//\t\t\t\t}\n//\t\t\t\telse {\n//\t\t\t\t\tclo[i] = -1./sampleSize;\n//\t\t\t\t\tabegin[i] = abegin[i-1]+(i==numScen?sampleSize:numScen);\n//\t\t\t\t}\n//\t\t\t}\n//\t\t\tabegin[cons] = abegin[cons-1]+numScen;\n//\t\t\t//variables\n//\t\t\tdouble[] obj = new double[vars];\n//\t\t\tdouble[] vlo = new double[vars];\n//\t\t\tdouble[] vup = new double[vars];\n//\t\t\tSlmBoundKey[] vbnd = new SlmBoundKey[vars];\n//\t\t\t//construct matrix\n//\t\t\tfor (int i=0; i<numScen; i++) \n//\t\t\t\tfor (int j=0; j<sampleSize; j++) {\n//\t\t\t\t\taidxj[i*sampleSize+j] = i*sampleSize+j;\n//\t\t\t\t\tavalj[i*sampleSize+j] = 1;\n//\t\t\t\t}\n//\t\t\tfor (int i=0; i<sampleSize; i++) \n//\t\t\t\tfor (int j=0; j<numScen; j++) {\n//\t\t\t\t\taidxj[vars+i*numScen+j] = j*sampleSize+i;\n//\t\t\t\t\tavalj[vars+i*numScen+j] = -1;\n//\t\t\t\t}\n//\t\t\tint i=0; double probSum = 0.;\n//\t\t\t//create variables and objective\n//\t\t\tfor (double[] d1 : scenarios.keySet()) {\n//\t\t\t\tdouble prob = scenarios.get(d1);\n//\t\t\t\tclo[i] = prob;\n//\t\t\t\tif (i==numScen-1) clo[i] = 1-probSum;\n//\t\t\t\tprobSum += clo[i];\n//\t\t\t\tint j=0;\n//\t\t\t\tfor (double[] d2 : sample) {\n//\t\t\t\t\tint idx = i*sampleSize+j;\n//\t\t\t\t\t//variable bounds\n//\t\t\t\t\tvbnd[idx] = SlmBoundKey.SlmBndRa;\n//\t\t\t\t\tvup[idx] = 1./sampleSize;\n//\t\t\t\t\t//objective\n//\t\t\t\t\tobj[idx] = Metrics.squaredDistance(d1,d2);\n//\t\t\t\t\tj++;\n//\t\t\t\t}\n//\t\t\t\ti++;\n//\t\t\t}\n////\t\t\t\n////\t\t\tmodel.SetIntParam(SlmParamInt.SlmPrmIntObjSense,SlmObjSense.SlmObjSenseMin.get());\n//\t\t\tmodel.SetAllData(cons,vars,0.0,cbnd,clo,cup,vbnd,obj,vlo,vup,0,abegin,aidxj,avalj);\n////\t\t\tmodel.SetIntParam(SlmParamInt.SlmPrmIntObjSense,SlmObjSense.SlmObjSenseMin.get());\n////\t\t\tSystem.err.println(\"Model time: \"+(System.nanoTime()-time)/1000000000.0);\n////\t\t\ttime = System.nanoTime();\n////\t\t\tmodel.WriteProblem(\"wasserstein_log_dim25_scen500_cv1.0_rho0.0.mps.gz\");\n////\t\t\tSystem.err.println(\"Save time: \"+(System.nanoTime()-time)/1000000000.0);\n////\t\t\tSystem.out.println(model.WriteStringProblem(SlmCompressionType.SlmCompressionTypeNone, SlmEncodingType.SlmEncodingTypeNone, SlmProblemFormat.SlmProblemFormatLp));\n//\t\t\tmodel.Optimize();\n////\t\t\tmodel.PrintSolQuality(SlmStream.SlmStrInfo);\n////\t\t\tmodel.WriteSolution(\"wasserstein_neg5_simplex.sol\");\n//\t\t\treturn Math.sqrt(model.GetDbInfo(SlmInfoDb.SlmInfoDbPrimObj));\n//\t\t} catch (Exception e) {\n//\t\t\te.printStackTrace();\n//\t\t\ttry {\n////\t\t\t\tSystem.err.println(\"Solver time: \"+(System.nanoTime()-time)/1000000000.0);\n//\t\t\t\treturn Math.sqrt(model.GetDbInfo(SlmInfoDb.SlmInfoDbPrimObj));\n//\t\t\t} catch (Exception e1) {\n//\t\t\t\te1.printStackTrace();\n//\t\t\t}\n//\t\t\t\n//\t\t}\n//\t\tfinally {\n//\t\t\tenv.Dispose();\n//\t\t\tmodel.Dispose();\n//\t\t}\n//\t\treturn Double.NaN;\n//\t}\n\t\n\t\n\tpublic static double getLowerBound(int dim, Map<double[],Double> scen, Collection<double[]> sample) {\n\t\tint sampleSize = sample.size();\n\t\tscengen.tools.MetricTree<Cluster> tree = new scengen.tools.MetricTree<>(dim);\n\t\tfor (double[] x : scen.keySet())\n\t\t\ttree.add(x, new Cluster(x,scen.get(x)*sampleSize));\n\t\tdouble distance = 0.;\n\t\tfor (double[] x : sample) {\n\t\t\tCluster nearest = tree.get(x);\n\t\t\tdistance += Metrics.squaredDistance(x, nearest.center);\n\t\t}\n\t\treturn Math.sqrt(distance/sampleSize);\n\t}\n\n\tpublic static double getUpperBound(int dim, Map<double[],Double> scen, Collection<double[]> sample) {\n\t\tint sampleSize = sample.size();\n\t\tscengen.tools.MetricTree<Cluster> tree = new scengen.tools.MetricTree<>(dim);\n\t\tfor (double[] x : scen.keySet())\n\t\t\ttree.add(x, new Cluster(x,scen.get(x)*sampleSize));\n\t\tdouble distance = 0.0;\n\t\tfor (double[] x : sample) {\n\t\t\tCluster next = tree.get(x);\n\t\t\tdouble dec1 = 1;\n\t\t\tdouble dec2 = next.decrement(dec1);\n\t\t\twhile (dec1!=dec2) {\n\t\t\t\tdistance += dec2*Metrics.squaredDistance(next.center,x);\n\t\t\t\tscengen.tools.MetricTree<Cluster> tree2 = new scengen.tools.MetricTree<>(dim);\n\t\t\t\tfor (Cluster c : tree.getAll())\n\t\t\t\t\tif (c != next)\n\t\t\t\t\t\ttree2.add(c.center, new Cluster(c.center,c.weight));\n\t\t\t\ttree = tree2;\n\t\t\t\tif (tree.size()>0) {\n\t\t\t\t\tnext = tree.get(x);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\ttree.add(next.center,next);\n\t\t\t\t\tnext.weight = sampleSize;\n\t\t\t\t}\n\t\t\t\tdec1 -= dec2;\n\t\t\t\tdec2 = next.decrement(dec1);\n\t\t\t}\n\t\t\tdistance += dec2*Metrics.squaredDistance(next.center,x);\n\t\t}\n\t\treturn Math.sqrt(distance/sampleSize);\n\t}\n\t\n\tstatic class Cluster {\n\t\tdouble[] center;\n\t\tdouble weight;\n\t\t\n\t\tCluster(double[] x, double w) {\n\t\t\tcenter = x;\n\t\t\tweight = w;\n\t\t}\n\t\t\n\t\tdouble decrement(double w) {\n\t\t\tdouble dec = Math.min(weight,w);\n\t\t\tweight -= w;\n\t\t\treturn dec;\n\t\t}\n\t\t\n\t}\n\t\n}", "public enum METHOD {\n\tMonteCarlo, QuasiMonteCarlo, MomentMatching, QuantizationLearning, QuantizationGrids, Scenred2, VoronoiCellSampling\n}", "public class MonteCarlo extends ReductionMethod {\n\t\n\tMultivariateDistribution _mvDist;\n\t\n\tpublic MonteCarlo (MultivariateDistribution mvDist) {\n\t\t_mvDist = mvDist;\n\t\t\n\t}\n\t\n\t@Override\n\tpublic Map<double[], Double> getScenarios(int numScen) {\n\t\tMap<double[],Double> resultMap = new LinkedHashMap<>();\n\t\tfor (int i=0; i<numScen; i++)\n\t\t\tresultMap.put(_mvDist.getRealization(),1./numScen);\n\t\treturn resultMap;\n\t}\n}", "public class Statistics implements Serializable {\r\n\t\r\n\tprivate static final long serialVersionUID = 677360888189461348L;\r\n\tint count;\r\n\tdouble avgX;\r\n\tpublic double avgX2;\r\n\t\r\n\t/**\r\n\t * Adds a sample point to the list.\r\n\t * @param X add a data point\r\n\t */\r\n\tpublic synchronized void add(double X){\r\n\t\tif (Double.isNaN(X)) return;\r\n\t\tdouble a = 1./++count;\r\n\t\tavgX += a*(X-avgX);\r\n\t\tavgX2 += a*(X*X-avgX2);\r\n\t}\r\n\r\n\t\r\n\t/**\r\n\t * Returns the mean.\r\n\t * @return batch mean\r\n\t */\r\n\tpublic double getMean() {\r\n\t\tif (count==0) return Double.NaN;\r\n\t\treturn avgX;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Returns the mean.\r\n\t * @return batch mean\r\n\t */\r\n\tpublic double getMeanOfSquares() {\r\n\t\tif (count==0) return Double.NaN;\r\n\t\treturn avgX2;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Returns the variance.\r\n\t * @return variance\r\n\t */\r\n\tpublic double getVariance() {\r\n\t\tif (count<=1) return Double.NaN;\r\n\t\treturn (avgX2-avgX*avgX)*count/(count-1);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Returns the standard deviation.\r\n\t * @return variance\r\n\t */\r\n\tpublic double getStandardDeviation() {\r\n\t\tif (count<=1) return Double.NaN;\r\n\t\treturn Math.sqrt(getVariance());\r\n\t}\r\n\t\r\n\t/**\r\n\t * Returns the helf width of the confidence interval (e.g, for the 95% confidence interval alpha=0.95).\r\n\t * @return variance\r\n\t */\r\n\tpublic double getHalfwidth(double alpha) {\r\n\t\tif (count<5) return Double.NaN;\r\n\t\tTDistribution t = new TDistribution(count);\r\n\t\treturn t.inverseCumulativeProbability((1.+alpha)/2.)*getStandardError();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Returns the standard error.\r\n\t * @return standard error\r\n\t */\r\n\tpublic double getStandardError() {\r\n\t\tif (count<=1) return Double.NaN;\r\n\t\treturn Math.sqrt((avgX2-avgX*avgX)/(count-1));\r\n\t}\r\n\t\r\n\t/**\r\n\t * @return Returns the coefficient of variation (CV).\r\n\t */\r\n\tpublic double getCV() {\r\n\t\tif (count<=1) return Double.NaN;\r\n\t\treturn getStandardDeviation()/getMean();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Deletes the sample and resets the variables.\r\n\t */\r\n\tpublic void reset() {\r\n\t\tavgX = 0.0; avgX2 = 0.0; count = 0;\r\n\t}\r\n\t\r\n\tpublic int size() {\r\n\t\treturn count;\r\n\t}\r\n\t\r\n}\r", "public class Xorshift extends Random {\n\tprivate static final long serialVersionUID = 1L;\n\n\t/** 2<sup>-53</sup>. */\n\tprivate static final double NORM_53 = 1. / ( 1L << 53 );\n\t/** 2<sup>-24</sup>. */\n\tprivate static final double NORM_24 = 1. / ( 1L << 24 );\n\n\t/** The internal state of the algorithm. */\n\tprivate long[] s;\n\tprivate int p;\n\t\n\t/** Creates a new generator seeded using {@link #randomSeed()}. */\n\tpublic Xorshift() {\n\t\tthis( randomSeed() );\n\t}\n\n\t/** Creates a new generator using a given seed.\n\t * \n\t * @param seed a nonzero seed for the generator (if zero, the generator will be seeded with -1).\n\t */\n\tpublic Xorshift( final long seed ) {\n\t\tsuper( seed );\n\t}\n\n\t@Override\n\tprotected int next( int bits ) {\n\t\treturn (int)( nextLong() >>> 64 - bits );\n\t}\n\t\n\t@Override\n\tpublic synchronized long nextLong() {\n\t\tlong s0 = s[ p ];\n\t\tlong s1 = s[ p = ( p + 1 ) & 15 ];\n\t\ts1 ^= s1 << 1;\n\t\treturn 1181783497276652981L * ( s[ p ] = s1 ^ s0 ^ ( s1 >>> 13 ) ^ ( s0 >>> 7 ) );\n\t}\n\n\t@Override\n\tpublic int nextInt() {\n\t\treturn (int)nextLong();\n\t}\n\t\n\t@Override\n\tpublic int nextInt( final int n ) {\n\t\treturn (int)nextLong( n );\n\t}\n\t\n\t/** Returns a pseudorandom uniformly distributed {@code long} value\n * between 0 (inclusive) and the specified value (exclusive), drawn from\n * this random number generator's sequence. The algorithm used to generate\n * the value guarantees that the result is uniform, provided that the\n * sequence of 64-bit values produced by this generator is. \n * \n * @param n the positive bound on the random number to be returned.\n * @return the next pseudorandom {@code long} value between {@code 0} (inclusive) and {@code n} (exclusive).\n */\n\tpublic long nextLong( final long n ) {\n if ( n <= 0 ) throw new IllegalArgumentException();\n\t\t// No special provision for n power of two: all our bits are good.\n\t\tfor(;;) {\n\t\t\tfinal long bits = nextLong() >>> 1;\n\t\t\tfinal long value = bits % n;\n\t\t\tif ( bits - value + ( n - 1 ) >= 0 ) return value;\n\t\t}\n\t}\n\t\n\t@Override\n\t public double nextDouble() {\n\t\treturn ( nextLong() >>> 11 ) * NORM_53;\n\t}\n\t\n\t@Override\n\tpublic float nextFloat() {\n\t\treturn (float)( ( nextLong() >>> 40 ) * NORM_24 );\n\t}\n\n\t@Override\n\tpublic boolean nextBoolean() {\n\t\treturn ( nextLong() & 1 ) != 0;\n\t}\n\t\n\t@Override\n\tpublic void nextBytes( final byte[] bytes ) {\n\t\tint i = bytes.length, n = 0;\n\t\twhile( i != 0 ) {\n\t\t\tn = Math.min( i, 8 );\n\t\t\tfor ( long bits = nextLong(); n-- != 0; bits >>= 8 ) bytes[ --i ] = (byte)bits;\n\t\t}\n\t}\n\t\n\t/** Returns a random seed generated by taking a unique increasing long, adding\n\t * {@link System#nanoTime()} and scrambling the result using the finalisation step of Austin\n\t * Appleby's <a href=\"http://sites.google.com/site/murmurhash/\">MurmurHash3</a>.\n\t * \n\t * @return a reasonably good random seed. \n\t */\n\tprivate static final AtomicLong seedUniquifier = new AtomicLong();\n\tpublic static long randomSeed() {\n\t\tlong seed = seedUniquifier.incrementAndGet() + System.nanoTime();\n\n\t\tseed ^= seed >>> 33;\n\t\tseed *= 0xff51afd7ed558ccdL;\n\t\tseed ^= seed >>> 33;\n\t\tseed *= 0xc4ceb9fe1a85ec53L;\n\t\tseed ^= seed >>> 33;\n\n\t\treturn seed;\n\t}\n\n\t/** Sets the seed of this generator.\n\t * \n\t * @param seed a nonzero seed for the generator (if zero, the generator will be seeded with -1).\n\t */\n\t@Override\n\tpublic synchronized void setSeed( final long seed ) {\n\t\tif ( s == null ) s = new long[ 16 ];\n\t\tfor( int i = s.length; i-- != 0; ) s[ i ] = seed == 0 ? -1 : seed;\n\t\tfor( int i = s.length * 4; i-- != 0; ) nextLong(); // Warmup.\n\t}\n}" ]
import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Map; import java.util.Random; import scengen.application.Generator; import scengen.distribution.MultivariateDistribution; import scengen.distribution.MultivariateNormal; import scengen.measures.WassersteinDistance; import scengen.methods.METHOD; import scengen.methods.MonteCarlo; import scengen.tools.Statistics; import scengen.tools.Xorshift;
package scengen.paper; public class QuantizationGridBench { static int _sampleSize = 100000; static int _numRepititions = 10; static long _seed = 191; static Random _rand = new Xorshift(_seed); static String filename = "comparison_"+System.nanoTime()+".txt"; static int[][] dimScens = new int[][]{{2,4},{2,40},{10,20},{10,200}}; public static void main (String... args) throws IOException { FileOutputStream stream = new FileOutputStream(filename); BufferedWriter br = new BufferedWriter(new OutputStreamWriter(stream)); String s = "Dimensions\tScenarios\tMethod\tWasserstein\tSE\n"; br.write(s);br.flush(); System.out.print(s); for (int[] dimScen : dimScens) { int dim = dimScen[0]; int numScen = dimScen[1]; double[] means = new double[dim]; double[][] cov = new double[dim][dim]; for (int i=0; i<dim; i++) cov[i][i] = 1; MultivariateDistribution mvDist = new MultivariateNormal(means,cov,_rand); for (METHOD method : new METHOD[]{METHOD.QuantizationGrids,METHOD.QuantizationLearning}) {
Statistics wasserStat = new Statistics();
6
FabioZumbi12/PixelVip
PixelVip-Spigot/src/main/java/br/net/fabiozumbi12/pixelvip/bukkit/PixelVip.java
[ "public class PackageManager {\n\n private YamlConfiguration packages;\n private PixelVip plugin;\n private File fPack;\n\n public PackageManager(PixelVip plugin) {\n this.plugin = plugin;\n\n packages = new YamlConfiguration();\n fPack = new File(plugin.getDataFolder(), \"packages.yml\");\n try {\n if (!fPack.exists()) {\n fPack.createNewFile();\n }\n\n packages.load(fPack);\n if (!packages.contains(\"packages\")) {\n packages.set(\"pending-variants\", new HashMap<>());\n packages.set(\"packages.999.commands\", Arrays.asList(\"givevip {p} vip1 10\", \"eco add {p} 1000\"));\n packages.set(\"packages.999.variants.options\", new HashMap<>());\n packages.set(\"packages.999.variants.message\", \"\");\n\n packages.set(\"packages.998.commands\", new ArrayList<>());\n packages.set(\"packages.998.variants.options.Masculino\", Collections.singletonList(\"addvip {p} vip2m 10\"));\n packages.set(\"packages.998.variants.options.Feminino\", Collections.singletonList(\"addvip {p} vip2f 10\"));\n packages.set(\"packages.998.variants.message\", \"&aSelect your tag gender (click): \");\n packages.save(fPack);\n }\n\n packages.set(\"hand.cmd\", packages.getString(\"hand.cmd\", \"give {p} {item} {amount}\"));\n\n packages.set(\"strings.choose\", packages.getString(\"strings.choose\", \"&bClick in one of the available variants to choose one: \"));\n packages.set(\"strings.hover-info\", packages.getString(\"strings.hover-info\", \"&eClick to select this variant!\"));\n packages.set(\"strings.use-cmd\", packages.getString(\"strings.use-cmd\", \"&bUse the following command to select your variant: &e\\\\givepackage %s [variant]\"));\n packages.set(\"strings.variants\", packages.getString(\"strings.variants\", \"&bSelect a variant: \"));\n packages.set(\"strings.no-package\", packages.getString(\"strings.no-package\", \"&cThere's no package with id {id}\"));\n packages.set(\"strings.no-pendent\", packages.getString(\"strings.no-pendent\", \"&cYou don't have any pendent variants to use!\"));\n packages.set(\"strings.removed\", packages.getString(\"strings.removed\", \"&aPackage removed with success!\"));\n packages.set(\"strings.added\", packages.getString(\"strings.added\", \"&aPackage added with success!\"));\n packages.set(\"strings.exists\", packages.getString(\"strings.exists\", \"&cA package with id {id} already exists!\"));\n packages.set(\"strings.hand-empty\", packages.getString(\"strings.hand-empty\", \"&cYour hand is empty or an invalid item!\"));\n packages.set(\"strings.only-players\", packages.getString(\"strings.only-players\", \"&cOnly players can use this command to add a item from hand!\"));\n packages.save(fPack);\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n public void save() {\n try {\n packages.save(fPack);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n public boolean hasPendingPlayer(Player player) {\n return !packages.getStringList(\"pending-variants.\" + player.getName()).isEmpty();\n }\n\n public List<String> getPendingVariant(Player player) {\n return this.packages.getStringList(\"pending-variants.\" + player.getName());\n }\n\n public YamlConfiguration getPackages() {\n return this.packages;\n }\n\n public PVPackage getPackage(String id) {\n if (packages.contains(\"packages.\" + id))\n return new PVPackage(plugin, id, packages);\n return null;\n }\n}", "public class MercadoPagoHook implements PaymentModel {\n private PixelVip plugin;\n private boolean sandbox;\n\n public MercadoPagoHook(PixelVip plugin) {\n this.plugin = plugin;\n this.sandbox = plugin.getPVConfig().getApiRoot().getBoolean(\"apis.mercadopago.sandbox\");\n String accToken = plugin.getPVConfig().getApiRoot().getString(\"apis.mercadopago.access-token\");\n\n try {\n MercadoPago.SDK.setAccessToken(accToken);\n } catch (MPConfException e) {\n e.printStackTrace();\n }\n }\n\n @Override\n public String getPayname() {\n return \"MercadoPago\";\n }\n\n @Override\n public boolean checkTransaction(Player player, String transCode) {\n\n //check if used\n if (plugin.getPVConfig().transExist(this.getPayname(), transCode)) {\n player.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"payment.codeused\").replace(\"{payment}\", getPayname())));\n return true;\n }\n\n boolean test = plugin.getPVConfig().getApiRoot().getBoolean(\"apis.in-test\");\n boolean success;\n try {\n JsonElement payment_info = MercadoPago.SDK.Get(this.sandbox ? \"/sandbox\" : \"\" + \"/v1/payments/\" + transCode).getJsonElementResponse();\n\n if (payment_info.getAsJsonObject().getAsJsonPrimitive(\"status\").getAsString().equals(\"404\")) {\n return false;\n }\n\n //check if approved\n if (!payment_info.getAsJsonObject().getAsJsonPrimitive(\"status\").getAsString().equalsIgnoreCase(\"approved\")) {\n player.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"payment.waiting\").replace(\"{payment}\", getPayname())));\n return true;\n }\n\n //check if expired\n try {\n Date oldCf = new SimpleDateFormat(\"dd/MM/yyyy HH:mm:ss\").parse(plugin.getPVConfig().getApiRoot().getString(\"apis.mercadopago.ignoreOldest\"));\n Date transCf = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ss.SSSXXX\").parse(payment_info.getAsJsonObject().getAsJsonPrimitive(\"date_last_updated\").getAsString());\n if (transCf.compareTo(oldCf) < 0) {\n player.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"payment.expired\").replace(\"{payment}\", getPayname())));\n return true;\n }\n } catch (ParseException e) {\n e.printStackTrace();\n }\n\n JsonArray jItems;\n if (payment_info.getAsJsonObject().get(\"additional_info\").getAsJsonObject().has(\"items\")){\n jItems = payment_info.getAsJsonObject().get(\"additional_info\").getAsJsonObject().get(\"items\").getAsJsonArray();\n } else {\n String[] description = payment_info.getAsJsonObject().get(\"description\").getAsString().split(\" \");\n String desc = payment_info.getAsJsonObject().get(\"description\").getAsString();\n\n // Id handling\n String id;\n Optional<String> optId = Arrays.stream(description).filter(i -> i.startsWith(\"#\")).findFirst();\n if (plugin.getPackageManager().getPackage(description[0]) != null){\n id = description[0];\n } else if (optId.isPresent()){\n id = optId.get().substring(optId.get().indexOf(\"#\"));\n } else {\n plugin.getPVLogger().warning(\"ID of Item not found, setting to 0: \" + desc);\n id = String.valueOf(0);\n }\n\n String quantity = description[description.length-1];\n\n jItems = new JsonArray();\n jItems.add(new JsonParser().parse(\n \"{\\\"id\\\":\\\"\"+id+\"\\\",\\\"quantity\\\":\\\"\"+quantity+\"\\\",\\\"title\\\":\\\"\"+desc+\"\\\",\\\"unit_price\\\":\\\"\"+payment_info.getAsJsonObject().get(\"transaction_details\").getAsJsonObject().get(\"net_received_amount\").getAsString()+\"\\\"}\"));\n }\n\n // Debug\n if (test) {\n plugin.getPVLogger().severe(\"Items: \" + jItems);\n plugin.getPVLogger().severe(\"---------\");\n for (JsonElement item : jItems) {\n plugin.getPVLogger().severe(\"ID: \" + item.getAsJsonObject().get(\"id\").getAsString());\n plugin.getPVLogger().severe(\"Quantity: \" + item.getAsJsonObject().get(\"quantity\").getAsString());\n plugin.getPVLogger().severe(\"Title: \" + item.getAsJsonObject().get(\"title\").getAsString());\n plugin.getPVLogger().severe(\"Price: \" + item.getAsJsonObject().get(\"unit_price\").getAsString());\n plugin.getPVLogger().severe(\"---------\");\n }\n // Debug\n }\n\n HashMap<String, Integer> items = new HashMap<>();\n for (JsonElement item : jItems) {\n String id;\n if (plugin.getPVConfig().getApiRoot().getString(\"apis.mercadopago.product-id-location\").equalsIgnoreCase(\"ID\")) {\n id = item.getAsJsonObject().get(\"id\").getAsString();\n } else {\n String[] idStr = item.getAsJsonObject().get(\"title\").getAsString().split(\" \");\n Optional<String> optId = Arrays.stream(idStr).filter(i -> i.startsWith(\"#\")).findFirst();\n if (plugin.getPackageManager().getPackage(idStr[0]) != null){\n id = idStr[0];\n } else id = optId.map(s -> s.substring(s.indexOf(\"#\"))).orElseGet(() -> String.valueOf(0));\n }\n\n if (plugin.getPackageManager().getPackage(id) == null) {\n player.sendMessage(ChatColor.translateAlternateColorCodes('&',\n plugin.getPVConfig().getLang(\"_pluginTag\") +\n plugin.getPVConfig().getLang(\"payment.noitems\")\n .replace(\"{payment}\",getPayname()) + \"\\n\" +\n \" - Error: \" + item.getAsJsonObject().get(\"title\").getAsString()));\n continue;\n }\n\n items.put(id, item.getAsJsonObject().get(\"quantity\").getAsInt());\n\n // Debug\n if (test) {\n plugin.getPVLogger().severe(\"Added Item: \" + item.getAsJsonObject().get(\"title\").getAsString() + \" | ID: \" + item.getAsJsonObject().get(\"id\").getAsString());\n }\n }\n\n success = plugin.getUtil().paymentItems(items, player, this.getPayname(), transCode);\n } catch (Exception e) {\n e.printStackTrace();\n plugin.processTrans.remove(transCode);\n return false;\n }\n\n //if success\n if (success && !sandbox) plugin.getPVConfig().addTrans(this.getPayname(), transCode, player.getName());\n plugin.processTrans.remove(transCode);\n return true;\n }\n}", "public class PagSeguroHook implements PaymentModel {\n private PixelVip plugin;\n private boolean sandbox;\n private PagSeguro pagSeguro;\n\n public PagSeguroHook(PixelVip plugin) {\n this.plugin = plugin;\n sandbox = plugin.getPVConfig().getApiRoot().getBoolean(\"apis.pagseguro.sandbox\");\n try {\n Credential accCred = Credential.sellerCredential(plugin.getPVConfig().getApiRoot().getString(\"apis.pagseguro.email\"), plugin.getPVConfig().getApiRoot().getString(\"apis.pagseguro.token\"));\n PagSeguroEnv environment;\n environment = sandbox ? PagSeguroEnv.SANDBOX : PagSeguroEnv.PRODUCTION;\n pagSeguro = PagSeguro.instance(accCred, environment);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n @Override\n public String getPayname() {\n return \"PagSeguro\";\n }\n\n @Override\n public boolean checkTransaction(Player player, String transCode) {\n\n //check if used\n if (plugin.getPVConfig().transExist(this.getPayname(), transCode)) {\n player.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"payment.codeused\").replace(\"{payment}\", getPayname())));\n return true;\n }\n\n boolean test = plugin.getPVConfig().getApiRoot().getBoolean(\"apis.in-test\");\n boolean success;\n try {\n TransactionDetail trans = pagSeguro.transactions().search().byCode(transCode);\n\n if (trans == null) {\n return false;\n }\n\n //check if approved\n if (!trans.getStatus().getStatus().equals(TransactionStatus.Status.APPROVED)) {\n player.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"payment.waiting\").replace(\"{payment}\", getPayname())));\n return true;\n }\n\n //check if expired\n SimpleDateFormat sdf = new SimpleDateFormat(\"dd/MM/yyyy\");\n Date oldCf = sdf.parse(plugin.getPVConfig().getApiRoot().getString(\"apis.pagseguro.ignoreOldest\"));\n if (trans.getDate().compareTo(oldCf) < 0) {\n player.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"payment.expired\").replace(\"{payment}\", getPayname())));\n return true;\n }\n\n\n // Debug\n if (test) {\n plugin.getPVLogger().severe(\"Items: \" + trans);\n plugin.getPVLogger().severe(\"---------\");\n for (PaymentItem item : trans.getItems()) {\n plugin.getPVLogger().severe(\"ID: \" + item.getId());\n plugin.getPVLogger().severe(\"Quantity: \" + item.getQuantity());\n plugin.getPVLogger().severe(\"Title: \" + item.getDescription());\n plugin.getPVLogger().severe(\"---------\");\n }\n }\n // Debug\n\n HashMap<String, Integer> items = new HashMap<>();\n for (PaymentItem item : trans.getItems()) {\n String id;\n if (plugin.getPVConfig().getApiRoot().getString(\"apis.pagseguro.product-id-location\").equalsIgnoreCase(\"ID\")) {\n id = item.getId();\n } else {\n String[] idStr = item.getDescription().split(\" \");\n Optional<String> optId = Arrays.stream(idStr).filter(i -> i.startsWith(\"#\")).findFirst();\n if (plugin.getPackageManager().getPackage(idStr[0]) != null){\n id = idStr[0];\n } else id = optId.map(s -> s.substring(s.indexOf(\"#\"))).orElseGet(() -> String.valueOf(0));\n }\n\n if (plugin.getPackageManager().getPackage(id) == null) {\n player.sendMessage(ChatColor.translateAlternateColorCodes('&',\n plugin.getPVConfig().getLang(\"_pluginTag\") +\n plugin.getPVConfig().getLang(\"payment.noitems\").replace(\"{payment}\",getPayname()) + \"\\n\" +\n \" - Error: \" + item.getDescription()));\n continue;\n }\n\n items.put(id, item.getQuantity());\n\n // Debug\n if (test) {\n plugin.getPVLogger().severe(\"Added Item: \" + item.getDescription() + \" | ID: \" + item.getId());\n }\n }\n\n success = plugin.getUtil().paymentItems(items, player, this.getPayname(), transCode);\n } catch (Exception e) {\n e.printStackTrace();\n plugin.processTrans.remove(transCode);\n return false;\n }\n\n //if success\n if (!sandbox || success) plugin.getPVConfig().addTrans(this.getPayname(), transCode, player.getName());\n plugin.processTrans.remove(transCode);\n return true;\n }\n}", "public class PayPalHook implements PaymentModel {\n private PixelVip plugin;\n private boolean sandbox;\n private PayPal paypal;\n\n public PayPalHook(PixelVip plugin) {\n this.plugin = plugin;\n this.sandbox = plugin.getPVConfig().getApiRoot().getBoolean(\"apis.paypal.sandbox\");\n\n try {\n Profile user = new BaseProfile.Builder(\n plugin.getPVConfig().getApiRoot().getString(\"apis.paypal.username\"),\n plugin.getPVConfig().getApiRoot().getString(\"apis.paypal.password\"))\n .signature(plugin.getPVConfig().getApiRoot().getString(\"apis.paypal.signature\")).build();\n paypal = new paypalnvp.core.PayPal(user,paypalnvp.core.PayPal.Environment.LIVE);\n } catch (Exception ex) {\n ex.printStackTrace();\n }\n }\n\n @Override\n public String getPayname() {\n return \"PayPal\";\n }\n\n @Override\n public boolean checkTransaction(Player player, String transCode) {\n\n //check if used\n if (plugin.getPVConfig().transExist(this.getPayname(), transCode)) {\n player.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"payment.codeused\").replace(\"{payment}\", getPayname())));\n return true;\n }\n\n boolean test = plugin.getPVConfig().getApiRoot().getBoolean(\"apis.in-test\");\n boolean success;\n try {\n\n GetTransactionDetails transactionDetails = new GetTransactionDetails(transCode);\n paypal.setResponse(transactionDetails);\n Map<String, String> response = transactionDetails.getNVPResponse();\n\n //check if exists\n if (!response.containsKey(\"PAYMENTSTATUS\")) {\n return false;\n }\n\n //check if approved\n if (!response.get(\"PAYMENTSTATUS\").equals(\"Completed\")) {\n player.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"payment.waiting\").replace(\"{payment}\", getPayname())));\n plugin.processTrans.remove(transCode);\n return true;\n }\n\n /*for (Map.Entry<String, String> resp : response.entrySet()) {\n plugin.getPVLogger().severe(resp.getKey() + \": \" + resp.getValue());\n }*/\n\n //check if expired\n Date oldCf = new SimpleDateFormat(\"dd/MM/yyyy HH:mm:ss\").parse(plugin.getPVConfig().getApiRoot().getString(\"apis.paypal.ignoreOldest\"));\n Date payCf = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ss'Z'\").parse(response.get(\"ORDERTIME\"));\n if (payCf.compareTo(oldCf) < 0) {\n player.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"payment.expired\").replace(\"{payment}\", getPayname())));\n return true;\n }\n\n List<String[]> itemList = new ArrayList<>();\n String index = \"0\";\n String[] itemArr = new String[]{\"\",\"\",\"\",\"\"};\n for (Map.Entry<String, String> item : response.entrySet().stream().filter(map->map.getKey().startsWith(\"L_\")).collect(Collectors.toList())) {\n String newIndex = item.getKey().substring(item.getKey().length()-1);\n if (newIndex.equals(index)){\n String newKey = item.getKey().substring(0, item.getKey().length()-1);\n if (newKey.equals(\"L_NUMBER\"))\n itemArr[0] = item.getValue();\n if (newKey.equals(\"L_QTY\"))\n itemArr[1] = item.getValue();\n if (newKey.equals(\"L_NAME\"))\n itemArr[2] = item.getValue();\n if (newKey.equals(\"L_AMT\"))\n itemArr[3] = item.getValue();\n } else {\n index = newIndex;\n itemList.add(itemArr);\n itemArr = new String[]{\"\",\"\",\"\",\"\"};\n }\n }\n\n if (!itemList.contains(itemArr)) itemList.add(itemArr);\n\n // Debug\n if (test) {\n plugin.getPVLogger().severe(\"---------\");\n for (String[] item : itemList) {\n plugin.getPVLogger().severe(\"ID: \" + item[0]);\n plugin.getPVLogger().severe(\"Quantity: \" + item[1]);\n plugin.getPVLogger().severe(\"Title: \" + item[2]);\n plugin.getPVLogger().severe(\"Price: \" + item[3]);\n plugin.getPVLogger().severe(\"---------\");\n }\n // Debug\n }\n\n HashMap<String, Integer> items = new HashMap<>();\n for (String[] item : itemList) {\n String id;\n if (plugin.getPVConfig().getApiRoot().getString(\"apis.mercadopago.product-id-location\").equalsIgnoreCase(\"ID\")) {\n id = item[0];\n } else {\n String[] idStr = item[2].split(\" \");\n Optional<String> optId = Arrays.stream(idStr).filter(i -> i.startsWith(\"#\")).findFirst();\n if (plugin.getPackageManager().getPackage(idStr[0]) != null){\n id = idStr[0];\n } else id = optId.map(s -> s.substring(s.indexOf(\"#\"))).orElseGet(() -> String.valueOf(0));\n }\n\n if (plugin.getPackageManager().getPackage(id) == null) {\n player.sendMessage(ChatColor.translateAlternateColorCodes('&',\n plugin.getPVConfig().getLang(\"_pluginTag\") +\n plugin.getPVConfig().getLang(\"payment.noitems\")\n .replace(\"{payment}\",getPayname()) + \"\\n\" +\n \" - Error: \" + item[2]));\n continue;\n }\n\n items.put(id, Integer.parseInt(item[1]));\n\n // Debug\n if (test) {\n plugin.getPVLogger().severe(\"Added Item: \" + item[2] + \" | ID: \" + item[0]);\n }\n }\n\n success = plugin.getUtil().paymentItems(items, player, this.getPayname(), transCode);\n } catch (Exception e) {\n e.printStackTrace();\n plugin.processTrans.remove(transCode);\n return false;\n }\n\n //if success\n if (success && !sandbox) plugin.getPVConfig().addTrans(this.getPayname(), transCode, player.getName());\n plugin.processTrans.remove(transCode);\n return true;\n }\n}", "public interface PaymentModel {\n\n String getPayname();\n\n boolean checkTransaction(Player player, String transCode);\n}", "public class PixelVipBungee implements PluginMessageListener, Listener {\n\n private PixelVip plugin;\n private List<byte[]> pendentBytes;\n\n public PixelVipBungee(PixelVip plugin) {\n this.plugin = plugin;\n this.pendentBytes = new ArrayList<>();\n }\n\n @Override\n public void onPluginMessageReceived(String channel, Player player, byte[] message) {\n if (!channel.equals(\"bungee:pixelvip\")) {\n return;\n }\n if (!plugin.getPVConfig().bungeeSyncEnabled()) {\n return;\n }\n\n plugin.serv.getScheduler().runTaskLater(plugin, () -> {\n\n DataInputStream in = new DataInputStream(new ByteArrayInputStream(message));\n try {\n String id = in.readUTF();\n if (id.equals(plugin.getPVConfig().getString(\"\", \"bungee.serverID\"))) {\n return;\n }\n\n //operation\n String op = in.readUTF();\n if (op.equals(\"receive\")) {\n\n while (in.available() > 0) {\n String a = in.readUTF();\n\n if (a.equals(\"vips\")) {\n String uuid = in.readUTF();\n String duration = in.readUTF();\n String group = in.readUTF();\n String pgroup = in.readUTF();\n String nick = in.readUTF();\n boolean active = Boolean.getBoolean(in.readUTF());\n String expires = in.readUTF();\n plugin.getPVConfig().addVip(group, uuid, pgroup, Long.parseLong(duration), nick, expires);\n plugin.getPVConfig().setVipActive(uuid, group, active);\n plugin.getPVConfig().saveVips();\n }\n if (a.startsWith(\"keys\")) {\n String key = in.readUTF();\n String group = in.readUTF();\n long millis = Long.parseLong(in.readUTF());\n int uses = Integer.parseInt(in.readUTF());\n plugin.getPVConfig().addKey(key, group, millis, uses);\n plugin.getPVConfig().saveKeys();\n }\n if (a.startsWith(\"itemkeys\")) {\n String key = in.readUTF();\n List<String> cmds = Arrays.asList(in.readUTF().split(\",\"));\n plugin.getPVConfig().addItemKey(key, cmds);\n plugin.getPVConfig().saveKeys();\n }\n }\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }, 20);\n }\n\n public void sendBungeeSync() {\n if (!plugin.getPVConfig().bungeeSyncEnabled()) {\n return;\n }\n\n for (String key : plugin.getPVConfig().getListKeys()) {\n ByteArrayDataOutput out = ByteStreams.newDataOutput();\n //operation\n out.writeUTF(\"send\");\n out.writeUTF(\"keys\");\n\n out.writeUTF(key);\n String[] kinfo = plugin.getPVConfig().getKeyInfo(key);\n out.writeUTF(kinfo[0]);\n out.writeUTF(kinfo[1]);\n out.writeUTF(kinfo[2]);\n sendPendentBungee(out.toByteArray());\n }\n for (String key : plugin.getPVConfig().getItemListKeys()) {\n ByteArrayDataOutput out = ByteStreams.newDataOutput();\n //operation\n out.writeUTF(\"send\");\n out.writeUTF(\"itemkeys\");\n\n out.writeUTF(key);\n List<String> kinfo = plugin.getPVConfig().getItemKeyCmds(key);\n out.writeUTF(Arrays.toString(kinfo.toArray()));\n sendPendentBungee(out.toByteArray());\n }\n for (String uuid : plugin.getPVConfig().getAllVips().keySet()) {\n ByteArrayDataOutput out = ByteStreams.newDataOutput();\n for (String[] vip : plugin.getPVConfig().getAllVips().get(uuid)) {\n //operation\n out.writeUTF(\"send\");\n out.writeUTF(\"vips\");\n out.writeUTF(uuid);\n for (String vipinfo : vip) {\n out.writeUTF(vipinfo);\n }\n sendPendentBungee(out.toByteArray());\n }\n }\n }\n\n private void sendPendentBungee(final byte[] out) {\n if (plugin.serv.getOnlinePlayers().size() > 0) {\n Player play = Iterables.getFirst(plugin.serv.getOnlinePlayers(), null);\n play.sendPluginMessage(plugin, \"bungee:pixelvip\", out);\n } else {\n pendentBytes.add(out);\n }\n }\n\n @EventHandler\n public void onPlayerJoin(PlayerJoinEvent e) {\n if (!plugin.getPVConfig().bungeeSyncEnabled()) {\n return;\n }\n Player p = e.getPlayer();\n plugin.serv.getScheduler().runTaskLater(plugin, () -> {\n if (p.isOnline()) {\n for (byte[] b : pendentBytes) {\n p.sendPluginMessage(plugin, \"PixelVipBungee\", b);\n }\n pendentBytes.clear();\n }\n }, 40);\n }\n}", "public class PVCommands implements CommandExecutor, TabCompleter, Listener {\n\n private final PixelVip plugin;\n private final List<String> cmdWait;\n\n public PVCommands(PixelVip plugin) {\n this.plugin = plugin;\n this.cmdWait = new ArrayList<>();\n plugin.serv.getPluginManager().registerEvents(this, plugin);\n\n plugin.getCommand(\"delkey\").setExecutor(this);\n plugin.getCommand(\"newkey\").setExecutor(this);\n plugin.getCommand(\"sendkey\").setExecutor(this);\n plugin.getCommand(\"newitemkey\").setExecutor(this);\n plugin.getCommand(\"newukey\").setExecutor(this);\n plugin.getCommand(\"additemkey\").setExecutor(this);\n plugin.getCommand(\"listkeys\").setExecutor(this);\n plugin.getCommand(\"usekey\").setExecutor(this);\n plugin.getCommand(\"viptime\").setExecutor(this);\n plugin.getCommand(\"removevip\").setExecutor(this);\n plugin.getCommand(\"setactive\").setExecutor(this);\n plugin.getCommand(\"addvip\").setExecutor(this);\n plugin.getCommand(\"setvip\").setExecutor(this);\n plugin.getCommand(\"pixelvip\").setExecutor(this);\n plugin.getCommand(\"listvips\").setExecutor(this);\n plugin.getCommand(\"givepackage\").setExecutor(this);\n plugin.getCommand(\"getvariant\").setExecutor(this);\n plugin.getCommand(\"listpackages\").setExecutor(this);\n plugin.getCommand(\"addpackage\").setExecutor(this);\n plugin.getCommand(\"delpackage\").setExecutor(this);\n }\n\n @Override\n public List<String> onTabComplete(CommandSender sender, Command cmd, String alias, String[] args) {\n\n if (args.length == 1) {\n if (cmd.getName().equalsIgnoreCase(\"newkey\") || cmd.getName().equalsIgnoreCase(\"newukey\")) {\n List<String> list = new ArrayList<>(plugin.getPVConfig().getGroupList(false));\n list.replaceAll(g -> plugin.getUtil().removeColor(g));\n return list;\n }\n if (sender instanceof Player && cmd.getName().equalsIgnoreCase(\"setactive\")) {\n Player p = (Player) sender;\n List<String> list = new ArrayList<>();\n for (String[] vip : plugin.getPVConfig().getVipInfo(p.getUniqueId().toString())) {\n list.add(ChatColor.stripColor(plugin.getPVConfig().getVipTitle(vip[1])));\n }\n return list;\n }\n if (cmd.getName().equalsIgnoreCase(\"delpackage\")) {\n return new ArrayList<>(plugin.getPackageManager().getPackages().getConfigurationSection(\"packages\").getKeys(false));\n }\n }\n if (args.length == 2) {\n if (cmd.getName().equalsIgnoreCase(\"setvip\") ||\n cmd.getName().equalsIgnoreCase(\"addvip\") ||\n cmd.getName().equalsIgnoreCase(\"removevip\")) {\n List<String> list = new ArrayList<>(plugin.getPVConfig().getGroupList(false));\n list.replaceAll(g -> plugin.getUtil().removeColor(g));\n return list;\n }\n if (cmd.getName().equalsIgnoreCase(\"givepackage\")) {\n return new ArrayList<>(plugin.getPackageManager().getPackages().getConfigurationSection(\"packages\").getKeys(false));\n }\n if (cmd.getName().equalsIgnoreCase(\"addpackage\")) {\n return Arrays.asList(\"hand\", \"command\");\n }\n }\n\n if (cmd.getName().equalsIgnoreCase(\"pixelvip\") && args.length == 1) {\n return Arrays.asList(\"reload\", \"mysqlToFile\", \"fileToMysql\");\n }\n return null;\n }\n\n @EventHandler\n public void onChat(AsyncPlayerChatEvent e) {\n Player sender = e.getPlayer();\n if (plugin.getPackageManager().hasPendingPlayer(sender)) {\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"pendent\")));\n for (String pend : plugin.getPackageManager().getPendingVariant(sender)) {\n givePackage(sender, new String[]{sender.getName(), pend}, false);\n }\n e.setCancelled(true);\n }\n }\n\n @Override\n public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {\n if (sender instanceof Player && !plugin.getPVConfig().worldAllowed(((Player) sender).getWorld())) {\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"cmdNotAllowedWorld\")));\n return true;\n }\n\n if (sender instanceof Player) {\n if (plugin.getPackageManager().hasPendingPlayer((Player) sender) && !cmd.getName().equalsIgnoreCase(\"getvariant\")) {\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"pendent\")));\n for (String pend : plugin.getPackageManager().getPendingVariant((Player) sender)) {\n givePackage(sender, new String[]{sender.getName(), pend}, false);\n }\n return true;\n }\n\n if (cmdWait.contains(sender.getName())) {\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"wait-cmd\")));\n return true;\n } else {\n cmdWait.add(sender.getName());\n Bukkit.getScheduler().runTaskLater(plugin, () -> cmdWait.remove(sender.getName()), 200);\n }\n }\n\n Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {\n boolean success = true;\n if (cmd.getName().equalsIgnoreCase(\"delkey\")) {\n success = delKey(sender, args);\n }\n\n if (cmd.getName().equalsIgnoreCase(\"newkey\")) {\n success = newKey(sender, args, false);\n }\n\n if (cmd.getName().equalsIgnoreCase(\"newukey\")) {\n success = newUniqueKey(sender, args);\n }\n\n if (cmd.getName().equalsIgnoreCase(\"sendkey\")) {\n success = sendKey(args);\n }\n\n if (cmd.getName().equalsIgnoreCase(\"newitemkey\")) {\n success = newItemKey(sender, args);\n }\n\n if (cmd.getName().equalsIgnoreCase(\"additemkey\")) {\n success = addItemKey(sender, args);\n }\n\n if (cmd.getName().equalsIgnoreCase(\"listkeys\")) {\n success = listKeys(sender);\n }\n\n if (cmd.getName().equalsIgnoreCase(\"usekey\")) {\n success = useKey(sender, args);\n }\n\n if (cmd.getName().equalsIgnoreCase(\"viptime\")) {\n success = vipTime(sender, args);\n }\n\n if (cmd.getName().equalsIgnoreCase(\"removevip\")) {\n success = removeVip(sender, args);\n }\n\n if (cmd.getName().equalsIgnoreCase(\"setactive\")) {\n success = setActive(sender, args);\n }\n\n if (cmd.getName().equalsIgnoreCase(\"addvip\")) {\n success = addVip(sender, args);\n }\n\n if (cmd.getName().equalsIgnoreCase(\"setvip\")) {\n success = setVip(sender, args);\n }\n\n if (cmd.getName().equalsIgnoreCase(\"pixelvip\")) {\n success = mainCommand(sender, args);\n }\n\n if (cmd.getName().equalsIgnoreCase(\"listvips\")) {\n success = listVips(sender, args);\n }\n\n if (cmd.getName().equalsIgnoreCase(\"givepackage\")) {\n success = givePackage(sender, args, true);\n }\n\n if (cmd.getName().equalsIgnoreCase(\"getvariant\")) {\n success = getVariant(sender, args);\n }\n\n if (cmd.getName().equalsIgnoreCase(\"listpackages\")) {\n success = listPackages(sender);\n }\n\n if (cmd.getName().equalsIgnoreCase(\"addpackage\")) {\n success = addPackage(sender, args);\n }\n\n if (cmd.getName().equalsIgnoreCase(\"delpackage\")) {\n success = delPackage(sender, args);\n }\n if (!success) {\n sender.sendMessage(cmd.getDescription());\n sender.sendMessage(cmd.getUsage());\n }\n cmdWait.remove(sender.getName());\n });\n return true;\n }\n\n private boolean delPackage(CommandSender sender, String[] args) {\n if (args.length == 1) {\n PackageManager packages = plugin.getPackageManager();\n String id = args[0];\n if (packages.getPackage(id) == null) {\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&',\n plugin.getPVConfig().getLang(\"_pluginTag\") + packages.getPackages().getString(\"strings.no-package\").replace(\"{id}\", id)));\n return true;\n }\n packages.getPackages().set(\"packages.\" + id, null);\n packages.save();\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&',\n plugin.getPVConfig().getLang(\"_pluginTag\") + packages.getPackages().getString(\"strings.removed\")));\n return true;\n }\n return false;\n }\n\n private boolean addPackage(CommandSender sender, String[] args) {\n PackageManager packages = plugin.getPackageManager();\n //itemstack: /addpackage <id> hand|command [command1, command2]\n if (args.length >= 2) {\n String id = args[0];\n if (packages.getPackage(id) != null) {\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&',\n plugin.getPVConfig().getLang(\"_pluginTag\") + packages.getPackages().getString(\"strings.exists\").replace(\"{id}\", id)));\n return true;\n }\n\n if (args.length == 2 && args[1].equalsIgnoreCase(\"hand\")) {\n if (!(sender instanceof Player)) {\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&',\n plugin.getPVConfig().getLang(\"_pluginTag\") + packages.getPackages().getString(\"strings.only-players\")));\n return true;\n }\n Player p = (Player) sender;\n if (p.getItemInHand().getType().equals(Material.AIR)) {\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&',\n plugin.getPVConfig().getLang(\"_pluginTag\") + packages.getPackages().getString(\"strings.hand-empty\")));\n return true;\n }\n String item = p.getItemInHand().getType().name();\n int amount = p.getItemInHand().getAmount();\n String cmd = packages.getPackages().getString(\"hand.cmd\", \"give {p} {item} {amount}\")\n .replace(\"{item}\", item)\n .replace(\"{amount}\", amount + \"\");\n\n packages.getPackages().set(\"packages.\" + id + \".commands\", Collections.singletonList(cmd));\n packages.save();\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&',\n plugin.getPVConfig().getLang(\"_pluginTag\") + packages.getPackages().getString(\"strings.added\")));\n return true;\n }\n if (args[1].equalsIgnoreCase(\"command\")) {\n args[0] = \"\";\n args[1] = \"\";\n List<String> cmds = fixArgs(args);\n packages.getPackages().set(\"packages.\" + id + \".commands\", cmds);\n packages.save();\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&',\n plugin.getPVConfig().getLang(\"_pluginTag\") + packages.getPackages().getString(\"strings.added\")));\n return true;\n }\n }\n return false;\n }\n\n private boolean listPackages(CommandSender sender) {\n sender.sendMessage(ChatColor.AQUA + \"PixelVip Packages:\");\n for (String pkg : plugin.getPackageManager().getPackages().getConfigurationSection(\"packages\").getKeys(false)) {\n sender.sendMessage(ChatColor.GREEN + \"ID: \" + pkg + \" - Variants: \" + (plugin.getPackageManager().getPackage(pkg).getVariants() != null));\n }\n return true;\n }\n\n private boolean getVariant(CommandSender sender, String[] args) {\n if (sender instanceof Player && args.length == 2) {\n Player p = (Player) sender;\n if (plugin.getPackageManager().hasPendingPlayer(p)) {\n String id = args[0];\n for (String idv : plugin.getPackageManager().getPendingVariant(p)) {\n if (idv.equalsIgnoreCase(id)) {\n PVPackage pkg = plugin.getPackageManager().getPackage(idv);\n if (pkg.hasVariant(args[1])) {\n pkg.giveVariant(p, args[1]);\n } else {\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&',\n plugin.getPVConfig().getLang(\"_pluginTag\") + plugin.getPackageManager().getPackages().getString(\"strings.no-pendent\")));\n }\n break;\n }\n }\n return true;\n } else {\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&',\n plugin.getPVConfig().getLang(\"_pluginTag\") + plugin.getPackageManager().getPackages().getString(\"strings.no-pendent\")));\n return true;\n }\n }\n return false;\n }\n\n private boolean givePackage(CommandSender sender, String[] args, boolean add) {\n if (args.length == 2) {\n if (plugin.serv.getPlayer(args[0]) != null) {\n YamlConfiguration packages = plugin.getPackageManager().getPackages();\n Player p = plugin.serv.getPlayer(args[0]);\n if (plugin.getPackageManager().getPackage(args[1]) != null) {\n PVPackage pkg = plugin.getPackageManager().getPackage(args[1]);\n pkg.runCommands(p);\n if (pkg.getVariants() != null) {\n\n //add for usage\n if (add) {\n List<String> pending = packages.getStringList(\"pending-variants.\" + p.getName());\n pending.add(pkg.getID());\n packages.set(\"pending-variants.\" + p.getName(), pending);\n try {\n packages.save(new File(plugin.getDataFolder(), \"packages.yml\"));\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n if (plugin.getPVConfig().getRoot().getBoolean(\"configs.spigot.clickKeySuggest\")) {\n SpigotText text = new SpigotText(ChatColor.translateAlternateColorCodes('&',\n plugin.getPVConfig().getLang(\"_pluginTag\") + packages.getString(\"packages.\" + pkg.getID() + \".variants.message\")), null, null, null);\n String start = \"\";\n for (String var : pkg.getVariants().keySet()) {\n text.getText().addExtra(new SpigotText(\n ChatColor.translateAlternateColorCodes('&', start + \"&e\" + var),\n null,\n String.format(\"/getvariant %s %s\", pkg.getID(), var),\n ChatColor.translateAlternateColorCodes('&', packages.getString(\"strings.hover-info\"))).getText());\n if (start.equals(\"\")) start = \", \";\n }\n text.sendMessage(p);\n } else {\n p.sendMessage(ChatColor.translateAlternateColorCodes('&',\n plugin.getPVConfig().getLang(\"_pluginTag\") + String.format(packages.getString(\"strings.use-cmd\"), pkg.getID())));\n\n StringBuilder vars = new StringBuilder();\n for (String var : pkg.getVariants().keySet()) {\n vars.append(\", \").append(var);\n }\n p.sendMessage(ChatColor.translateAlternateColorCodes('&',\n packages.getString(\"strings.variants\") + \"&e\" + vars.toString().substring(2)));\n }\n }\n return true;\n } else {\n sender.sendMessage(ChatColor.translateAlternateColorCodes('&',\n plugin.getPVConfig().getLang(\"_pluginTag\") + packages.getString(\"strings.no-package\").replace(\"{id}\", args[1])));\n p.sendMessage(ChatColor.translateAlternateColorCodes('&',\n plugin.getPVConfig().getLang(\"_pluginTag\") + plugin.getPVConfig().getLang(\"payment.noitems\").replace(\"{payment}\",\"Alert\")));\n }\n }\n }\n return false;\n }\n\n private boolean listVips(CommandSender sender, String[] args) {\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"list-of-vips\")));\n sender.sendMessage(plugin.getUtil().toColor(\"&b---------------------------------------------\"));\n\n if (args.length == 0) {\n HashMap<String, List<String[]>> vips = plugin.getPVConfig().getVipList();\n vips.forEach((uuid, vipinfolist) -> vipinfolist.forEach((vipinfo) -> {\n String pname = plugin.getServer().getOfflinePlayer(UUID.fromString(uuid)).getName();\n if (pname == null) {\n pname = vipinfo[4];\n }\n sender.sendMessage(plugin.getUtil().toColor(\"&7> Player &3\" + pname + \"&7:\"));\n sender.sendMessage(plugin.getUtil().toColor(\" \" + plugin.getPVConfig().getLang(\"timeGroup\") + plugin.getPVConfig().getVipTitle(vipinfo[1])));\n sender.sendMessage(plugin.getUtil().toColor(\" \" + plugin.getPVConfig().getLang(\"timeLeft\") + plugin.getUtil().millisToMessage(Long.parseLong(vipinfo[0]) - plugin.getUtil().getNowMillis())));\n }));\n sender.sendMessage(plugin.getUtil().toColor(\"&b---------------------------------------------\"));\n }\n\n if (args.length == 1) {\n if (args[0].equalsIgnoreCase(\"active\")) {\n HashMap<String, List<String[]>> vips = plugin.getPVConfig().getVipList();\n vips.forEach((uuid, vipinfolist) -> vipinfolist.forEach((vipinfo) -> {\n String pname = plugin.getServer().getOfflinePlayer(UUID.fromString(uuid)).getName();\n if (pname == null) {\n pname = vipinfo[4];\n }\n sender.sendMessage(plugin.getUtil().toColor(\"&7> Player &3\" + pname + \"&7:\"));\n sender.sendMessage(plugin.getUtil().toColor(\" \" + plugin.getPVConfig().getLang(\"timeGroup\") + plugin.getPVConfig().getVipTitle(vipinfo[1])));\n sender.sendMessage(plugin.getUtil().toColor(\" \" + plugin.getPVConfig().getLang(\"timeLeft\") + plugin.getUtil().millisToMessage(Long.parseLong(vipinfo[0]) - plugin.getUtil().getNowMillis())));\n }));\n sender.sendMessage(plugin.getUtil().toColor(\"&b---------------------------------------------\"));\n }\n if (args[0].equalsIgnoreCase(\"all\")) {\n HashMap<String, List<String[]>> vips = plugin.getPVConfig().getAllVips();\n vips.forEach((uuid, vipinfolist) -> vipinfolist.forEach((vipinfo) -> {\n String pname = plugin.getServer().getOfflinePlayer(UUID.fromString(uuid)).getName();\n if (pname == null) {\n pname = vipinfo[4];\n }\n long vipTime = vipinfo[3].equals(\"true\") ? Long.parseLong(vipinfo[0]) - plugin.getUtil().getNowMillis() : Long.parseLong(vipinfo[0]);\n sender.sendMessage(plugin.getUtil().toColor(\"&7> Player &3\" + pname + \"&7:\"));\n sender.sendMessage(plugin.getUtil().toColor(\" \" + plugin.getPVConfig().getLang(\"timeGroup\") + plugin.getPVConfig().getVipTitle(vipinfo[1])));\n sender.sendMessage(plugin.getUtil().toColor(\" \" + plugin.getPVConfig().getLang(\"timeLeft\") + plugin.getUtil().millisToMessage(vipTime)));\n sender.sendMessage(plugin.getUtil().toColor(\" \" + plugin.getPVConfig().getLang(\"timeActive\") + plugin.getPVConfig().getLang(vipinfo[3])));\n }));\n sender.sendMessage(plugin.getUtil().toColor(\"&b---------------------------------------------\"));\n }\n }\n return true;\n }\n\n private boolean mainCommand(CommandSender sender, String[] args) {\n if (args.length == 1) {\n if (args[0].equalsIgnoreCase(\"reload\")) {\n plugin.reloadCmd(sender);\n return true;\n }\n }\n if (sender instanceof ConsoleCommandSender) {\n if (args.length == 1) {\n if (args[0].equalsIgnoreCase(\"fileToMysql\")) {\n if (plugin.getPVConfig().getRoot().getString(\"configs.database.type\").equalsIgnoreCase(\"mysql\")) {\n sender.sendMessage(plugin.getUtil().toColor(\"&cYour database type is already Mysql. Use &4/pixelvip mysqlToFile &cif you want to convert to file.\"));\n return true;\n }\n plugin.getPVConfig().getRoot().set(\"configs.database.type\", \"mysql\");\n convertDB(new PVDataMysql(plugin));\n return true;\n }\n if (args[0].equalsIgnoreCase(\"mysqlToFile\")) {\n if (plugin.getPVConfig().getRoot().getString(\"configs.database.type\").equalsIgnoreCase(\"file\")) {\n sender.sendMessage(plugin.getUtil().toColor(\"&cYour database type is already File. Use &4/pixelvip fileToMysql &cif you want to convert to mysql.\"));\n return true;\n }\n plugin.getPVConfig().getRoot().set(\"configs.database.type\", \"file\");\n convertDB(new PVDataFile(plugin));\n return true;\n }\n }\n }\n return false;\n }\n\n private void convertDB(PVDataManager dm) {\n plugin.getPVConfig().getAllVips().forEach((uuid, vipInfo) -> {\n vipInfo.forEach(vips -> {\n dm.addRawVip(vips[1], uuid, Arrays.asList(vips[2].split(\"'\")), Long.valueOf(vips[0]), vips[4], plugin.getUtil().expiresOn(Long.valueOf(vips[0])), Boolean.parseBoolean(vips[3]));\n });\n });\n dm.saveVips();\n\n plugin.getPVConfig().getListKeys().forEach(key -> {\n String[] keyInfo = plugin.getPVConfig().getKeyInfo(key);\n dm.addRawKey(key, keyInfo[0], Long.parseLong(keyInfo[1]), Integer.parseInt(keyInfo[2]), Boolean.getBoolean(keyInfo[3]));\n });\n\n plugin.getPVConfig().getItemListKeys().forEach(key -> {\n dm.addRawItemKey(key, plugin.getPVConfig().getItemKeyCmds(key));\n });\n dm.saveKeys();\n\n plugin.getPVConfig().getAllTrans().forEach((payment, trans) -> {\n for (Map.Entry<String, String> tr : trans.entrySet()) {\n dm.addTras(payment, tr.getKey(), tr.getValue());\n }\n });\n\n dm.closeCon();\n plugin.getPVConfig().getCommConfig().saveConfig();\n plugin.reloadCmd(Bukkit.getConsoleSender());\n }\n\n private List<String> fixArgs(String[] args) {\n StringBuilder cmds = new StringBuilder();\n for (String arg : args) {\n cmds.append(arg).append(\" \");\n }\n String[] cmdsSplit = cmds.toString().split(\",\");\n List<String> cmdList = new ArrayList<String>();\n for (String cmd : cmdsSplit) {\n cmd = cmd.replace(\" \", \" \");\n if (cmd.length() <= 0) {\n continue;\n }\n if (cmd.startsWith(\" \")) {\n cmd = cmd.substring(1);\n }\n if (cmd.endsWith(\" \")) {\n cmd = cmd.substring(0, cmd.length() - 1);\n }\n cmdList.add(cmd);\n }\n return cmdList;\n }\n\n /**\n * Command to generate new item key.\n *\n * @return boolean\n */\n private boolean addItemKey(CommandSender sender, String[] args) {\n if (args.length >= 2) {\n String key = args[0].toUpperCase();\n args[0] = \"\";\n\n List<String> cmds = fixArgs(args);\n plugin.getPVConfig().addItemKey(key, cmds);\n\n sender.sendMessage(plugin.getUtil().toColor(\"&b---------------------------------------------\"));\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"itemsAdded\")));\n plugin.getUtil().sendHoverKey(sender, key);\n for (String cmd : cmds) {\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"item\")) + cmd);\n }\n sender.sendMessage(plugin.getUtil().toColor(\"&b---------------------------------------------\"));\n return true;\n }\n\n return false;\n }\n\n /**\n * Command to generate new item key.\n *\n * @return boolean\n */\n private boolean newItemKey(CommandSender sender, String[] args) {\n if (args.length >= 1) {\n List<String> cmds = fixArgs(args);\n String key = plugin.getUtil().genKey(plugin.getPVConfig().getInt(10, \"configs.key-size\"));\n plugin.getPVConfig().addItemKey(key, cmds);\n\n sender.sendMessage(plugin.getUtil().toColor(\"&b---------------------------------------------\"));\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"keyGenerated\")));\n plugin.getUtil().sendHoverKey(sender, key);\n for (String cmd : cmds) {\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"item\")) + cmd);\n }\n sender.sendMessage(plugin.getUtil().toColor(\"&b---------------------------------------------\"));\n return true;\n }\n\n return false;\n }\n\n private boolean delKey(CommandSender sender, String[] args) {\n if (args.length == 1) {\n boolean removed = false;\n if (plugin.getPVConfig().delKey(args[0], 1))\n removed = true;\n if (plugin.getPVConfig().delItemKey(args[0]))\n removed = true;\n\n if (removed) {\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"keyRemoved\") + args[0]));\n } else {\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"noKeyRemoved\")));\n }\n return true;\n }\n\n return false;\n }\n\n /**\n * Command to generate new key.\n *\n * @return boolean\n */\n private boolean newKey(CommandSender sender, String[] args, boolean isSend) {\n if (args.length == 2) {\n String group = plugin.getPVConfig().getVipByTitle(args[0]);\n long days;\n\n try {\n days = Long.parseLong(args[1]);\n } catch (NumberFormatException ex) {\n return false;\n }\n\n if (days <= 0) {\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"moreThanZero\")));\n return true;\n }\n\n if (!plugin.getPVConfig().groupExists(group)) {\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"noGroups\") + group));\n return true;\n }\n String key = plugin.getUtil().genKey(plugin.getPVConfig().getInt(10, \"configs.key-size\"));\n plugin.getPVConfig().addKey(key, group, plugin.getUtil().dayToMillis(days), 1);\n if (isSend) {\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"keySendTo\")));\n } else {\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"keyGenerated\")));\n }\n plugin.getUtil().sendHoverKey(sender, key);\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"timeGroup\") + plugin.getPVConfig().getVipTitle(group)));\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"totalTime\") + days));\n return true;\n }\n\n if (args.length == 3) {\n String group = plugin.getPVConfig().getVipByTitle(args[0]);\n long days;\n int uses;\n\n try {\n days = Long.parseLong(args[1]);\n uses = Integer.parseInt(args[2]);\n } catch (NumberFormatException ex) {\n return false;\n }\n\n if (days <= 0) {\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"moreThanZero\")));\n return true;\n }\n\n if (uses <= 0) {\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"moreThanZero\")));\n return true;\n }\n\n if (!plugin.getPVConfig().groupExists(group)) {\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"noGroups\") + group));\n return true;\n }\n String key = plugin.getUtil().genKey(plugin.getPVConfig().getInt(10, \"configs.key-size\"));\n plugin.getPVConfig().addKey(key, group, plugin.getUtil().dayToMillis(days), uses);\n if (isSend) {\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"keySendTo\")));\n } else {\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"keyGenerated\")));\n }\n plugin.getUtil().sendHoverKey(sender, key);\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"timeGroup\") + plugin.getPVConfig().getVipTitle(group)));\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"totalTime\") + days));\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"infoUses\") + uses));\n return true;\n }\n return false;\n }\n\n\n /**\n * Command to generate new key.\n *\n * @return boolean\n */\n private boolean newUniqueKey(CommandSender sender, String[] args) {\n if (args.length == 2) {\n String group = plugin.getPVConfig().getVipByTitle(args[0]);\n long days;\n\n try {\n days = Long.parseLong(args[1]);\n } catch (NumberFormatException ex) {\n return false;\n }\n\n if (days <= 0) {\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"moreThanZero\")));\n return true;\n }\n\n if (!plugin.getPVConfig().groupExists(group)) {\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"noGroups\") + group));\n return true;\n }\n String key = plugin.getUtil().genKey(plugin.getPVConfig().getInt(10, \"configs.key-size\"));\n plugin.getPVConfig().addUniqueKey(key, group, plugin.getUtil().dayToMillis(days));\n\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"uniqueKeyGenerated\")));\n\n plugin.getUtil().sendHoverKey(sender, key);\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"timeGroup\") + plugin.getPVConfig().getVipTitle(group)));\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"totalTime\") + days));\n return true;\n }\n return false;\n }\n\n /**\n * Command to send a new key to a player.\n *\n * @return boolean\n */\n private boolean sendKey(String[] args) {\n if (args.length == 2) {\n if (plugin.serv.getPlayer(args[0]) == null) {\n return false;\n }\n if (!plugin.getPVConfig().getListKeys().contains(args[1])) {\n return false;\n }\n Player play = plugin.serv.getPlayer(args[0]);\n String[] keyInfo = plugin.getPVConfig().getKeyInfo(args[1]);\n\n play.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"keySendTo\")));\n plugin.getUtil().sendHoverKey(play, args[1]);\n play.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"timeGroup\") + plugin.getPVConfig().getVipTitle(keyInfo[0])));\n play.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"totalTime\") + plugin.getUtil().millisToDay(keyInfo[1])));\n play.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"infoUses\") + keyInfo[2]));\n return true;\n }\n\n if (args.length == 3 || args.length == 4) {\n String[] nargs = new String[args.length - 1];\n String splay = args[0];\n if (plugin.serv.getPlayer(splay) == null) {\n return false;\n }\n Player play = plugin.serv.getPlayer(splay);\n for (int i = 0; i < args.length; i++) {\n if (i + 1 == args.length) {\n break;\n }\n nargs[i] = args[i + 1];\n }\n return newKey(play, nargs, true);\n }\n return false;\n }\n\n /**\n * Command to list all available keys, and key's info.\n *\n * @return CommandSpec\n */\n public boolean listKeys(CommandSender sender) {\n Collection<String> keys = plugin.getPVConfig().getListKeys();\n Collection<String> itemKeys = plugin.getPVConfig().getItemListKeys();\n int i = 0;\n if (keys.size() > 0) {\n sender.sendMessage(plugin.getUtil().toColor(\"&b---------------------------------------------\"));\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"listKeys\")));\n for (Object key : keys) {\n String[] keyinfo = plugin.getPVConfig().getKeyInfo(key.toString());\n long days = plugin.getUtil().millisToDay(keyinfo[1]);\n sender.sendMessage(plugin.getUtil().toColor(\"&b- Key: &6\" + key.toString() + \"&b | Group: &6\" + keyinfo[0] + \"&b | Days: &6\" + days + \"&b | Uses left: &6\" + keyinfo[2]));\n i++;\n }\n }\n\n if (itemKeys.size() > 0) {\n sender.sendMessage(plugin.getUtil().toColor(\"&b---------------------------------------------\"));\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"listItemKeys\")));\n for (Object key : itemKeys) {\n List<String> cmds = plugin.getPVConfig().getItemKeyCmds(key.toString());\n plugin.getUtil().sendHoverKey(sender, key.toString());\n for (String cmd : cmds) {\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"item\")) + cmd);\n }\n i++;\n }\n }\n if (i == 0) {\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"noKeys\")));\n } else {\n sender.sendMessage(plugin.getUtil().toColor(\"&b---------------------------------------------\"));\n }\n return true;\n }\n\n /**\n * Command to activate a vip using a key.\n *\n * @return CommandSpec\n */\n public boolean useKey(CommandSender sender, String[] args) {\n if (args.length == 1) {\n if (sender instanceof Player) {\n Player p = (Player) sender;\n String key = args[0].toUpperCase();\n\n // Command alert\n if (plugin.getPVConfig().getRoot().getBoolean(\"configs.useKeyWarning\") && p.isOnline() && !key.isEmpty()) {\n if (!plugin.getPVConfig().commandAlert.containsKey(p.getName()) || !plugin.getPVConfig().commandAlert.get(p.getName()).equalsIgnoreCase(key)) {\n plugin.getPVConfig().commandAlert.put(p.getName(), key);\n p.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"confirmUsekey\")));\n return true;\n }\n plugin.getPVConfig().commandAlert.remove(p.getName());\n }\n\n if (!plugin.getPayments().isEmpty()) {\n for (PaymentModel pay : plugin.getPayments()) {\n plugin.processTrans.put(pay.getPayname(), key);\n if (pay.checkTransaction(p, key)) {\n return true;\n }\n }\n }\n plugin.getPVConfig().activateVip(p, key, \"\", 0, p.getName());\n } else {\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"onlyPlayers\")));\n }\n return true;\n }\n return false;\n }\n\n /**\n * Command to check the vip time.\n *\n * @return CommandSpec\n */\n public boolean vipTime(CommandSender sender, String[] args) {\n if (sender instanceof Player && args.length == 0) {\n plugin.getUtil().sendVipTime(sender, ((Player) sender).getUniqueId().toString(), sender.getName());\n return true;\n }\n if (args.length == 1 && sender.hasPermission(\"pixelvip.cmd.player.others\")) {\n String uuid = plugin.getPVConfig().getVipUUID(args[0]);\n if (uuid != null) {\n plugin.getUtil().sendVipTime(sender, uuid, args[0]);\n } else {\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"noPlayersByName\")));\n }\n return true;\n }\n return false;\n }\n\n /**\n * Command to remove a vip of player.\n *\n * @return CommandSpec\n */\n public boolean removeVip(CommandSender sender, String[] args) {\n if (args.length == 1) {\n String uuid = plugin.getPVConfig().getVipUUID(args[0]);\n if (uuid != null) {\n plugin.getPVConfig().removeVip(uuid, Optional.empty());\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"vipsRemoved\")));\n } else {\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"playerNotVip\")));\n }\n return true;\n }\n if (args.length == 2) {\n Optional<String> group = Optional.of(plugin.getPVConfig().getVipByTitle(args[1]));\n if (!plugin.getPVConfig().groupExists(group.get())) {\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"noGroups\") + args[1]));\n return true;\n }\n\n String uuid = plugin.getPVConfig().getVipUUID(args[0]);\n if (uuid != null) {\n plugin.getPVConfig().removeVip(uuid, group);\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"vipsRemoved\")));\n } else {\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"playerNotVip\")));\n }\n return true;\n }\n return false;\n }\n\n /**\n * Command to sets the active vip, if more than one key activated.\n *\n * @return CommandSpec\n */\n public boolean setActive(CommandSender sender, String[] args) {\n if (args.length == 1) {\n if (sender instanceof Player) {\n Player p = (Player) sender;\n String group = plugin.getPVConfig().getVipByTitle(args[0]);\n if (!plugin.getPVConfig().groupExists(group)) {\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"noGroups\") + args[0]));\n return true;\n }\n\n if (plugin.getPVConfig().isVipActive(group, p.getUniqueId().toString())) {\n p.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"activeVipSetTo\") + plugin.getPVConfig().getVipTitle(args[0])));\n return true;\n }\n\n List<String[]> vipInfo = plugin.getPVConfig().getVipInfo(p.getUniqueId().toString());\n\n if (vipInfo.size() > 0) {\n for (String[] vip : vipInfo) {\n if (vip[1].equalsIgnoreCase(group)) {\n plugin.getPVConfig().setActive(p.getUniqueId().toString(), vip[1], Arrays.asList(vip[2].split(\",\")));\n p.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"activeVipSetTo\") + plugin.getPVConfig().getVipTitle(vip[1])));\n return true;\n }\n }\n }\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"playerNotVip\")));\n return true;\n } else {\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"onlyPlayers\")));\n return true;\n }\n }\n if (args.length == 2 && sender.hasPermission(\"pixelvip.cmd.setactive\")) {\n String uuid = plugin.getPVConfig().getVipUUID(args[1]);\n if (uuid == null) {\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"noPlayersByName\")));\n return true;\n }\n String group = plugin.getPVConfig().getVipByTitle(args[0]);\n if (!plugin.getPVConfig().groupExists(group)) {\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"noGroups\") + args[0]));\n return true;\n }\n\n if (plugin.getPVConfig().isVipActive(group, uuid)) {\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"activeVipSetTo\") + plugin.getPVConfig().getVipTitle(args[0])));\n return true;\n }\n\n List<String[]> vipInfo = plugin.getPVConfig().getVipInfo(uuid);\n\n if (vipInfo.size() > 0) {\n for (String[] vip : vipInfo) {\n if (vip[1].equalsIgnoreCase(group)) {\n plugin.getPVConfig().setActive(uuid, vip[1], Arrays.asList(vip[2].split(\",\")));\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"activeVipSetTo\") + plugin.getPVConfig().getVipTitle(vip[1])));\n return true;\n }\n }\n }\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"noGroups\") + args[0]));\n return true;\n }\n return false;\n }\n\n /**\n * Command to add a vip for a player without key.\n *\n * @return CommandSpec\n */\n @SuppressWarnings(\"deprecation\")\n public boolean addVip(CommandSender sender, String[] args) {\n if (args.length == 3) {\n String pname = args[0];\n OfflinePlayer p = Bukkit.getOfflinePlayer(pname);\n if (p.getName() != null) {\n pname = p.getName();\n }\n String group = plugin.getPVConfig().getVipByTitle(args[1]);\n if (!plugin.getPVConfig().groupExists(group)) {\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"noGroups\") + args[1]));\n return true;\n }\n long days;\n try {\n days = Long.parseLong(args[2]);\n } catch (NumberFormatException ex) {\n return false;\n }\n plugin.getPVConfig().activateVip(p, null, group, days, pname);\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"vipAdded\")));\n return true;\n }\n return false;\n }\n\n /**\n * Command to set a vip without activation and without key.\n *\n * @return CommandSpec\n */\n @SuppressWarnings(\"deprecation\")\n public boolean setVip(CommandSender sender, String[] args) {\n if (args.length == 3) {\n String pname = args[0];\n String uuid = plugin.getPVConfig().getVipUUID(pname);\n if (uuid == null) {\n uuid = Bukkit.getOfflinePlayer(pname).getUniqueId().toString();\n }\n String group = plugin.getPVConfig().getVipByTitle(args[1]);\n if (!plugin.getPVConfig().groupExists(group)) {\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"noGroups\") + group));\n return true;\n }\n long days;\n try {\n days = Long.parseLong(args[2]);\n } catch (NumberFormatException ex) {\n return false;\n }\n plugin.getPVConfig().setVip(uuid, group, plugin.getUtil().dayToMillis(days), pname);\n sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang(\"_pluginTag\", \"vipSet\")));\n return true;\n }\n return false;\n }\n}", "public class PVConfig {\n\n public HashMap<String, String> commandAlert = new HashMap<>();\n private final PixelVip plugin;\n private int delay = 0;\n private PVDataManager dataManager;\n private final CommentedConfig comConfig;\n private final CommentedConfig apisConfig;\n private final CommentedConfig uniqueKeys;\n\n public PVConfig(PixelVip plugin) {\n this.plugin = plugin;\n\n /*----------------------------------------------------------------------------------*/\n\n String header = \"=============== PixelVip Configuration Options ================\\n\" +\n \"The configuration is commented! If you need more help or have issues, use our github:\\n\" +\n \"https://github.com/FabioZumbi12/PixelVip\\n\" +\n \"\\n\" +\n \"Pixelvip by FabioZumbi12\";\n\n comConfig = new CommentedConfig(new File(plugin.getDataFolder(), \"config.yml\"), plugin.getConfig(), header);\n\n comConfig.setDefault(\"groups\", null, \"Group names like is in your permissions plugin (case sensitive)!\\n\" +\n \"Available placeholders: \\n\" +\n \"- {p|player} = Players Name\\n\" +\n \"- {vip} = Vip Group\\n\" +\n \"- {playergroup} = Player Group before Vip activation\\n\" +\n \"- {days} = Days of activated Vip\");\n if (comConfig.configurations.contains(\"groups\") && !comConfig.configurations.getConfigurationSection(\"groups\").getKeys(false).isEmpty()) {\n comConfig.configurations.getConfigurationSection(\"groups\").getKeys(false).forEach(g -> {\n comConfig.setDefault(\"groups.\" + g + \".title\", g);\n comConfig.setDefault(\"groups.\" + g + \".commands\", new ArrayList<>());\n comConfig.setDefault(\"groups.\" + g + \".cmdChances.0\", new ArrayList<>());\n comConfig.setDefault(\"groups.\" + g + \".run-on-vip-finish\", new ArrayList<>());\n comConfig.setDefault(\"groups.\" + g + \".essentials-kit\", g);\n });\n } else {\n comConfig.setDefault(\"groups.vipExample\", null, \"This is an Example of vip group properties.\\nCopy or use this as example to setups all your other groups.\");\n comConfig.setDefault(\"groups.vipExample.essentials-kit\", \"ExampleKit\", \"Put the Essentials kit name to freeze the kit time when this vip is not in use.\\nThis is anti-exploit.\");\n comConfig.setDefault(\"groups.vipExample.title\", \"&bVip Example\", \"Title to use on commands and to show on chat.\");\n comConfig.setDefault(\"groups.vipExample.commands\", Arrays.asList(\"broadcast &aThe player &6{p} &ahas acquired your &6{vip} &afor &6{days} &adays\", \"give {p} minecraft:diamond 10\", \"eco give {p} 10000\"),\n \"Add the commands to run when the player use the key for activation \\n\" +\n \"You can use the variables:\\n\" +\n \"{p|player} = Player name, {vip} = Vip group, {days} = Vip days, {playergroup} = Player group before activate vip\");\n comConfig.setDefault(\"groups.vipExample.cmdChances\", null,\n \"Add commands here to give items to players based on chances.\\n\" +\n \"Use 1 - 100 for add chance commands.\");\n comConfig.setDefault(\"groups.vipExample.cmdChances.50\", Collections.singletonList(\"give {p} minecraft:diamond_block 5\"));\n comConfig.setDefault(\"groups.vipExample.cmdChances.30\", Collections.singletonList(\"give {p} minecraft:mob_spawner 1\"));\n comConfig.setDefault(\"groups.vipExample.run-on-vip-finish\", Collections.singletonList(\"broadcast [Example message from PixelVip on run-on-vip-finish] The vip of {p} (Vip {vip}) has ended and now is back to {playergroup}!\"), \"Commands to run on this vip ends.\");\n }\n\n //database\n comConfig.setDefault(\"configs.database.type\", \"file\", \"Options: \\\"file\\\" or \\\"mysql\\\"\");\n comConfig.setDefault(\"configs.database.mysql\", null, \"Database configuration!\\n\" +\n \"H2 uri: \\\"jdbc:h2:%s/pixelvip.db;mode=MySQL\\\" (%s will be replaced by pixelvip path)\\n\" +\n \"Mysql uri: \\\"jdbc:mysql://localhost:3306/\\\"\");\n comConfig.setDefault(\"configs.database.mysql.host\", \"jdbc:mysql://localhost:3306/\");\n comConfig.setDefault(\"configs.database.mysql.db-name\", \"pixelvip\");\n comConfig.setDefault(\"configs.database.mysql.username\", \"user\");\n comConfig.setDefault(\"configs.database.mysql.password\", \"pass\");\n\n comConfig.setDefault(\"configs.database.mysql.keys.table-name\", \"pixelvip_keys\");\n comConfig.setDefault(\"configs.database.mysql.keys.columns.key\", \"col_key\");\n comConfig.setDefault(\"configs.database.mysql.keys.columns.group\", \"col_group\");\n comConfig.setDefault(\"configs.database.mysql.keys.columns.duration\", \"col_duration\");\n comConfig.setDefault(\"configs.database.mysql.keys.columns.uses\", \"col_uses\");\n comConfig.setDefault(\"configs.database.mysql.keys.columns.unique\", \"col_unique\");\n comConfig.setDefault(\"configs.database.mysql.keys.columns.cmds\", \"col_cmds\");\n comConfig.setDefault(\"configs.database.mysql.keys.columns.info\", \"col_info\");\n comConfig.setDefault(\"configs.database.mysql.keys.columns.comments\", \"col_comments\");\n\n comConfig.setDefault(\"configs.database.mysql.vips.table-name\", \"pixelvip_vips\");\n comConfig.setDefault(\"configs.database.mysql.vips.columns.uuid\", \"col_uuid\");\n comConfig.setDefault(\"configs.database.mysql.vips.columns.vip\", \"col_vip\");\n comConfig.setDefault(\"configs.database.mysql.vips.columns.playerGroup\", \"col_playerGroup\");\n comConfig.setDefault(\"configs.database.mysql.vips.columns.duration\", \"col_duration\");\n comConfig.setDefault(\"configs.database.mysql.vips.columns.nick\", \"col_nick\");\n comConfig.setDefault(\"configs.database.mysql.vips.columns.expires-on-exact\", \"col_expires\");\n comConfig.setDefault(\"configs.database.mysql.vips.columns.active\", \"col_active\");\n comConfig.setDefault(\"configs.database.mysql.vips.columns.kits\", \"col_kits\");\n comConfig.setDefault(\"configs.database.mysql.vips.columns.comments\", \"col_comments\");\n\n comConfig.setDefault(\"configs.database.mysql.transactions.table-name\", \"pixelvip_transactions\");\n comConfig.setDefault(\"configs.database.mysql.transactions.columns.idt\", \"col_idt\");\n comConfig.setDefault(\"configs.database.mysql.transactions.columns.payment\", \"col_payment\");\n comConfig.setDefault(\"configs.database.mysql.transactions.columns.nick\", \"col_nick\");\n //end database\n\n try {\n plugin.serv.spigot();\n comConfig.setDefault(\"configs.spigot.clickKeySuggest\", true);\n } catch (NoSuchMethodError e) {\n comConfig.setDefault(\"configs.spigot.clickKeySuggest\", false);\n }\n comConfig.setDefault(\"configs.spigot.clickSuggest\", \"/usekey {key}\");\n\n comConfig.setDefault(\"configs.key-size\", 10, \"Sets the length of your vip keys.\");\n\n comConfig.setDefault(\"configs.useKeyWarning\", true, \"Should we alert the player about free inventory space before use the key?\");\n\n comConfig.setDefault(\"configs.Vault.use\", true);\n comConfig.setDefault(\"configs.Vault.mode\", \"set\");\n\n comConfig.setDefault(\"configs.cmdToReloadPermPlugin\", \"\", \"Command to reload the permissions plugin after some action.\");\n comConfig.setDefault(\"configs.cmdOnRemoveVip\", \"lp user {p} parent remove {vip}\", \"Command to run when a vip is removed by command.\");\n comConfig.setDefault(\"configs.commandsToRunOnVipFinish\", Collections.singletonList(\"nick {p} off\"),\n \"Run this commands when the vip of a player finish.\\n\" +\n \"Variables: {p|player} get the player name, {vip} get the actual vip, {playergroup} get the group before the player activate your vip.\");\n comConfig.setDefault(\"configs.commandsToRunOnChangeVip\", Arrays.asList(\"lp user {p} parent set {newvip}\",\n \"lp user {p} parent remove {oldvip}\"),\n \"Run this commands on player change your vip to other.\\n\" +\n \"Variables: {p|player} get the player name, {newvip} get the new vip, {oldvip} get the vip group before change.\");\n comConfig.setDefault(\"configs.queueCmdsForOfflinePlayers\", false);\n Set<String> worlds = new HashSet<>(comConfig.configurations.getStringList(\"configs.worldCmdsAllowed\"));\n for (World w : Bukkit.getWorlds()) {\n worlds.add(w.getName());\n }\n comConfig.setDefault(\"configs.worldCmdsAllowed\", new ArrayList<>(worlds));\n comConfig.setDefault(\"bungee.enableSync\", false);\n comConfig.setDefault(\"bungee.serverID\", \"server1\");\n\n\n //strings\n comConfig.setDefault(\"strings._pluginTag\", \"&7[&6PixelVip&7] \");\n comConfig.setDefault(\"strings.noPlayersByName\", \"&cTheres no players with this name!\");\n comConfig.setDefault(\"strings.onlyPlayers\", \"&cOnly players ca use this command!\");\n comConfig.setDefault(\"strings.noKeys\", \"&aTheres no available keys! Use &6/newkey &aor &6/newikey &ato generate one.\");\n comConfig.setDefault(\"strings.listKeys\", \"&aList of Keys:\");\n comConfig.setDefault(\"strings.listItemKeys\", \"&aList of Item Keys:\");\n comConfig.setDefault(\"strings.vipInfoFor\", \"&aVip info for \");\n comConfig.setDefault(\"strings.playerNotVip\", \"&cThis player(or you) is not VIP!\");\n comConfig.setDefault(\"strings.moreThanZero\", \"&cThis number need to be more than 0\");\n comConfig.setDefault(\"strings.keyGenerated\", \"&aGenerated a key with the following:\");\n comConfig.setDefault(\"strings.uniqueKeyGenerated\", \"&aGenerated a unique key with the following:\");\n comConfig.setDefault(\"strings.keySendTo\", \"&aYou received a key with the following:\");\n comConfig.setDefault(\"strings.invalidKey\", \"&cThis key is invalid or not exists!\");\n comConfig.setDefault(\"strings.vipActivated\", \"&aVip activated with success:\");\n comConfig.setDefault(\"strings.usesLeftActivation\", \"&bThis key can be used for more: &6{uses} &btimes.\");\n comConfig.setDefault(\"strings.headingLine\", \"&b---------------------------------------------\");\n comConfig.setDefault(\"strings.activeVip\", \"&b- Vip: &6{vip}\");\n comConfig.setDefault(\"strings.activeDays\", \"&b- Days: &6{days} &bdays\");\n comConfig.setDefault(\"strings.timeLeft\", \"&b- Time left: &6\");\n comConfig.setDefault(\"strings.totalTime\", \"&b- Days: &6\");\n comConfig.setDefault(\"strings.timeKey\", \"&b- Key: &6\");\n comConfig.setDefault(\"strings.hoverKey\", \"&7&o(Click to get the Key)&r\");\n comConfig.setDefault(\"strings.timeGroup\", \"&b- Vip: &6\");\n comConfig.setDefault(\"strings.timeActive\", \"&b- In Use: &6\");\n comConfig.setDefault(\"strings.infoUses\", \"&b- Uses left: &6\");\n comConfig.setDefault(\"strings.alreadyUsedUniqueKey\", \"&cYou have used this key before!\");\n comConfig.setDefault(\"strings.activeVipSetTo\", \"&aYour active VIP is \");\n comConfig.setDefault(\"strings.noGroups\", \"&cNo groups with name &6\");\n comConfig.setDefault(\"strings.days\", \" &bdays\");\n comConfig.setDefault(\"strings.hours\", \" &bhours\");\n comConfig.setDefault(\"strings.minutes\", \" &bminutes\");\n comConfig.setDefault(\"strings.and\", \" &band\");\n comConfig.setDefault(\"strings.vipEnded\", \" &bYour vip &6{vip} &bhas ended. &eWe hope you enjoyed your Vip time &a:D\");\n comConfig.setDefault(\"strings.lessThan\", \"&6Less than one minute to end your vip...\");\n comConfig.setDefault(\"strings.vipsRemoved\", \"&aVip(s) of player removed with success!\");\n comConfig.setDefault(\"strings.vipSet\", \"&aVip set with success for this player!\");\n comConfig.setDefault(\"strings.sync-groups\", \"&aGroup configs send to all servers!\");\n comConfig.setDefault(\"strings.list-of-vips\", \"&aList of active VIPs: \");\n comConfig.setDefault(\"strings.vipAdded\", \"&aVip added with success for this player!\");\n comConfig.setDefault(\"strings.item\", \"&a-- Item: &b\");\n comConfig.setDefault(\"strings.itemsGiven\", \"&aGiven {items} item(s) using a key.\");\n comConfig.setDefault(\"strings.itemsAdded\", \"&aItem(s) added to key:\");\n comConfig.setDefault(\"strings.keyRemoved\", \"&aKey removed with success: &b\");\n comConfig.setDefault(\"strings.noKeyRemoved\", \"&cTheres no keys to remove!\");\n comConfig.setDefault(\"strings.cmdNotAllowedWorld\", \"&cThis command is not allowed in this world!\");\n comConfig.setDefault(\"strings.true\", \"&atrue\");\n comConfig.setDefault(\"strings.false\", \"&cfalse\");\n comConfig.setDefault(\"strings.reload\", \"&aPixelvip reloaded with success!\");\n comConfig.setDefault(\"strings.wait-cmd\", \"&cWait before use a pixelvip command again!\");\n comConfig.setDefault(\"strings.confirmUsekey\", \"&4Warning: &cMake sure you have free space on your inventory to use this key for your vip or items. &6Use the same command again to confirm!\");\n comConfig.setDefault(\"strings.pendent\", \"&cYou have some pendent activation(s) to use. Please select one before continue!\");\n\n comConfig.setDefault(\"strings.payment.waiting\", \"&c{payment}: Your purchase has not yet been approved!\");\n comConfig.setDefault(\"strings.payment.codeused\", \"&c{payment}: This code has already been used!\");\n comConfig.setDefault(\"strings.payment.expired\", \"&c{payment}: This code has expired!\");\n comConfig.setDefault(\"strings.payment.noitems\", \"&c{payment}: No items delivered. Code: {transaction} - Print this message and send to an Administrator!\");\n /*---------------------------------------------------------*/\n\n // Apis configs\n String apiHeader = \"=============== PixelVip Payment APIs Options ================\\n\" +\n \"The configuration is commented! If you need more help or have issues, use our github:\\n\" +\n \"https://github.com/FabioZumbi12/PixelVip/wiki/(2)-Payments-APIs\\n\" +\n \"\\n\" +\n \"Pixelvip by FabioZumbi12\";\n apisConfig = new CommentedConfig(new File(plugin.getDataFolder(), \"apis.yml\"), new YamlConfiguration(), apiHeader);\n\n SimpleDateFormat sdf = new SimpleDateFormat(\"dd/MM/yyyy HH:mm:ss\");\n apisConfig.setDefault(\"apis.in-test\", false, \"Set this to true until you is testing the APIs.\\n\" +\n \"In test, we will not save the transaction codes.\\n\" +\n \"DONT FORGET TO SET THIS TO FALSE WHEN DONE YOUR TESTS!!\");\n\n apisConfig.setDefault(\"apis.pagseguro\", null, \"Wiki: https://github.com/FabioZumbi12/PixelVip/wiki/(2)-Payments-APIs#pagseguro-brazil\");\n apisConfig.setDefault(\"apis.pagseguro.use\", false);\n apisConfig.setDefault(\"apis.pagseguro.sandbox\", false);\n apisConfig.setDefault(\"apis.pagseguro.email\", \"your@email.com\");\n apisConfig.setDefault(\"apis.pagseguro.token\", \"yourtoken\");\n apisConfig.setDefault(\"apis.pagseguro.ignoreOldest\", sdf.format(Calendar.getInstance().getTime()));\n apisConfig.setDefault(\"apis.pagseguro.product-id-location\", \"ID\", \"Define se a identificação do produto vai ser pelo ID ou pela descrição.\\n\" +\n \"As opções são: \\\"ID\\\" ou \\\"DESCRICAO\\\"\\n\" +\n \"ID: Iremos verificar o REF, SKU ou ID do produto\\n\" +\n \"DESCRICAO: Iremos verificar se na descrição do produto, a primeira palavra é o id, ou se o id esta no meio da descrição iniciado com #\\n\" +\n \"Exemplo com código de pacote do PixelVip 999: \\n\" +\n \" - \\\"999 - Vip4 Elite\\\"\\n\" +\n \" - \\\"Vip4 Elite #999\\\"\");\n\n\n apisConfig.setDefault(\"apis.mercadopago\", null, \"Wiki: https://github.com/FabioZumbi12/PixelVip/wiki/(2)-Payments-APIs#mercadopago\");\n apisConfig.setDefault(\"apis.mercadopago.use\", false);\n apisConfig.setDefault(\"apis.mercadopago.sandbox\", false);\n apisConfig.setDefault(\"apis.mercadopago.access-token\", \"ACCESS-TOKEN\");\n apisConfig.setDefault(\"apis.mercadopago.ignoreOldest\", sdf.format(Calendar.getInstance().getTime()));\n apisConfig.setDefault(\"apis.mercadopago.product-id-location\", \"ID\", \"Define se a identificação do produto vai ser pelo ID ou pela descrição.\\n\" +\n \"As opções são: \\\"ID\\\" ou \\\"DESCRICAO\\\"\\n\" +\n \"ID: Iremos verificar o REF, SKU ou ID do produto\\n\" +\n \"DESCRICAO: Iremos verificar se na descrição do produto, a primeira palavra é o id, ou se o id esta no meio da descrição iniciado com #\\n\" +\n \"Exemplo com código de pacote do PixelVip 999: \\n\" +\n \" - \\\"999 - Vip4 Elite\\\"\\n\" +\n \" - \\\"Vip4 Elite #999\\\"\");\n\n\n apisConfig.setDefault(\"apis.paypal\", null, \"Wiki: https://github.com/FabioZumbi12/PixelVip/wiki/(2)-Payments-APIs#paypal\");\n apisConfig.setDefault(\"apis.paypal.use\", false);\n apisConfig.setDefault(\"apis.paypal.sandbox\", false);\n apisConfig.setDefault(\"apis.paypal.username\", \"username\");\n apisConfig.setDefault(\"apis.paypal.password\", \"password\");\n apisConfig.setDefault(\"apis.paypal.signature\", \"signature\");\n apisConfig.setDefault(\"apis.paypal.ignoreOldest\", sdf.format(Calendar.getInstance().getTime()));\n apisConfig.setDefault(\"apis.paypal.product-id-location\", \"ID\", \"Define se a identificação do produto vai ser pelo ID ou pela descrição.\\n\" +\n \"As opções são: \\\"ID\\\" ou \\\"DESCRICAO\\\"\\n\" +\n \"ID: Iremos verificar o REF, SKU ou ID do produto\\n\" +\n \"DESCRICAO: Iremos verificar se na descrição do produto, a primeira palavra é o id, ou se o id esta no meio da descrição iniciado com #\\n\" +\n \"Exemplo com código de pacote do PixelVip 999: \\n\" +\n \" - \\\"999 - Vip4 Elite\\\"\\n\" +\n \" - \\\"Vip4 Elite #999\\\"\");\n\n if (comConfig.configurations.getConfigurationSection(\"apis\") != null) {\n plugin.getPVLogger().warning(\"APIs configurations moved to 'apis.yml'\");\n comConfig.configurations.getConfigurationSection(\"apis\").getKeys(true).forEach((keys -> {\n apisConfig.configurations.set(\"apis.\" + keys, comConfig.configurations.get(\"apis.\" + keys));\n }));\n\n comConfig.configurations.set(\"apis\", null);\n }\n apisConfig.saveConfig();\n\n /*---------------------------------------------------------*/\n\n uniqueKeys = new CommentedConfig(new File(plugin.getDataFolder(), \"uniqueKeys.yml\"), new YamlConfiguration(), \"This keys are unique, allowed to be used only one time per player\");\n uniqueKeys.setDefault(\"keys\", null, null);\n\n uniqueKeys.saveConfig();\n\n /*---------------------------------------------------------*/\n //move vips to new file if is in config.yml\n\n if (comConfig.configurations.getConfigurationSection(\"activeVips\") != null) {\n plugin.getPVLogger().warning(\"Active Vips moved to file 'vips.yml'\");\n comConfig.configurations.getConfigurationSection(\"activeVips\").getKeys(false).forEach((group -> {\n comConfig.configurations.getConfigurationSection(\"activeVips.\" + group).getKeys(false).forEach((id) -> {\n dataManager.addRawVip(group, id,\n new ArrayList<>(Arrays.asList(comConfig.configurations.getString(\"activeVips.\" + group + \".\" + id + \".playerGroup\").split(\",\"))),\n comConfig.configurations.getLong(\"activeVips.\" + group + \".\" + id + \".duration\"),\n comConfig.configurations.getString(\"activeVips.\" + group + \".\" + id + \".nick\"),\n comConfig.configurations.getString(\"activeVips.\" + group + \".\" + id + \".expires-on-exact\"));\n dataManager.setVipActive(id, group, comConfig.configurations.getBoolean(\"activeVips.\" + group + \".\" + id + \".active\"));\n });\n }));\n\n comConfig.configurations.set(\"activeVips\", null);\n saveVips();\n }\n\n /*---------------------------------------------------------*/\n\n /*---------------------------------------------------------*/\n //move keys to new file if is in config.yml\n\n if (comConfig.configurations.getConfigurationSection(\"keys\") != null) {\n plugin.getPVLogger().warning(\"keys moved to file 'keys.yml'\");\n comConfig.configurations.getConfigurationSection(\"keys\").getKeys(false).forEach((key) -> {\n dataManager.addRawKey(key,\n comConfig.configurations.getString(\"keys.\" + key + \".group\"),\n comConfig.configurations.getLong(\"keys.\" + key + \".duration\"),\n comConfig.configurations.getInt(\"keys.\" + key + \".uses\"), false);\n });\n\n comConfig.configurations.set(\"keys\", null);\n saveKeys();\n }\n\n if (comConfig.configurations.getConfigurationSection(\"itemKeys\") != null) {\n plugin.getPVLogger().warning(\"itemKeys moved to file 'keys.yml'\");\n comConfig.configurations.getConfigurationSection(\"itemKeys\").getKeys(false).forEach((key) -> {\n dataManager.addRawItemKey(key, comConfig.configurations.getStringList(\"itemKeys.\" + key + \".cmds\"));\n });\n\n comConfig.configurations.set(\"itemKeys\", null);\n saveKeys();\n }\n\n /*---------------------------------------------------------*/\n\n comConfig.saveConfig();\n }\n\n public FileConfiguration getRoot() {\n return this.comConfig.configurations;\n }\n\n public FileConfiguration getApiRoot() {\n return this.apisConfig.configurations;\n }\n\n public CommentedConfig getCommConfig() {\n return this.comConfig;\n }\n\n public String getVipTitle(String vipGroup) {\n return ChatColor.translateAlternateColorCodes('&', comConfig.configurations.getString(\"groups.\" + vipGroup + \".title\", vipGroup));\n }\n\n public String getVipByTitle(String vipTitle) {\n vipTitle = vipTitle.replace(\"_\", \" \");\n for (String group : comConfig.configurations.getConfigurationSection(\"groups\").getKeys(false)) {\n if (!vipTitle.isEmpty() && comConfig.configurations.getString(\"groups.\" + group + \".title\") != null &&\n plugin.getUtil().removeColor(comConfig.configurations.getString(\"groups.\" + group + \".title\")).equalsIgnoreCase(vipTitle))\n return group;\n }\n return vipTitle;\n }\n\n public void changeUUIDs(String oldUUID, String newUUID) {\n dataManager.changeUUID(oldUUID, newUUID);\n }\n\n public void reloadVips() {\n if (dataManager != null) {\n dataManager.closeCon();\n }\n if (comConfig.configurations.getString(\"configs.database.type\").equalsIgnoreCase(\"mysql\")) {\n dataManager = new PVDataMysql(plugin);\n } else {\n dataManager = new PVDataFile(plugin);\n }\n }\n\n public boolean transExist(String payment, String trans) {\n return dataManager.transactionExist(payment, trans);\n }\n\n public void addTrans(String payment, String trans, String player) {\n if (apisConfig.configurations.getBoolean(\"apis.in-test\"))\n return;\n dataManager.addTras(payment, trans, player);\n }\n\n public HashMap<String, Map<String, String>> getAllTrans() {\n return dataManager.getAllTrans();\n }\n\n public boolean worldAllowed(World w) {\n return comConfig.configurations.getStringList(\"configs.worldCmdsAllowed\").contains(w.getName());\n }\n\n public List<String> getItemKeyCmds(String key) {\n return dataManager.getItemKeyCmds(key);\n }\n\n public void saveKeys() {\n dataManager.saveKeys();\n }\n\n public void saveVips() {\n dataManager.saveVips();\n }\n\n public void closeCon() {\n if (dataManager != null) {\n dataManager.closeCon();\n }\n }\n\n public boolean isVipActive(String vip, String id) {\n return dataManager.isVipActive(id, vip);\n }\n\n public boolean bungeeSyncEnabled() {\n return getBoolean(false, \"bungee.enableSync\");\n }\n\n public boolean queueCmds() {\n return getBoolean(false, \"configs.queueCmdsForOfflinePlayers\");\n }\n\n /*\n * For BungeeCord\n */\n public void setVipActive(String uuid, String vip, boolean active) {\n dataManager.setVipActive(uuid, vip, active);\n }\n\n public List<String> getQueueCmds(String uuid) {\n List<String> cmds = new ArrayList<>();\n if (comConfig.configurations.contains(\"joinCmds.\" + uuid + \".cmds\")) {\n cmds.addAll(comConfig.configurations.getStringList(\"joinCmds.\" + uuid + \".cmds\"));\n }\n if (comConfig.configurations.contains(\"joinCmds.\" + uuid + \".chanceCmds\")) {\n cmds.addAll(comConfig.configurations.getStringList(\"joinCmds.\" + uuid + \".chanceCmds\"));\n }\n comConfig.setDefault(\"joinCmds.\" + uuid, null);\n comConfig.saveConfig();\n return cmds;\n }\n\n private void setJoinCmds(String uuid, List<String> cmds, List<String> chanceCmds) {\n comConfig.setDefault(\"joinCmds.\" + uuid + \".cmds\", cmds);\n comConfig.setDefault(\"joinCmds.\" + uuid + \".chanceCmds\", chanceCmds);\n comConfig.saveConfig();\n }\n\n public void addKey(String key, String group, long millis, int uses) {\n dataManager.addRawKey(key, group, millis, uses, false);\n saveConfigAll();\n }\n\n public void addUniqueKey(String key, String group, long millis) {\n dataManager.addRawKey(key, group, millis, 1, true);\n saveConfigAll();\n }\n\n public void addItemKey(String key, List<String> cmds) {\n cmds.addAll(dataManager.getItemKeyCmds(key));\n dataManager.addRawItemKey(key, cmds);\n saveConfigAll();\n }\n\n private void saveConfigAll() {\n saveVips();\n saveKeys();\n comConfig.saveConfig();\n plugin.getPVBungee().sendBungeeSync();\n }\n\n public boolean delItemKey(String key) {\n if (dataManager.getItemListKeys().contains(key)) {\n dataManager.removeItemKey(key);\n saveConfigAll();\n return true;\n } else {\n return false;\n }\n }\n\n public boolean delKey(String key, int uses) {\n if (dataManager.getListKeys().contains(key)) {\n if (uses <= 1) {\n dataManager.removeKey(key);\n removeUniqueKey(key);\n } else {\n dataManager.setKeyUse(key, uses - 1);\n }\n saveConfigAll();\n return true;\n } else {\n return false;\n }\n }\n\n public boolean activateVip(OfflinePlayer p, String key, String group, long days, String pname) {\n\n boolean hasItemkey = dataManager.getItemListKeys().contains(key);\n if (hasItemkey) {\n StringBuilder cmdsBuilder = new StringBuilder();\n List<String> cmds = dataManager.getItemKeyCmds(key);\n for (String cmd : cmds) {\n cmdsBuilder.append(cmd).append(\", \");\n plugin.serv.getScheduler().runTaskLater(plugin, () -> {\n String cmdf = cmd\n .replace(\"{p}\", p.getName())\n .replace(\"{player}\", p.getName());\n if (p.isOnline()) {\n plugin.getUtil().ExecuteCmd(cmdf, null);\n }\n }, delay * 2);\n delay++;\n }\n dataManager.removeItemKey(key);\n saveConfigAll();\n\n p.getPlayer().sendMessage(plugin.getUtil().toColor(getLang(\"_pluginTag\", \"itemsGiven\").replace(\"{items}\", cmds.size() + \"\")));\n\n String cmdBuilded = cmdsBuilder.toString();\n plugin.addLog(\"ItemKey | \" + p.getName() + \" | \" + key + \" | Cmds: \" + cmdBuilded.substring(0, cmdBuilded.length() - 2));\n }\n\n String[] keyInfo = dataManager.getKeyInfo(key);\n if (keyInfo.length == 4) {\n int uses = Integer.parseInt(keyInfo[2]);\n\n if (keyInfo[3].equalsIgnoreCase(\"true\")) {\n if (hasUniquePlayer(p.getName(), key)) {\n p.getPlayer().sendMessage(plugin.getUtil().toColor(getLang(\"_pluginTag\", \"alreadyUsedUniqueKey\")));\n return false;\n }\n addUniquePlayerKey(p.getName(), key);\n } else {\n delKey(key, uses);\n }\n\n p.getPlayer().sendMessage(plugin.getUtil().toColor(\"&b---------------------------------------------\"));\n if (uses - 1 > 0) {\n p.getPlayer().sendMessage(plugin.getUtil().toColor(getLang(\"_pluginTag\", \"usesLeftActivation\").replace(\"{uses}\", \"\" + (uses - 1))));\n }\n enableVip(p, keyInfo[0], new Long(keyInfo[1]), pname, key);\n return true;\n } else if (!group.equals(\"\")) {\n enableVip(p, group, plugin.getUtil().dayToMillis(days), pname, key);\n return true;\n } else {\n if (!hasItemkey) {\n p.getPlayer().sendMessage(plugin.getUtil().toColor(getLang(\"_pluginTag\", \"invalidKey\")));\n return false;\n }\n return true;\n }\n }\n\n /*\n * For bungeecord\n */\n public void addVip(String group, String uuid, String pgroup, long duration, String nick, String expires) {\n dataManager.addRawVip(group, uuid, new ArrayList<>(Arrays.asList(pgroup.split(\",\"))), duration, nick, expires);\n }\n\n /**\n * Return the key info: <p>\n * [0] = Vip Group | [1] = Duration in millis | [2] = Uses\n *\n * @param key - The key to get info\n * @return {@code String[]} - Arrays with the key info.\n */\n public String[] getKeyInfo(String key) {\n return dataManager.getKeyInfo(key);\n }\n\n private void enableVip(OfflinePlayer p, String group, long durMillis, String pname, String key) {\n long durf = durMillis;\n Optional<String[]> otherVipOpt = getVipInfo(p.getUniqueId().toString()).stream().filter(v -> v[1].equals(group)).findFirst();\n if (otherVipOpt.isPresent()) {\n String[] otherVip = otherVipOpt.get();\n durMillis += new Long(otherVip[0]);\n if (otherVip[3].equals(\"false\")) {\n durMillis += plugin.getUtil().getNowMillis();\n }\n } else {\n durMillis += plugin.getUtil().getNowMillis();\n }\n\n List<String> pGroups = plugin.getPerms().getGroupsList(p);\n List<String> pdGroup = pGroups;\n List<String[]> vips = getVipInfo(p.getUniqueId().toString());\n if (!vips.isEmpty()) {\n pGroups = new ArrayList<>(Arrays.asList(vips.get(0)[2].split(\",\")));\n }\n\n List<String> normCmds = new ArrayList<>();\n List<String> chanceCmds = new ArrayList<>();\n\n //run command from vip\n comConfig.configurations.getStringList(\"groups.\" + group + \".commands\").forEach((cmd) -> {\n plugin.serv.getScheduler().runTaskLater(plugin, () -> {\n String cmdf = cmd\n .replace(\"{p}\", p.getName())\n .replace(\"{player}\", p.getName())\n .replace(\"{vip}\", group)\n .replace(\"{playergroup}\", pdGroup.isEmpty() ? \"\" : pdGroup.get(0))\n .replace(\"{days}\", String.valueOf(plugin.getUtil().millisToDay(durf)));\n if (p.isOnline()) {\n plugin.getUtil().ExecuteCmd(cmdf, null);\n } else {\n normCmds.add(cmdf);\n }\n }, delay);\n delay++;\n });\n\n //run command chances from vip\n getCmdChances(group).forEach((chanceString) -> {\n\n int chance = Integer.parseInt(chanceString);\n double rand = Math.random() * 100;\n\n //test chance\n if (rand <= chance) {\n comConfig.configurations.getStringList(\"groups.\" + group + \".cmdChances.\" + chanceString).forEach((cmd) -> {\n plugin.serv.getScheduler().runTaskLater(plugin, () -> {\n String cmdf = cmd\n .replace(\"{p}\", p.getName())\n .replace(\"{player}\", p.getName())\n .replace(\"{vip}\", group)\n .replace(\"{playergroup}\", pdGroup.isEmpty() ? \"\" : pdGroup.get(0))\n .replace(\"{days}\", String.valueOf(plugin.getUtil().millisToDay(durf)));\n if (p.isOnline()) {\n plugin.getUtil().ExecuteCmd(cmdf, null);\n } else {\n chanceCmds.add(cmdf);\n }\n }, delay);\n delay++;\n });\n }\n });\n\n if (queueCmds() && (normCmds.size() > 0 || chanceCmds.size() > 0)) {\n plugin.serv.getScheduler().runTaskLater(plugin, () -> {\n plugin.getLogger().info(\"Queued cmds for player \" + p.getName() + \" to run on join.\");\n setJoinCmds(p.getUniqueId().toString(), normCmds, chanceCmds);\n }, delay);\n }\n\n delay = 0;\n\n dataManager.addRawVip(group, p.getUniqueId().toString(),\n pGroups,\n durMillis,\n pname,\n plugin.getUtil().expiresOn(durMillis));\n\n setActive(p.getUniqueId().toString(), group, pdGroup);\n\n if (p.isOnline()) {\n p.getPlayer().sendMessage(plugin.getUtil().toColor(getLang(\"_pluginTag\", \"vipActivated\")));\n p.getPlayer().sendMessage(plugin.getUtil().toColor(getLang(\"activeVip\").replace(\"{vip}\", getVipTitle(group))));\n p.getPlayer().sendMessage(plugin.getUtil().toColor(getLang(\"activeDays\").replace(\"{days}\", String.valueOf(plugin.getUtil().millisToDay(durf)))));\n p.getPlayer().sendMessage(plugin.getUtil().toColor(\"&b---------------------------------------------\"));\n }\n plugin.addLog(\"EnableVip | key: \" + key + \" | \" + p.getName() + \" | \" + group + \" | Expires on: \" + plugin.getUtil().expiresOn(durMillis));\n }\n\n public void setVip(String uuid, String group, long durMillis, String pname) {\n Optional<String[]> otherVipOpt = getVipInfo(uuid).stream().filter(v -> v[1].equals(group)).findFirst();\n if (otherVipOpt.isPresent()) {\n String[] otherVip = otherVipOpt.get();\n durMillis += new Long(otherVip[0]);\n if (otherVip[3].equals(\"false\")) {\n durMillis += plugin.getUtil().getNowMillis();\n }\n } else {\n durMillis += plugin.getUtil().getNowMillis();\n }\n\n List<String> pGroups = new ArrayList<>();\n OfflinePlayer p = Bukkit.getOfflinePlayer(UUID.fromString(uuid));\n if (p.getName() != null) {\n pGroups = plugin.getPerms().getGroupsList(p);\n }\n List<String[]> vips = getVipInfo(uuid);\n if (!vips.isEmpty()) {\n pGroups = new ArrayList<>(Collections.singletonList(vips.get(0)[2]));\n }\n\n dataManager.addRawVip(group, uuid,\n pGroups,\n durMillis,\n pname,\n plugin.getUtil().expiresOn(durMillis));\n setActive(uuid, group, pGroups);\n\n plugin.addLog(\"SetVip | \" + p.getName() + \" | \" + group + \" | Expires on: \" + plugin.getUtil().expiresOn(durMillis));\n }\n\n public void setActive(String uuid, String group, List<String> pgroup) {\n String newVip = group;\n String oldVip = pgroup.stream().anyMatch(str -> getGroupList(true).contains(str)) ? pgroup.stream().filter(str -> getGroupList(true).contains(str)).findFirst().get() : \"\";\n for (String glist : getGroupList(true)) {\n if (dataManager.containsVip(uuid, glist)) {\n if (glist.equals(group)) {\n if (!dataManager.isVipActive(uuid, glist)) {\n newVip = glist;\n long total = dataManager.getVipDuration(uuid, glist) + plugin.getUtil().getNowMillis();\n dataManager.setVipDuration(uuid, glist, total);\n }\n dataManager.setVipActive(uuid, glist, true);\n } else {\n if (dataManager.isVipActive(uuid, glist)) {\n oldVip = glist;\n long total = dataManager.getVipDuration(uuid, glist) - plugin.getUtil().getNowMillis();\n dataManager.setVipDuration(uuid, glist, total);\n }\n dataManager.setVipActive(uuid, glist, false);\n }\n }\n }\n //change kits\n changeVipKit(uuid, oldVip, newVip);\n\n OfflinePlayer p = Bukkit.getOfflinePlayer(UUID.fromString(uuid));\n if (p.getName() != null) {\n runChangeVipCmds(p, newVip, oldVip);\n }\n saveConfigAll();\n }\n\n public void runChangeVipCmds(OfflinePlayer p, String newVip, String oldVip) {\n for (String cmd : comConfig.configurations.getStringList(\"configs.commandsToRunOnChangeVip\")) {\n if (p.getName() == null) {\n break;\n }\n\n String cmdf = cmd.replace(\"{p}\", p.getName())\n .replace(\"{player}\", p.getName());\n if (oldVip != null && !oldVip.equals(\"\") && cmdf.contains(\"{oldvip}\")) {\n plugin.serv.getScheduler().runTaskLater(plugin, () -> plugin.getUtil().ExecuteCmd(cmdf.replace(\"{oldvip}\", oldVip), null), delay);\n delay++;\n } else if (!newVip.equals(\"\") && cmdf.contains(\"{newvip}\")) {\n plugin.serv.getScheduler().runTaskLater(plugin, () -> plugin.getUtil().ExecuteCmd(cmdf.replace(\"{newvip}\", newVip), null), delay);\n delay++;\n } else {\n plugin.serv.getScheduler().runTaskLater(plugin, () -> plugin.getUtil().ExecuteCmd(cmdf, null), delay);\n delay++;\n }\n }\n if (comConfig.configurations.getBoolean(\"configs.Vault.use\")) {\n plugin.serv.getScheduler().runTaskLater(plugin, () -> {\n if (oldVip != null && !oldVip.isEmpty() && !oldVip.equals(newVip)) {\n plugin.getPerms().removeGroup(p.getUniqueId().toString(), oldVip);\n }\n if (comConfig.configurations.getString(\"configs.Vault.mode\").equalsIgnoreCase(\"set\")) {\n plugin.getPerms().setGroup(p.getUniqueId().toString(), newVip);\n }\n if (comConfig.configurations.getString(\"configs.Vault.mode\").equalsIgnoreCase(\"add\")) {\n plugin.getPerms().addGroup(p.getUniqueId().toString(), newVip);\n }\n }, delay);\n delay++;\n } else {\n reloadPerms();\n }\n }\n\n private void changeVipKit(String uuid, String oldVip, String newVip) {\n if (plugin.ess != null) {\n long now = System.currentTimeMillis();\n String oldKit = this.getString(\"\", \"groups.\" + oldVip + \".essentials-kit\");\n try {\n User user = plugin.ess.getUser(UUID.fromString(uuid));\n if (!oldKit.isEmpty() && user != null) {\n long oldTime = user.getKitTimestamp(oldKit.toLowerCase(Locale.ENGLISH));\n dataManager.setVipKitCooldown(uuid, oldVip, now - oldTime);\n }\n\n String newKit = this.getString(\"\", \"groups.\" + newVip + \".essentials-kit\");\n if (!newKit.isEmpty() && user != null) {\n long newTime = dataManager.getVipCooldown(uuid, newVip);\n if (newTime > 0) {\n user.setKitTimestamp(newKit.toLowerCase(Locale.ENGLISH), now - newTime);\n }\n }\n } catch (Exception ignored) {\n plugin.getPVLogger().warning(\"An old version of Essentials plugin was detected! Ignoring kit timer handler.\");\n }\n }\n }\n\n void removeVip(String uuid, String pname, String group) {\n plugin.addLog(\"RemoveVip | \" + pname + \" | \" + group);\n\n dataManager.removeVip(uuid, group);\n plugin.serv.getScheduler().runTaskLater(plugin, () -> plugin.getUtil().ExecuteCmd(getString(\"\", \"configs.cmdOnRemoveVip\")\n .replace(\"{p}\", Optional.ofNullable(pname).get())\n .replace(\"{player}\", Optional.ofNullable(pname).get())\n .replace(\"{vip}\", group), null), delay);\n delay++;\n\n if (comConfig.configurations.getBoolean(\"configs.Vault.use\")) {\n plugin.serv.getScheduler().runTaskLater(plugin, () -> plugin.getPerms().removeGroup(uuid, group), delay);\n delay++;\n }\n }\n\n public void removeVip(String uuid, Optional<String> optg) {\n List<String[]> vipInfo = getVipInfo(uuid);\n boolean id = false;\n String nick = \"\";\n List<String> oldGroup = new ArrayList<>();\n String vipGroup = \"\";\n if (vipInfo.size() > 0) {\n for (String[] key : vipInfo) {\n vipGroup = key[1];\n try {\n oldGroup = Arrays.asList(key[2].split(\",\"));\n nick = key[4];\n } catch (Exception ex) {\n plugin.getPVLogger().warning(\"Error on removeVip: \" + ex.getMessage());\n ex.printStackTrace();\n }\n if (vipInfo.size() > 1) {\n if (optg.isPresent()) {\n if (optg.get().equals(vipGroup)) {\n removeVip(uuid, nick, vipGroup);\n } else if (!id) {\n setActive(uuid, vipGroup, new ArrayList<>());\n id = true;\n }\n } else {\n removeVip(uuid, nick, vipGroup);\n }\n } else {\n removeVip(uuid, nick, vipGroup);\n }\n }\n }\n\n //commands to run on vip finish\n if (getVipInfo(uuid).size() == 0) {\n for (String cmd : comConfig.configurations.getStringList(\"configs.commandsToRunOnVipFinish\")) {\n if (cmd == null || cmd.isEmpty() || cmd.contains(\"{vip}\")) {\n continue;\n }\n final String replace = cmd.replace(\"{p}\", nick)\n .replace(\"{player}\", nick);\n if (!oldGroup.isEmpty() && cmd.contains(\"{playergroup}\")) {\n for (String group : oldGroup) {\n String cmdf = replace\n .replace(\"{playergroup}\", group);\n plugin.serv.getScheduler().runTaskLater(plugin, () -> plugin.getUtil().ExecuteCmd(cmdf, null), delay);\n delay++;\n }\n } else {\n plugin.serv.getScheduler().runTaskLater(plugin, () -> plugin.getUtil().ExecuteCmd(replace, null), delay);\n delay++;\n }\n }\n }\n\n //command to run from vip GROUP on finish\n for (String cmd : getCmdsToRunOnFinish(vipGroup)) {\n if (cmd == null || cmd.isEmpty()) continue;\n final String replace = cmd.replace(\"{p}\", nick)\n .replace(\"{player}\", nick);\n if (!oldGroup.isEmpty() && cmd.contains(\"{playergroup}\")) {\n for (String group : oldGroup) {\n String cmdf = replace.replace(\"{playergroup}\", group);\n plugin.serv.getScheduler().runTaskLater(plugin, () -> plugin.getUtil().ExecuteCmd(cmdf, null), delay);\n delay++;\n }\n } else {\n plugin.serv.getScheduler().runTaskLater(plugin, () -> plugin.getUtil().ExecuteCmd(replace, null), delay);\n delay++;\n }\n }\n\n //use vault to add back oldgroup\n if (comConfig.configurations.getBoolean(\"configs.Vault.use\")) {\n for (String group : oldGroup) {\n plugin.serv.getScheduler().runTaskLater(plugin, () -> plugin.getPerms().addGroup(uuid, group), delay);\n delay++;\n }\n } else {\n reloadPerms();\n }\n saveConfigAll();\n }\n\n public void reloadPerms() {\n plugin.serv.getScheduler().runTaskLater(plugin, () -> plugin.getUtil().ExecuteCmd(getString(\"\", \"configs.cmdToReloadPermPlugin\"), null), delay);\n delay = 0;\n }\n\n public long getLong(int def, String node) {\n return comConfig.configurations.getLong(node, def);\n }\n\n public int getInt(int def, String node) {\n return comConfig.configurations.getInt(node, def);\n }\n\n public String getString(String def, String node) {\n return comConfig.configurations.getString(node, def);\n }\n\n public boolean getBoolean(boolean def, String node) {\n return comConfig.configurations.getBoolean(node, def);\n }\n\n public String getLang(String... nodes) {\n StringBuilder msg = new StringBuilder();\n for (String node : nodes) {\n msg.append(getString(\"No strings with \" + node, \"strings.\" + node));\n }\n return msg.toString();\n }\n\n public boolean groupExists(String group) {\n return comConfig.configurations.contains(\"groups.\" + group);\n }\n\n public Set<String> getCmdChances(String vip) {\n if (comConfig.configurations.getConfigurationSection(\"groups.\" + vip + \".cmdChances\") != null) {\n return comConfig.configurations.getConfigurationSection(\"groups.\" + vip + \".cmdChances\").getKeys(false);\n }\n return new HashSet<>();\n }\n\n public Set<String> getCmdsToRunOnFinish(String vip) {\n if (comConfig.configurations.getConfigurationSection(\"groups.\" + vip + \".run-on-vip-end\") != null) {\n return comConfig.configurations.getConfigurationSection(\"groups.\" + vip + \".run-on-vip-end\").getKeys(false);\n }\n return new HashSet<>();\n }\n\n public Set<String> getListKeys() {\n return dataManager.getListKeys();\n }\n\n public Set<String> getItemListKeys() {\n return dataManager.getItemListKeys();\n }\n\n public Set<String> getGroupList(boolean raw) {\n Set<String> list = new HashSet<>();\n if (raw) {\n if (comConfig.configurations.getConfigurationSection(\"groups\") != null) {\n return comConfig.configurations.getConfigurationSection(\"groups\").getKeys(false);\n }\n } else {\n if (comConfig.configurations.getConfigurationSection(\"groups\") != null) {\n for (String group : comConfig.configurations.getConfigurationSection(\"groups\").getKeys(false)) {\n if (comConfig.configurations.getString(\"groups.\" + group + \".title\") != null &&\n !comConfig.configurations.getString(\"groups.\" + group + \".title\").isEmpty())\n list.add(comConfig.configurations.getString(\"groups.\" + group + \".title\"));\n else\n list.add(group);\n }\n }\n }\n return list;\n }\n\n public HashMap<String, List<String[]>> getVipList() {\n return dataManager.getActiveVipList();\n }\n\n /**\n * Return player's vip info.<p>\n * [0] = Duration, [1] = Vip Group, [2] = Player Group, [3] = Is Active, [4] = Player Nick\n *\n * @param puuid Player UUID as string.\n * @return {@code List<String[5]>} or a empty list if theres no vip for player.\n */\n public List<String[]> getVipInfo(String puuid) {\n return dataManager.getVipInfo(puuid);\n }\n\n\n /**\n * Return player's vip info.<p>\n * [0] = Duration, [1] = Vip Group, [2] = Player Group, [3] = Is Active, [4] = Player Nick\n *\n * @param playName Player UUID as string or nickname.\n * @return {@code String[5]}\n */\n public String[] getActiveVipInfo(String playName) {\n String uuid;\n try {\n UUID.fromString(playName);\n uuid = playName;\n } catch (IllegalArgumentException ex) {\n uuid = getVipUUID(playName);\n }\n for (String[] vips : getVipInfo(uuid)) {\n if (vips[3].equals(\"true\")) {\n return vips;\n }\n }\n return new String[5];\n }\n\n /**\n * Return all vip info.<p>\n *\n * @return {@code HashMap<String,List<String[]>>}<p>\n * Key: Existing Group Name.<p>\n * Value: [0] = Duration, [1] = Vip Group, [2] = Player Group, [3] = Is Active, [4] = Player Nick\n */\n public HashMap<String, List<String[]>> getAllVips() {\n return dataManager.getAllVipList();\n }\n\n public String getVipUUID(String string) {\n return dataManager.getVipUUID(string);\n }\n\n public boolean hasUniquePlayer(String player, String key) {\n return uniqueKeys.configurations.contains(\"keys.\" + key + \".\" + player);\n }\n\n public void addUniquePlayerKey(String player, String key) {\n SimpleDateFormat sdf = new SimpleDateFormat(\"dd/MM/yyyy HH:mm:ss\");\n uniqueKeys.configurations.set(\"keys.\" + key + \".\" + player, sdf.format(Calendar.getInstance().getTime()));\n uniqueKeys.saveConfig();\n }\n\n public void removeUniqueKey(String key) {\n uniqueKeys.configurations.set(\"keys.\" + key, null);\n uniqueKeys.saveConfig();\n }\n}", "@SuppressWarnings({\"WeakerAccess\", \"unused\"})\npublic class Metrics {\n\n static {\n // You can use the property to disable the check in your test environment\n if (System.getProperty(\"bstats.relocatecheck\") == null || !System.getProperty(\"bstats.relocatecheck\").equals(\"false\")) {\n // Maven's Relocate is clever and changes strings, too. So we have to use this little \"trick\" ... :D\n final String defaultPackage = new String(\n new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'});\n final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'});\n // We want to make sure nobody just copy & pastes the example and use the wrong package names\n if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class.getPackage().getName().equals(examplePackage)) {\n throw new IllegalStateException(\"bStats Metrics class has not been relocated correctly!\");\n }\n }\n }\n\n // The version of this bStats class\n public static final int B_STATS_VERSION = 1;\n\n // The url to which the data is sent\n private static final String URL = \"https://bStats.org/submitData/bukkit\";\n\n // Is bStats enabled on this server?\n private boolean enabled;\n\n // Should failed requests be logged?\n private static boolean logFailedRequests;\n\n // Should the sent data be logged?\n private static boolean logSentData;\n\n // Should the response text be logged?\n private static boolean logResponseStatusText;\n\n // The uuid of the server\n private static String serverUUID;\n\n // The plugin\n private final Plugin plugin;\n\n // A list with all custom charts\n private final List<CustomChart> charts = new ArrayList<>();\n\n /**\n * Class constructor.\n *\n * @param plugin The plugin which stats should be submitted.\n */\n public Metrics(Plugin plugin) {\n if (plugin == null) {\n throw new IllegalArgumentException(\"Plugin cannot be null!\");\n }\n this.plugin = plugin;\n\n // Get the config file\n File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), \"bStats\");\n File configFile = new File(bStatsFolder, \"config.yml\");\n YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile);\n\n // Check if the config file exists\n if (!config.isSet(\"serverUuid\")) {\n\n // Add default values\n config.addDefault(\"enabled\", true);\n // Every server gets it's unique random id.\n config.addDefault(\"serverUuid\", UUID.randomUUID().toString());\n // Should failed request be logged?\n config.addDefault(\"logFailedRequests\", false);\n // Should the sent data be logged?\n config.addDefault(\"logSentData\", false);\n // Should the response text be logged?\n config.addDefault(\"logResponseStatusText\", false);\n\n // Inform the server owners about bStats\n config.options().header(\n \"bStats collects some data for plugin authors like how many servers are using their plugins.\\n\" +\n \"To honor their work, you should not disable it.\\n\" +\n \"This has nearly no effect on the server performance!\\n\" +\n \"Check out https://bStats.org/ to learn more :)\"\n ).copyDefaults(true);\n try {\n config.save(configFile);\n } catch (IOException ignored) { }\n }\n\n // Load the data\n enabled = config.getBoolean(\"enabled\", true);\n serverUUID = config.getString(\"serverUuid\");\n logFailedRequests = config.getBoolean(\"logFailedRequests\", false);\n logSentData = config.getBoolean(\"logSentData\", false);\n logResponseStatusText = config.getBoolean(\"logResponseStatusText\", false);\n\n if (enabled) {\n boolean found = false;\n // Search for all other bStats Metrics classes to see if we are the first one\n for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {\n try {\n service.getField(\"B_STATS_VERSION\"); // Our identifier :)\n found = true; // We aren't the first\n break;\n } catch (NoSuchFieldException ignored) { }\n }\n // Register our service\n Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal);\n if (!found) {\n // We are the first!\n startSubmitting();\n }\n }\n }\n\n /**\n * Checks if bStats is enabled.\n *\n * @return Whether bStats is enabled or not.\n */\n public boolean isEnabled() {\n return enabled;\n }\n\n /**\n * Adds a custom chart.\n *\n * @param chart The chart to add.\n */\n public void addCustomChart(CustomChart chart) {\n if (chart == null) {\n throw new IllegalArgumentException(\"Chart cannot be null!\");\n }\n charts.add(chart);\n }\n\n /**\n * Starts the Scheduler which submits our data every 30 minutes.\n */\n private void startSubmitting() {\n final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags\n timer.scheduleAtFixedRate(new TimerTask() {\n @Override\n public void run() {\n if (!plugin.isEnabled()) { // Plugin was disabled\n timer.cancel();\n return;\n }\n // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler\n // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)\n Bukkit.getScheduler().runTask(plugin, () -> submitData());\n }\n }, 1000 * 60 * 5, 1000 * 60 * 30);\n // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start\n // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted!\n // WARNING: Just don't do it!\n }\n\n /**\n * Gets the plugin specific data.\n * This method is called using Reflection.\n *\n * @return The plugin specific data.\n */\n public JsonObject getPluginData() {\n JsonObject data = new JsonObject();\n\n String pluginName = plugin.getDescription().getName();\n String pluginVersion = plugin.getDescription().getVersion();\n\n data.addProperty(\"pluginName\", pluginName); // Append the name of the plugin\n data.addProperty(\"pluginVersion\", pluginVersion); // Append the version of the plugin\n JsonArray customCharts = new JsonArray();\n for (CustomChart customChart : charts) {\n // Add the data of the custom charts\n JsonObject chart = customChart.getRequestJsonObject();\n if (chart == null) { // If the chart is null, we skip it\n continue;\n }\n customCharts.add(chart);\n }\n data.add(\"customCharts\", customCharts);\n\n return data;\n }\n\n /**\n * Gets the server specific data.\n *\n * @return The server specific data.\n */\n private JsonObject getServerData() {\n // Minecraft specific data\n int playerAmount;\n try {\n // Around MC 1.8 the return type was changed to a collection from an array,\n // This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection;\n Method onlinePlayersMethod = Class.forName(\"org.bukkit.Server\").getMethod(\"getOnlinePlayers\");\n playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class)\n ? ((Collection<?>) onlinePlayersMethod.invoke(Bukkit.getServer())).size()\n : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length;\n } catch (Exception e) {\n playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed\n }\n int onlineMode = Bukkit.getOnlineMode() ? 1 : 0;\n String bukkitVersion = Bukkit.getVersion();\n String bukkitName = Bukkit.getName();\n\n // OS/Java specific data\n String javaVersion = System.getProperty(\"java.version\");\n String osName = System.getProperty(\"os.name\");\n String osArch = System.getProperty(\"os.arch\");\n String osVersion = System.getProperty(\"os.version\");\n int coreCount = Runtime.getRuntime().availableProcessors();\n\n JsonObject data = new JsonObject();\n\n data.addProperty(\"serverUUID\", serverUUID);\n\n data.addProperty(\"playerAmount\", playerAmount);\n data.addProperty(\"onlineMode\", onlineMode);\n data.addProperty(\"bukkitVersion\", bukkitVersion);\n data.addProperty(\"bukkitName\", bukkitName);\n\n data.addProperty(\"javaVersion\", javaVersion);\n data.addProperty(\"osName\", osName);\n data.addProperty(\"osArch\", osArch);\n data.addProperty(\"osVersion\", osVersion);\n data.addProperty(\"coreCount\", coreCount);\n\n return data;\n }\n\n /**\n * Collects the data and sends it afterwards.\n */\n private void submitData() {\n final JsonObject data = getServerData();\n\n JsonArray pluginData = new JsonArray();\n // Search for all other bStats Metrics classes to get their plugin data\n for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {\n try {\n service.getField(\"B_STATS_VERSION\"); // Our identifier :)\n\n for (RegisteredServiceProvider<?> provider : Bukkit.getServicesManager().getRegistrations(service)) {\n try {\n Object plugin = provider.getService().getMethod(\"getPluginData\").invoke(provider.getProvider());\n if (plugin instanceof JsonObject) {\n pluginData.add((JsonObject) plugin);\n } else { // old bstats version compatibility\n try {\n Class<?> jsonObjectJsonSimple = Class.forName(\"org.json.simple.JSONObject\");\n if (plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) {\n Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod(\"toJSONString\");\n jsonStringGetter.setAccessible(true);\n String jsonString = (String) jsonStringGetter.invoke(plugin);\n JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject();\n pluginData.add(object);\n }\n } catch (ClassNotFoundException e) {\n // minecraft version 1.14+\n if (logFailedRequests) {\n this.plugin.getLogger().log(Level.SEVERE, \"Encountered unexpected exception\", e);\n }\n continue; // continue looping since we cannot do any other thing.\n }\n }\n } catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { }\n }\n } catch (NoSuchFieldException ignored) { }\n }\n\n data.add(\"plugins\", pluginData);\n\n // Create a new thread for the connection to the bStats server\n new Thread(new Runnable() {\n @Override\n public void run() {\n try {\n // Send the data\n sendData(plugin, data);\n } catch (Exception e) {\n // Something went wrong! :(\n if (logFailedRequests) {\n plugin.getLogger().log(Level.WARNING, \"Could not submit plugin stats of \" + plugin.getName(), e);\n }\n }\n }\n }).start();\n }\n\n /**\n * Sends the data to the bStats server.\n *\n * @param plugin Any plugin. It's just used to get a logger instance.\n * @param data The data to send.\n * @throws Exception If the request failed.\n */\n private static void sendData(Plugin plugin, JsonObject data) throws Exception {\n if (data == null) {\n throw new IllegalArgumentException(\"Data cannot be null!\");\n }\n if (Bukkit.isPrimaryThread()) {\n throw new IllegalAccessException(\"This method must not be called from the main thread!\");\n }\n if (logSentData) {\n plugin.getLogger().info(\"Sending data to bStats: \" + data.toString());\n }\n HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();\n\n // Compress the data to save bandwidth\n byte[] compressedData = compress(data.toString());\n\n // Add headers\n connection.setRequestMethod(\"POST\");\n connection.addRequestProperty(\"Accept\", \"application/json\");\n connection.addRequestProperty(\"Connection\", \"close\");\n connection.addRequestProperty(\"Content-Encoding\", \"gzip\"); // We gzip our request\n connection.addRequestProperty(\"Content-Length\", String.valueOf(compressedData.length));\n connection.setRequestProperty(\"Content-Type\", \"application/json\"); // We send our data in JSON format\n connection.setRequestProperty(\"User-Agent\", \"MC-Server/\" + B_STATS_VERSION);\n\n // Send data\n connection.setDoOutput(true);\n DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());\n outputStream.write(compressedData);\n outputStream.flush();\n outputStream.close();\n\n InputStream inputStream = connection.getInputStream();\n BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));\n\n StringBuilder builder = new StringBuilder();\n String line;\n while ((line = bufferedReader.readLine()) != null) {\n builder.append(line);\n }\n bufferedReader.close();\n if (logResponseStatusText) {\n plugin.getLogger().info(\"Sent data to bStats and received response: \" + builder.toString());\n }\n }\n\n /**\n * Gzips the given String.\n *\n * @param str The string to gzip.\n * @return The gzipped String.\n * @throws IOException If the compression failed.\n */\n private static byte[] compress(final String str) throws IOException {\n if (str == null) {\n return null;\n }\n ByteArrayOutputStream outputStream = new ByteArrayOutputStream();\n GZIPOutputStream gzip = new GZIPOutputStream(outputStream);\n gzip.write(str.getBytes(StandardCharsets.UTF_8));\n gzip.close();\n return outputStream.toByteArray();\n }\n\n /**\n * Represents a custom chart.\n */\n public static abstract class CustomChart {\n\n // The id of the chart\n final String chartId;\n\n /**\n * Class constructor.\n *\n * @param chartId The id of the chart.\n */\n CustomChart(String chartId) {\n if (chartId == null || chartId.isEmpty()) {\n throw new IllegalArgumentException(\"ChartId cannot be null or empty!\");\n }\n this.chartId = chartId;\n }\n\n private JsonObject getRequestJsonObject() {\n JsonObject chart = new JsonObject();\n chart.addProperty(\"chartId\", chartId);\n try {\n JsonObject data = getChartData();\n if (data == null) {\n // If the data is null we don't send the chart.\n return null;\n }\n chart.add(\"data\", data);\n } catch (Throwable t) {\n if (logFailedRequests) {\n Bukkit.getLogger().log(Level.WARNING, \"Failed to get data for custom chart with id \" + chartId, t);\n }\n return null;\n }\n return chart;\n }\n\n protected abstract JsonObject getChartData() throws Exception;\n\n }\n\n /**\n * Represents a custom simple pie.\n */\n public static class SimplePie extends CustomChart {\n\n private final Callable<String> callable;\n\n /**\n * Class constructor.\n *\n * @param chartId The id of the chart.\n * @param callable The callable which is used to request the chart data.\n */\n public SimplePie(String chartId, Callable<String> callable) {\n super(chartId);\n this.callable = callable;\n }\n\n @Override\n protected JsonObject getChartData() throws Exception {\n JsonObject data = new JsonObject();\n String value = callable.call();\n if (value == null || value.isEmpty()) {\n // Null = skip the chart\n return null;\n }\n data.addProperty(\"value\", value);\n return data;\n }\n }\n\n /**\n * Represents a custom advanced pie.\n */\n public static class AdvancedPie extends CustomChart {\n\n private final Callable<Map<String, Integer>> callable;\n\n /**\n * Class constructor.\n *\n * @param chartId The id of the chart.\n * @param callable The callable which is used to request the chart data.\n */\n public AdvancedPie(String chartId, Callable<Map<String, Integer>> callable) {\n super(chartId);\n this.callable = callable;\n }\n\n @Override\n protected JsonObject getChartData() throws Exception {\n JsonObject data = new JsonObject();\n JsonObject values = new JsonObject();\n Map<String, Integer> map = callable.call();\n if (map == null || map.isEmpty()) {\n // Null = skip the chart\n return null;\n }\n boolean allSkipped = true;\n for (Map.Entry<String, Integer> entry : map.entrySet()) {\n if (entry.getValue() == 0) {\n continue; // Skip this invalid\n }\n allSkipped = false;\n values.addProperty(entry.getKey(), entry.getValue());\n }\n if (allSkipped) {\n // Null = skip the chart\n return null;\n }\n data.add(\"values\", values);\n return data;\n }\n }\n\n /**\n * Represents a custom drilldown pie.\n */\n public static class DrilldownPie extends CustomChart {\n\n private final Callable<Map<String, Map<String, Integer>>> callable;\n\n /**\n * Class constructor.\n *\n * @param chartId The id of the chart.\n * @param callable The callable which is used to request the chart data.\n */\n public DrilldownPie(String chartId, Callable<Map<String, Map<String, Integer>>> callable) {\n super(chartId);\n this.callable = callable;\n }\n\n @Override\n public JsonObject getChartData() throws Exception {\n JsonObject data = new JsonObject();\n JsonObject values = new JsonObject();\n Map<String, Map<String, Integer>> map = callable.call();\n if (map == null || map.isEmpty()) {\n // Null = skip the chart\n return null;\n }\n boolean reallyAllSkipped = true;\n for (Map.Entry<String, Map<String, Integer>> entryValues : map.entrySet()) {\n JsonObject value = new JsonObject();\n boolean allSkipped = true;\n for (Map.Entry<String, Integer> valueEntry : map.get(entryValues.getKey()).entrySet()) {\n value.addProperty(valueEntry.getKey(), valueEntry.getValue());\n allSkipped = false;\n }\n if (!allSkipped) {\n reallyAllSkipped = false;\n values.add(entryValues.getKey(), value);\n }\n }\n if (reallyAllSkipped) {\n // Null = skip the chart\n return null;\n }\n data.add(\"values\", values);\n return data;\n }\n }\n\n /**\n * Represents a custom single line chart.\n */\n public static class SingleLineChart extends CustomChart {\n\n private final Callable<Integer> callable;\n\n /**\n * Class constructor.\n *\n * @param chartId The id of the chart.\n * @param callable The callable which is used to request the chart data.\n */\n public SingleLineChart(String chartId, Callable<Integer> callable) {\n super(chartId);\n this.callable = callable;\n }\n\n @Override\n protected JsonObject getChartData() throws Exception {\n JsonObject data = new JsonObject();\n int value = callable.call();\n if (value == 0) {\n // Null = skip the chart\n return null;\n }\n data.addProperty(\"value\", value);\n return data;\n }\n\n }\n\n /**\n * Represents a custom multi line chart.\n */\n public static class MultiLineChart extends CustomChart {\n\n private final Callable<Map<String, Integer>> callable;\n\n /**\n * Class constructor.\n *\n * @param chartId The id of the chart.\n * @param callable The callable which is used to request the chart data.\n */\n public MultiLineChart(String chartId, Callable<Map<String, Integer>> callable) {\n super(chartId);\n this.callable = callable;\n }\n\n @Override\n protected JsonObject getChartData() throws Exception {\n JsonObject data = new JsonObject();\n JsonObject values = new JsonObject();\n Map<String, Integer> map = callable.call();\n if (map == null || map.isEmpty()) {\n // Null = skip the chart\n return null;\n }\n boolean allSkipped = true;\n for (Map.Entry<String, Integer> entry : map.entrySet()) {\n if (entry.getValue() == 0) {\n continue; // Skip this invalid\n }\n allSkipped = false;\n values.addProperty(entry.getKey(), entry.getValue());\n }\n if (allSkipped) {\n // Null = skip the chart\n return null;\n }\n data.add(\"values\", values);\n return data;\n }\n\n }\n\n /**\n * Represents a custom simple bar chart.\n */\n public static class SimpleBarChart extends CustomChart {\n\n private final Callable<Map<String, Integer>> callable;\n\n /**\n * Class constructor.\n *\n * @param chartId The id of the chart.\n * @param callable The callable which is used to request the chart data.\n */\n public SimpleBarChart(String chartId, Callable<Map<String, Integer>> callable) {\n super(chartId);\n this.callable = callable;\n }\n\n @Override\n protected JsonObject getChartData() throws Exception {\n JsonObject data = new JsonObject();\n JsonObject values = new JsonObject();\n Map<String, Integer> map = callable.call();\n if (map == null || map.isEmpty()) {\n // Null = skip the chart\n return null;\n }\n for (Map.Entry<String, Integer> entry : map.entrySet()) {\n JsonArray categoryValues = new JsonArray();\n categoryValues.add(entry.getValue());\n values.add(entry.getKey(), categoryValues);\n }\n data.add(\"values\", values);\n return data;\n }\n\n }\n\n /**\n * Represents a custom advanced bar chart.\n */\n public static class AdvancedBarChart extends CustomChart {\n\n private final Callable<Map<String, int[]>> callable;\n\n /**\n * Class constructor.\n *\n * @param chartId The id of the chart.\n * @param callable The callable which is used to request the chart data.\n */\n public AdvancedBarChart(String chartId, Callable<Map<String, int[]>> callable) {\n super(chartId);\n this.callable = callable;\n }\n\n @Override\n protected JsonObject getChartData() throws Exception {\n JsonObject data = new JsonObject();\n JsonObject values = new JsonObject();\n Map<String, int[]> map = callable.call();\n if (map == null || map.isEmpty()) {\n // Null = skip the chart\n return null;\n }\n boolean allSkipped = true;\n for (Map.Entry<String, int[]> entry : map.entrySet()) {\n if (entry.getValue().length == 0) {\n continue; // Skip this invalid\n }\n allSkipped = false;\n JsonArray categoryValues = new JsonArray();\n for (int categoryValue : entry.getValue()) {\n categoryValues.add(categoryValue);\n }\n values.add(entry.getKey(), categoryValues);\n }\n if (allSkipped) {\n // Null = skip the chart\n return null;\n }\n data.add(\"values\", values);\n return data;\n }\n }\n}" ]
import br.net.fabiozumbi12.pixelvip.bukkit.Packages.PackageManager; import br.net.fabiozumbi12.pixelvip.bukkit.PaymentsAPI.MercadoPagoHook; import br.net.fabiozumbi12.pixelvip.bukkit.PaymentsAPI.PagSeguroHook; import br.net.fabiozumbi12.pixelvip.bukkit.PaymentsAPI.PayPalHook; import br.net.fabiozumbi12.pixelvip.bukkit.PaymentsAPI.PaymentModel; import br.net.fabiozumbi12.pixelvip.bukkit.bungee.PixelVipBungee; import br.net.fabiozumbi12.pixelvip.bukkit.cmds.PVCommands; import br.net.fabiozumbi12.pixelvip.bukkit.config.PVConfig; import br.net.fabiozumbi12.pixelvip.bukkit.metrics.Metrics; import com.earth2me.essentials.Essentials; import net.milkbowl.vault.permission.Permission; import org.bukkit.Bukkit; import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.*;
package br.net.fabiozumbi12.pixelvip.bukkit; public class PixelVip extends JavaPlugin implements Listener { public PixelVip plugin; public Server serv; public PluginDescriptionFile pdf; public Essentials ess; public HashMap<String, String> processTrans; private PVLogger logger; private int task = 0; private List<PaymentModel> payments; private PVUtil util; private Permission perms; private PVConfig config; private PermsAPI permApi; private PixelVipBungee pvBungee;
private PackageManager packageManager;
0
sviperll/static-mustache
static-mustache/src/main/java/com/github/sviperll/staticmustache/token/MustacheTokenizer.java
[ "public abstract class MustacheToken {\n public static MustacheToken beginSection(final String name) {\n return new MustacheToken() {\n @Override\n public <R, E extends Exception> R accept(Visitor<R, E> visitor) throws E {\n return visitor.beginSection(name);\n }\n };\n }\n public static MustacheToken beginInvertedSection(final String name) {\n return new MustacheToken() {\n @Override\n public <R, E extends Exception> R accept(Visitor<R, E> visitor) throws E {\n return visitor.beginInvertedSection(name);\n }\n };\n }\n public static MustacheToken endSection(final String name) {\n return new MustacheToken() {\n @Override\n public <R, E extends Exception> R accept(Visitor<R, E> visitor) throws E {\n return visitor.endSection(name);\n }\n };\n }\n public static MustacheToken variable(final String name) {\n return new MustacheToken() {\n @Override\n public <R, E extends Exception> R accept(Visitor<R, E> visitor) throws E {\n return visitor.variable(name);\n }\n };\n }\n public static MustacheToken unescapedVariable(final String name) {\n return new MustacheToken() {\n @Override\n public <R, E extends Exception> R accept(Visitor<R, E> visitor) throws E {\n return visitor.unescapedVariable(name);\n }\n };\n }\n public static MustacheToken specialCharacter(final char c) {\n return new MustacheToken() {\n @Override\n public <R, E extends Exception> R accept(Visitor<R, E> visitor) throws E {\n return visitor.specialCharacter(c);\n }\n };\n }\n public static MustacheToken text(final String s) {\n return new MustacheToken() {\n @Override\n public <R, E extends Exception> R accept(Visitor<R, E> visitor) throws E {\n return visitor.text(s);\n }\n };\n }\n public static MustacheToken endOfFile() {\n return new MustacheToken() {\n @Override\n public <R, E extends Exception> R accept(Visitor<R, E> visitor) throws E {\n return visitor.endOfFile();\n }\n };\n }\n\n public abstract <R, E extends Exception> R accept(Visitor<R, E> visitor) throws E;\n\n private MustacheToken() {\n }\n public interface Visitor<R, E extends Exception> {\n R beginSection(String name) throws E;\n R beginInvertedSection(String name) throws E;\n R endSection(String name) throws E;\n R variable(String name) throws E;\n R unescapedVariable(String name) throws E;\n R specialCharacter(char c) throws E;\n R text(String s) throws E;\n R endOfFile() throws E;\n }\n}", "@SuppressWarnings(\"serial\")\npublic class Position implements Serializable {\n private final String fileName;\n private final int row;\n private final String currentLine;\n private final int col;\n public Position(String fileName, int row, String currentLine, int col) {\n this.fileName = fileName;\n this.row = row;\n this.currentLine = currentLine;\n this.col = col;\n }\n\n public String fileName() {\n return fileName;\n }\n\n public String currentLine() {\n return currentLine;\n }\n\n public int row() {\n return row;\n }\n\n public int col() {\n return col;\n }\n\n}", "public class PositionedToken<T> {\n private final Position position;\n private final T innerToken;\n public PositionedToken(Position position, @Nullable T innerToken) {\n this.position = position;\n this.innerToken = innerToken;\n }\n\n public Position position() {\n return position;\n }\n\n public T innerToken() {\n return innerToken;\n }\n}", "@SuppressWarnings(\"serial\")\npublic class ProcessingException extends Exception {\n private final Position position;\n\n private ProcessingException(Position position, String message, Throwable cause) {\n super(message, cause);\n this.position = position;\n }\n\n public ProcessingException(Position position, String message) {\n this(position, message, null);\n }\n\n public ProcessingException(Position position, ContextException contextException) {\n this(position, contextException.getMessage(), contextException);\n }\n\n public Position position() {\n return position;\n }\n}", "public interface TokenProcessor<T> {\n static Character EOF = null;\n\n void processToken(@Nullable T token) throws ProcessingException;\n}", "public class BracesTokenizer implements TokenProcessor<Character> {\n static TokenProcessorDecorator<Character, BracesToken> decorator() {\n return new TokenProcessorDecorator<Character, BracesToken>() {\n @Override\n public TokenProcessor<Character> decorateTokenProcessor(TokenProcessor<BracesToken> downstream) {\n return new BracesTokenizer(downstream);\n }\n };\n }\n public static TokenProcessor<Character> createInstance(String fileName, TokenProcessor<PositionedToken<BracesToken>> downstream) {\n TokenProcessor<PositionedToken<Character>> paransisTokenizer = PositionedTransformer.decorateTokenProcessor(BracesTokenizer.decorator(), downstream);\n return new PositionAnnotator(fileName, paransisTokenizer);\n }\n\n private final TokenProcessor<BracesToken> downstream;\n private State state = State.NONE;\n\n public BracesTokenizer(TokenProcessor<BracesToken> downstream) {\n this.downstream = downstream;\n }\n\n @Override\n public void processToken(Character token) throws ProcessingException {\n if (token == null) {\n if (state == State.WAS_OPEN) {\n downstream.processToken(BracesToken.character('{'));\n } else if (state == State.WAS_OPEN_TWICE) {\n downstream.processToken(BracesToken.twoOpenBraces());\n } else if (state == State.WAS_CLOSE) {\n downstream.processToken(BracesToken.character('}'));\n } else if (state == State.WAS_CLOSE_TWICE) {\n downstream.processToken(BracesToken.twoClosingBraces());\n }\n downstream.processToken(BracesToken.endOfFile());\n state = State.NONE;\n } else if (token == '{') {\n if (state == State.WAS_OPEN) {\n state = State.WAS_OPEN_TWICE;\n } else if (state == State.WAS_OPEN_TWICE) {\n downstream.processToken(BracesToken.threeOpenBraces());\n state = State.NONE;\n } else if (state == State.WAS_CLOSE) {\n downstream.processToken(BracesToken.character('}'));\n state = State.WAS_OPEN;\n } else if (state == State.WAS_CLOSE_TWICE) {\n downstream.processToken(BracesToken.twoClosingBraces());\n state = State.WAS_OPEN;\n } else {\n state = State.WAS_OPEN;\n }\n } else if (token == '}') {\n if (state == State.WAS_CLOSE) {\n state = State.WAS_CLOSE_TWICE;\n } else if (state == State.WAS_CLOSE_TWICE) {\n downstream.processToken(BracesToken.threeClosingBraces());\n state = State.NONE;\n } else if (state == State.WAS_OPEN) {\n downstream.processToken(BracesToken.character('{'));\n state = State.WAS_CLOSE;\n } else if (state == State.WAS_OPEN_TWICE) {\n downstream.processToken(BracesToken.twoOpenBraces());\n state = State.WAS_CLOSE;\n } else {\n state = State.WAS_CLOSE;\n }\n } else {\n if (state == State.WAS_OPEN) {\n downstream.processToken(BracesToken.character('{'));\n } else if (state == State.WAS_OPEN_TWICE) {\n downstream.processToken(BracesToken.twoOpenBraces());\n } else if (state == State.WAS_CLOSE) {\n downstream.processToken(BracesToken.character('}'));\n } else if (state == State.WAS_CLOSE_TWICE) {\n downstream.processToken(BracesToken.twoClosingBraces());\n }\n downstream.processToken(BracesToken.character(token));\n state = State.NONE;\n }\n }\n\n private enum State {\n WAS_OPEN, WAS_OPEN_TWICE, WAS_CLOSE, WAS_CLOSE_TWICE, NONE\n }\n}", "public class PositionHodingTokenProcessor<T> implements TokenProcessor<T> {\n private final TokenProcessor<PositionedToken<T>> downstream;\n private Position position = null;\n\n public PositionHodingTokenProcessor(TokenProcessor<PositionedToken<T>> downstream) {\n this.downstream = downstream;\n }\n\n public void setPosition(Position position) {\n this.position = position;\n }\n\n @Override\n public void processToken(T transformedToken) throws ProcessingException {\n downstream.processToken(new PositionedToken<T>(position, transformedToken));\n }\n\n}" ]
import com.github.sviperll.staticmustache.Position; import com.github.sviperll.staticmustache.PositionedToken; import com.github.sviperll.staticmustache.ProcessingException; import com.github.sviperll.staticmustache.TokenProcessor; import com.github.sviperll.staticmustache.token.util.BracesTokenizer; import com.github.sviperll.staticmustache.token.util.PositionHodingTokenProcessor; import javax.annotation.Nonnull; import com.github.sviperll.staticmustache.MustacheToken;
/* * Copyright (c) 2014, Victor Nazarov <asviraspossible@gmail.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.github.sviperll.staticmustache.token; /** * * @author Victor Nazarov <asviraspossible@gmail.com> */ public class MustacheTokenizer implements TokenProcessor<PositionedToken<BracesToken>> { /** * Creates TokenProcessor to be feed one-by-one with each character of mustache template. * Last fed character must be TokenProcessor#EOF wich denotes end of file. * * @param fileName fileName used in error messages. It can be custom string like "&lt;stdin&gt;" * @param downstream TokenProcessor is invoked on each found MustacheToken * @return . */ public static TokenProcessor<Character> createInstance(String fileName, TokenProcessor<PositionedToken<MustacheToken>> downstream) { TokenProcessor<PositionedToken<BracesToken>> mustacheTokenizer = new MustacheTokenizer(new PositionHodingTokenProcessor<MustacheToken>(downstream)); return BracesTokenizer.createInstance(fileName, mustacheTokenizer); } private final PositionHodingTokenProcessor<MustacheToken> downstream; private MustacheTokenizerState state = new OutsideMustacheTokenizerState(this); private Position position; MustacheTokenizer(PositionHodingTokenProcessor<MustacheToken> downstream) { this.downstream = downstream; } @Override
public void processToken(@Nonnull PositionedToken<BracesToken> positionedToken) throws ProcessingException {
3
epfl-labos/eagle
src/main/java/ch/epfl/eagle/api/EagleFrontendClient.java
[ "public class Network {\n \n public static THostPort socketAddressToThrift(InetSocketAddress address) {\n return new THostPort(address.getAddress().getHostAddress(), address.getPort());\n }\n\n /** Return the hostname of this machine, based on configured value, or system\n * Interrogation. */\n public static String getHostName(Configuration conf) {\n String defaultHostname = null;\n try {\n defaultHostname = InetAddress.getLocalHost().getHostName();\n } catch (UnknownHostException e) {\n defaultHostname = \"localhost\";\n }\n return conf.getString(EagleConf.HOSTNAME, defaultHostname); \n }\n \n /**\n * Return the IP address of this machine, as determined from the hostname\n * specified in configuration or from querying the machine.\n */\n public static String getIPAddress(Configuration conf) {\n String hostname = getHostName(conf);\n try {\n return InetAddress.getByName(hostname).getHostAddress();\n } catch (UnknownHostException e) {\n return \"IP UNKNOWN\";\n }\n }\n}", "public class TClients {\n private final static Logger LOG = Logger.getLogger(TClients.class);\n\n public static NodeMonitorService.Client createBlockingNmClient(String host, int port)\n throws IOException {\n return createBlockingNmClient(host, port, 0);\n }\n\n public static NodeMonitorService.Client createBlockingNmClient(String host, int port,\n int timeout)\n throws IOException {\n TTransport tr = new TFramedTransport(new TSocket(host, port, timeout));\n try {\n tr.open();\n } catch (TTransportException e) {\n LOG.warn(\"Error creating node monitor client to \" + host + \":\" + port);\n throw new IOException(e);\n }\n TProtocol proto = new TBinaryProtocol(tr);\n NodeMonitorService.Client client = new NodeMonitorService.Client(proto);\n return client;\n }\n\n public static SchedulerService.Client createBlockingSchedulerClient(\n InetSocketAddress socket) throws IOException {\n return createBlockingSchedulerClient(socket.getAddress().getHostAddress(), socket.getPort());\n }\n\n public static SchedulerService.Client createBlockingSchedulerClient(\n String host, int port) throws IOException {\n return createBlockingSchedulerClient(host, port, 0);\n }\n\n public static SchedulerService.Client createBlockingSchedulerClient(\n String host, int port, int timeout) throws IOException {\n TTransport tr = new TFramedTransport(new TSocket(host, port, timeout));\n try {\n tr.open();\n } catch (TTransportException e) {\n LOG.warn(\"Error creating scheduler client to \" + host + \":\" + port);\n throw new IOException(e);\n }\n TProtocol proto = new TBinaryProtocol(tr);\n SchedulerService.Client client = new SchedulerService.Client(proto);\n return client;\n }\n\n public static GetTaskService.Client createBlockingGetTaskClient(\n InetSocketAddress socket) throws IOException {\n return createBlockingGetTaskClient(socket.getAddress().getHostAddress(), socket.getPort());\n }\n\n public static GetTaskService.Client createBlockingGetTaskClient(\n String host, int port) throws IOException {\n return createBlockingGetTaskClient(host, port, 0);\n }\n\n public static GetTaskService.Client createBlockingGetTaskClient(\n String host, int port, int timeout) throws IOException {\n TTransport tr = new TFramedTransport(new TSocket(host, port, timeout));\n try {\n tr.open();\n } catch (TTransportException e) {\n LOG.warn(\"Error creating scheduler client to \" + host + \":\" + port);\n throw new IOException(e);\n }\n TProtocol proto = new TBinaryProtocol(tr);\n GetTaskService.Client client = new GetTaskService.Client(proto);\n return client;\n }\n\n public static BackendService.Client createBlockingBackendClient(\n InetSocketAddress socket) throws IOException {\n return createBlockingBackendClient(socket.getAddress().getHostAddress(), socket.getPort());\n }\n\n public static BackendService.Client createBlockingBackendClient(\n String host, int port) throws IOException {\n TTransport tr = new TFramedTransport(new TSocket(host, port));\n try {\n tr.open();\n } catch (TTransportException e) {\n LOG.warn(\"Error creating backend client to \" + host + \":\" + port);\n throw new IOException(e);\n }\n TProtocol proto = new TBinaryProtocol(tr);\n BackendService.Client client = new BackendService.Client(proto);\n return client;\n }\n\n public static StateStoreService.Client createBlockingStateStoreClient(\n String host, int port) throws IOException {\n TTransport tr = new TFramedTransport(new TSocket(host, port));\n try {\n tr.open();\n } catch (TTransportException e) {\n LOG.warn(\"Error creating state store client to \" + host + \":\" + port);\n throw new IOException(e);\n }\n TProtocol proto = new TBinaryProtocol(tr);\n StateStoreService.Client client = new StateStoreService.Client(proto);\n return client;\n }\n\n public static FrontendService.Client createBlockingFrontendClient(\n InetSocketAddress socket) throws IOException {\n return createBlockingFrontendClient(socket.getAddress().getHostAddress(), socket.getPort());\n }\n\n public static FrontendService.Client createBlockingFrontendClient(\n String host, int port) throws IOException {\n TTransport tr = new TFramedTransport(new TSocket(host, port));\n try {\n tr.open();\n } catch (TTransportException e) {\n LOG.warn(\"Error creating state store client to \" + host + \":\" + port);\n throw new IOException(e);\n }\n TProtocol proto = new TBinaryProtocol(tr);\n FrontendService.Client client = new FrontendService.Client(proto);\n return client;\n }\n}", "public class TServers {\n private final static Logger LOG = Logger.getLogger(TServers.class);\n private final static int SELECTOR_THREADS = 4;\n\n /**\n * Launch a single threaded nonblocking IO server. All requests to this server will be\n * handled in a single thread, so its requests should not contain blocking functions.\n */\n public static void launchSingleThreadThriftServer(int port, TProcessor processor)\n throws IOException {\n LOG.info(\"Staring async thrift server of type: \" + processor.getClass().toString()\n + \" on port \" + port);\n TNonblockingServerTransport serverTransport;\n try {\n serverTransport = new TNonblockingServerSocket(port);\n } catch (TTransportException e) {\n throw new IOException(e);\n }\n TNonblockingServer.Args serverArgs = new TNonblockingServer.Args(serverTransport);\n serverArgs.processor(processor);\n TServer server = new TNonblockingServer(serverArgs);\n new Thread(new TServerRunnable(server)).start();\n }\n\n /**\n * Launch a multi-threaded Thrift server with the given {@code processor}. Note that\n * internally this creates an expanding thread pool of at most {@code threads} threads,\n * and requests are queued whenever that thread pool is saturated.\n */\n public static void launchThreadedThriftServer(int port, int threads,\n TProcessor processor) throws IOException {\n LOG.info(\"Staring async thrift server of type: \" + processor.getClass().toString()\n \t\t+ \" on port \" + port);\n TNonblockingServerTransport serverTransport;\n try {\n serverTransport = new TNonblockingServerSocket(port);\n } catch (TTransportException e) {\n throw new IOException(e);\n }\n TThreadedSelectorServer.Args serverArgs = new TThreadedSelectorServer.Args(serverTransport);\n serverArgs.transportFactory(new TFramedTransport.Factory());\n serverArgs.protocolFactory(new TBinaryProtocol.Factory());\n serverArgs.processor(processor);\n serverArgs.selectorThreads(SELECTOR_THREADS);\n serverArgs.workerThreads(threads);\n TServer server = new TThreadedSelectorServer(serverArgs);\n new Thread(new TServerRunnable(server)).start();\n }\n\n /**\n * Runnable class to wrap thrift servers in their own thread.\n */\n private static class TServerRunnable implements Runnable {\n private TServer server;\n\n public TServerRunnable(TServer server) {\n this.server = server;\n }\n\n public void run() {\n this.server.serve();\n }\n }\n}", "@SuppressWarnings({\"cast\", \"rawtypes\", \"serial\", \"unchecked\"})\n@Generated(value = \"Autogenerated by Thrift Compiler (0.9.3)\", date = \"2016-03-03\")\npublic class FrontendService {\n\n public interface Iface {\n\n public void frontendMessage(ch.epfl.eagle.thrift.TFullTaskId taskId, int status, ByteBuffer message) throws org.apache.thrift.TException;\n\n }\n\n public interface AsyncIface {\n\n public void frontendMessage(ch.epfl.eagle.thrift.TFullTaskId taskId, int status, ByteBuffer message, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException;\n\n }\n\n public static class Client extends org.apache.thrift.TServiceClient implements Iface {\n public static class Factory implements org.apache.thrift.TServiceClientFactory<Client> {\n public Factory() {}\n public Client getClient(org.apache.thrift.protocol.TProtocol prot) {\n return new Client(prot);\n }\n public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {\n return new Client(iprot, oprot);\n }\n }\n\n public Client(org.apache.thrift.protocol.TProtocol prot)\n {\n super(prot, prot);\n }\n\n public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {\n super(iprot, oprot);\n }\n\n public void frontendMessage(ch.epfl.eagle.thrift.TFullTaskId taskId, int status, ByteBuffer message) throws org.apache.thrift.TException\n {\n send_frontendMessage(taskId, status, message);\n recv_frontendMessage();\n }\n\n public void send_frontendMessage(ch.epfl.eagle.thrift.TFullTaskId taskId, int status, ByteBuffer message) throws org.apache.thrift.TException\n {\n frontendMessage_args args = new frontendMessage_args();\n args.setTaskId(taskId);\n args.setStatus(status);\n args.setMessage(message);\n sendBase(\"frontendMessage\", args);\n }\n\n public void recv_frontendMessage() throws org.apache.thrift.TException\n {\n frontendMessage_result result = new frontendMessage_result();\n receiveBase(result, \"frontendMessage\");\n return;\n }\n\n }\n public static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface {\n public static class Factory implements org.apache.thrift.async.TAsyncClientFactory<AsyncClient> {\n private org.apache.thrift.async.TAsyncClientManager clientManager;\n private org.apache.thrift.protocol.TProtocolFactory protocolFactory;\n public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) {\n this.clientManager = clientManager;\n this.protocolFactory = protocolFactory;\n }\n public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) {\n return new AsyncClient(protocolFactory, clientManager, transport);\n }\n }\n\n public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.transport.TNonblockingTransport transport) {\n super(protocolFactory, clientManager, transport);\n }\n\n public void frontendMessage(ch.epfl.eagle.thrift.TFullTaskId taskId, int status, ByteBuffer message, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {\n checkReady();\n frontendMessage_call method_call = new frontendMessage_call(taskId, status, message, resultHandler, this, ___protocolFactory, ___transport);\n this.___currentMethod = method_call;\n ___manager.call(method_call);\n }\n\n public static class frontendMessage_call extends org.apache.thrift.async.TAsyncMethodCall {\n private ch.epfl.eagle.thrift.TFullTaskId taskId;\n private int status;\n private ByteBuffer message;\n public frontendMessage_call(ch.epfl.eagle.thrift.TFullTaskId taskId, int status, ByteBuffer message, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {\n super(client, protocolFactory, transport, resultHandler, false);\n this.taskId = taskId;\n this.status = status;\n this.message = message;\n }\n\n public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {\n prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage(\"frontendMessage\", org.apache.thrift.protocol.TMessageType.CALL, 0));\n frontendMessage_args args = new frontendMessage_args();\n args.setTaskId(taskId);\n args.setStatus(status);\n args.setMessage(message);\n args.write(prot);\n prot.writeMessageEnd();\n }\n\n public void getResult() throws org.apache.thrift.TException {\n if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {\n throw new IllegalStateException(\"Method call not finished!\");\n }\n org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());\n org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);\n (new Client(prot)).recv_frontendMessage();\n }\n }\n\n }\n\n public static class Processor<I extends Iface> extends org.apache.thrift.TBaseProcessor<I> implements org.apache.thrift.TProcessor {\n private static final Logger LOGGER = LoggerFactory.getLogger(Processor.class.getName());\n public Processor(I iface) {\n super(iface, getProcessMap(new HashMap<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>>()));\n }\n\n protected Processor(I iface, Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {\n super(iface, getProcessMap(processMap));\n }\n\n private static <I extends Iface> Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> getProcessMap(Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {\n processMap.put(\"frontendMessage\", new frontendMessage());\n return processMap;\n }\n\n public static class frontendMessage<I extends Iface> extends org.apache.thrift.ProcessFunction<I, frontendMessage_args> {\n public frontendMessage() {\n super(\"frontendMessage\");\n }\n\n public frontendMessage_args getEmptyArgsInstance() {\n return new frontendMessage_args();\n }\n\n protected boolean isOneway() {\n return false;\n }\n\n public frontendMessage_result getResult(I iface, frontendMessage_args args) throws org.apache.thrift.TException {\n frontendMessage_result result = new frontendMessage_result();\n iface.frontendMessage(args.taskId, args.status, args.message);\n return result;\n }\n }\n\n }\n\n public static class AsyncProcessor<I extends AsyncIface> extends org.apache.thrift.TBaseAsyncProcessor<I> {\n private static final Logger LOGGER = LoggerFactory.getLogger(AsyncProcessor.class.getName());\n public AsyncProcessor(I iface) {\n super(iface, getProcessMap(new HashMap<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>>()));\n }\n\n protected AsyncProcessor(I iface, Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {\n super(iface, getProcessMap(processMap));\n }\n\n private static <I extends AsyncIface> Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase,?>> getProcessMap(Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {\n processMap.put(\"frontendMessage\", new frontendMessage());\n return processMap;\n }\n\n public static class frontendMessage<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, frontendMessage_args, Void> {\n public frontendMessage() {\n super(\"frontendMessage\");\n }\n\n public frontendMessage_args getEmptyArgsInstance() {\n return new frontendMessage_args();\n }\n\n public AsyncMethodCallback<Void> getResultHandler(final AsyncFrameBuffer fb, final int seqid) {\n final org.apache.thrift.AsyncProcessFunction fcall = this;\n return new AsyncMethodCallback<Void>() { \n public void onComplete(Void o) {\n frontendMessage_result result = new frontendMessage_result();\n try {\n fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);\n return;\n } catch (Exception e) {\n LOGGER.error(\"Exception writing to internal frame buffer\", e);\n }\n fb.close();\n }\n public void onError(Exception e) {\n byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;\n org.apache.thrift.TBase msg;\n frontendMessage_result result = new frontendMessage_result();\n {\n msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;\n msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());\n }\n try {\n fcall.sendResponse(fb,msg,msgType,seqid);\n return;\n } catch (Exception ex) {\n LOGGER.error(\"Exception writing to internal frame buffer\", ex);\n }\n fb.close();\n }\n };\n }\n\n protected boolean isOneway() {\n return false;\n }\n\n public void start(I iface, frontendMessage_args args, org.apache.thrift.async.AsyncMethodCallback<Void> resultHandler) throws TException {\n iface.frontendMessage(args.taskId, args.status, args.message,resultHandler);\n }\n }\n\n }\n\n public static class frontendMessage_args implements org.apache.thrift.TBase<frontendMessage_args, frontendMessage_args._Fields>, java.io.Serializable, Cloneable, Comparable<frontendMessage_args> {\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"frontendMessage_args\");\n\n private static final org.apache.thrift.protocol.TField TASK_ID_FIELD_DESC = new org.apache.thrift.protocol.TField(\"taskId\", org.apache.thrift.protocol.TType.STRUCT, (short)1);\n private static final org.apache.thrift.protocol.TField STATUS_FIELD_DESC = new org.apache.thrift.protocol.TField(\"status\", org.apache.thrift.protocol.TType.I32, (short)2);\n private static final org.apache.thrift.protocol.TField MESSAGE_FIELD_DESC = new org.apache.thrift.protocol.TField(\"message\", org.apache.thrift.protocol.TType.STRING, (short)3);\n\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\n static {\n schemes.put(StandardScheme.class, new frontendMessage_argsStandardSchemeFactory());\n schemes.put(TupleScheme.class, new frontendMessage_argsTupleSchemeFactory());\n }\n\n public ch.epfl.eagle.thrift.TFullTaskId taskId; // required\n public int status; // required\n public ByteBuffer message; // required\n\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\n TASK_ID((short)1, \"taskId\"),\n STATUS((short)2, \"status\"),\n MESSAGE((short)3, \"message\");\n\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\n\n static {\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\n byName.put(field.getFieldName(), field);\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, or null if its not found.\n */\n public static _Fields findByThriftId(int fieldId) {\n switch(fieldId) {\n case 1: // TASK_ID\n return TASK_ID;\n case 2: // STATUS\n return STATUS;\n case 3: // MESSAGE\n return MESSAGE;\n default:\n return null;\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, throwing an exception\n * if it is not found.\n */\n public static _Fields findByThriftIdOrThrow(int fieldId) {\n _Fields fields = findByThriftId(fieldId);\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\n return fields;\n }\n\n /**\n * Find the _Fields constant that matches name, or null if its not found.\n */\n public static _Fields findByName(String name) {\n return byName.get(name);\n }\n\n private final short _thriftId;\n private final String _fieldName;\n\n _Fields(short thriftId, String fieldName) {\n _thriftId = thriftId;\n _fieldName = fieldName;\n }\n\n public short getThriftFieldId() {\n return _thriftId;\n }\n\n public String getFieldName() {\n return _fieldName;\n }\n }\n\n // isset id assignments\n private static final int __STATUS_ISSET_ID = 0;\n private byte __isset_bitfield = 0;\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\n static {\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\n tmpMap.put(_Fields.TASK_ID, new org.apache.thrift.meta_data.FieldMetaData(\"taskId\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, ch.epfl.eagle.thrift.TFullTaskId.class)));\n tmpMap.put(_Fields.STATUS, new org.apache.thrift.meta_data.FieldMetaData(\"status\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));\n tmpMap.put(_Fields.MESSAGE, new org.apache.thrift.meta_data.FieldMetaData(\"message\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING , true)));\n metaDataMap = Collections.unmodifiableMap(tmpMap);\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(frontendMessage_args.class, metaDataMap);\n }\n\n public frontendMessage_args() {\n }\n\n public frontendMessage_args(\n ch.epfl.eagle.thrift.TFullTaskId taskId,\n int status,\n ByteBuffer message)\n {\n this();\n this.taskId = taskId;\n this.status = status;\n setStatusIsSet(true);\n this.message = org.apache.thrift.TBaseHelper.copyBinary(message);\n }\n\n /**\n * Performs a deep copy on <i>other</i>.\n */\n public frontendMessage_args(frontendMessage_args other) {\n __isset_bitfield = other.__isset_bitfield;\n if (other.isSetTaskId()) {\n this.taskId = new ch.epfl.eagle.thrift.TFullTaskId(other.taskId);\n }\n this.status = other.status;\n if (other.isSetMessage()) {\n this.message = org.apache.thrift.TBaseHelper.copyBinary(other.message);\n }\n }\n\n public frontendMessage_args deepCopy() {\n return new frontendMessage_args(this);\n }\n\n @Override\n public void clear() {\n this.taskId = null;\n setStatusIsSet(false);\n this.status = 0;\n this.message = null;\n }\n\n public ch.epfl.eagle.thrift.TFullTaskId getTaskId() {\n return this.taskId;\n }\n\n public frontendMessage_args setTaskId(ch.epfl.eagle.thrift.TFullTaskId taskId) {\n this.taskId = taskId;\n return this;\n }\n\n public void unsetTaskId() {\n this.taskId = null;\n }\n\n /** Returns true if field taskId is set (has been assigned a value) and false otherwise */\n public boolean isSetTaskId() {\n return this.taskId != null;\n }\n\n public void setTaskIdIsSet(boolean value) {\n if (!value) {\n this.taskId = null;\n }\n }\n\n public int getStatus() {\n return this.status;\n }\n\n public frontendMessage_args setStatus(int status) {\n this.status = status;\n setStatusIsSet(true);\n return this;\n }\n\n public void unsetStatus() {\n __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __STATUS_ISSET_ID);\n }\n\n /** Returns true if field status is set (has been assigned a value) and false otherwise */\n public boolean isSetStatus() {\n return EncodingUtils.testBit(__isset_bitfield, __STATUS_ISSET_ID);\n }\n\n public void setStatusIsSet(boolean value) {\n __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __STATUS_ISSET_ID, value);\n }\n\n public byte[] getMessage() {\n setMessage(org.apache.thrift.TBaseHelper.rightSize(message));\n return message == null ? null : message.array();\n }\n\n public ByteBuffer bufferForMessage() {\n return org.apache.thrift.TBaseHelper.copyBinary(message);\n }\n\n public frontendMessage_args setMessage(byte[] message) {\n this.message = message == null ? (ByteBuffer)null : ByteBuffer.wrap(Arrays.copyOf(message, message.length));\n return this;\n }\n\n public frontendMessage_args setMessage(ByteBuffer message) {\n this.message = org.apache.thrift.TBaseHelper.copyBinary(message);\n return this;\n }\n\n public void unsetMessage() {\n this.message = null;\n }\n\n /** Returns true if field message is set (has been assigned a value) and false otherwise */\n public boolean isSetMessage() {\n return this.message != null;\n }\n\n public void setMessageIsSet(boolean value) {\n if (!value) {\n this.message = null;\n }\n }\n\n public void setFieldValue(_Fields field, Object value) {\n switch (field) {\n case TASK_ID:\n if (value == null) {\n unsetTaskId();\n } else {\n setTaskId((ch.epfl.eagle.thrift.TFullTaskId)value);\n }\n break;\n\n case STATUS:\n if (value == null) {\n unsetStatus();\n } else {\n setStatus((Integer)value);\n }\n break;\n\n case MESSAGE:\n if (value == null) {\n unsetMessage();\n } else {\n setMessage((ByteBuffer)value);\n }\n break;\n\n }\n }\n\n public Object getFieldValue(_Fields field) {\n switch (field) {\n case TASK_ID:\n return getTaskId();\n\n case STATUS:\n return getStatus();\n\n case MESSAGE:\n return getMessage();\n\n }\n throw new IllegalStateException();\n }\n\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\n public boolean isSet(_Fields field) {\n if (field == null) {\n throw new IllegalArgumentException();\n }\n\n switch (field) {\n case TASK_ID:\n return isSetTaskId();\n case STATUS:\n return isSetStatus();\n case MESSAGE:\n return isSetMessage();\n }\n throw new IllegalStateException();\n }\n\n @Override\n public boolean equals(Object that) {\n if (that == null)\n return false;\n if (that instanceof frontendMessage_args)\n return this.equals((frontendMessage_args)that);\n return false;\n }\n\n public boolean equals(frontendMessage_args that) {\n if (that == null)\n return false;\n\n boolean this_present_taskId = true && this.isSetTaskId();\n boolean that_present_taskId = true && that.isSetTaskId();\n if (this_present_taskId || that_present_taskId) {\n if (!(this_present_taskId && that_present_taskId))\n return false;\n if (!this.taskId.equals(that.taskId))\n return false;\n }\n\n boolean this_present_status = true;\n boolean that_present_status = true;\n if (this_present_status || that_present_status) {\n if (!(this_present_status && that_present_status))\n return false;\n if (this.status != that.status)\n return false;\n }\n\n boolean this_present_message = true && this.isSetMessage();\n boolean that_present_message = true && that.isSetMessage();\n if (this_present_message || that_present_message) {\n if (!(this_present_message && that_present_message))\n return false;\n if (!this.message.equals(that.message))\n return false;\n }\n\n return true;\n }\n\n @Override\n public int hashCode() {\n List<Object> list = new ArrayList<Object>();\n\n boolean present_taskId = true && (isSetTaskId());\n list.add(present_taskId);\n if (present_taskId)\n list.add(taskId);\n\n boolean present_status = true;\n list.add(present_status);\n if (present_status)\n list.add(status);\n\n boolean present_message = true && (isSetMessage());\n list.add(present_message);\n if (present_message)\n list.add(message);\n\n return list.hashCode();\n }\n\n @Override\n public int compareTo(frontendMessage_args other) {\n if (!getClass().equals(other.getClass())) {\n return getClass().getName().compareTo(other.getClass().getName());\n }\n\n int lastComparison = 0;\n\n lastComparison = Boolean.valueOf(isSetTaskId()).compareTo(other.isSetTaskId());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetTaskId()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.taskId, other.taskId);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n lastComparison = Boolean.valueOf(isSetStatus()).compareTo(other.isSetStatus());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetStatus()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.status, other.status);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n lastComparison = Boolean.valueOf(isSetMessage()).compareTo(other.isSetMessage());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetMessage()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.message, other.message);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n return 0;\n }\n\n public _Fields fieldForId(int fieldId) {\n return _Fields.findByThriftId(fieldId);\n }\n\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder(\"frontendMessage_args(\");\n boolean first = true;\n\n sb.append(\"taskId:\");\n if (this.taskId == null) {\n sb.append(\"null\");\n } else {\n sb.append(this.taskId);\n }\n first = false;\n if (!first) sb.append(\", \");\n sb.append(\"status:\");\n sb.append(this.status);\n first = false;\n if (!first) sb.append(\", \");\n sb.append(\"message:\");\n if (this.message == null) {\n sb.append(\"null\");\n } else {\n org.apache.thrift.TBaseHelper.toString(this.message, sb);\n }\n first = false;\n sb.append(\")\");\n return sb.toString();\n }\n\n public void validate() throws org.apache.thrift.TException {\n // check for required fields\n // check for sub-struct validity\n if (taskId != null) {\n taskId.validate();\n }\n }\n\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\n try {\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\n try {\n // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.\n __isset_bitfield = 0;\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private static class frontendMessage_argsStandardSchemeFactory implements SchemeFactory {\n public frontendMessage_argsStandardScheme getScheme() {\n return new frontendMessage_argsStandardScheme();\n }\n }\n\n private static class frontendMessage_argsStandardScheme extends StandardScheme<frontendMessage_args> {\n\n public void read(org.apache.thrift.protocol.TProtocol iprot, frontendMessage_args struct) throws org.apache.thrift.TException {\n org.apache.thrift.protocol.TField schemeField;\n iprot.readStructBegin();\n while (true)\n {\n schemeField = iprot.readFieldBegin();\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \n break;\n }\n switch (schemeField.id) {\n case 1: // TASK_ID\n if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) {\n struct.taskId = new ch.epfl.eagle.thrift.TFullTaskId();\n struct.taskId.read(iprot);\n struct.setTaskIdIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n case 2: // STATUS\n if (schemeField.type == org.apache.thrift.protocol.TType.I32) {\n struct.status = iprot.readI32();\n struct.setStatusIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n case 3: // MESSAGE\n if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {\n struct.message = iprot.readBinary();\n struct.setMessageIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n default:\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n iprot.readFieldEnd();\n }\n iprot.readStructEnd();\n\n // check for required fields of primitive type, which can't be checked in the validate method\n struct.validate();\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot, frontendMessage_args struct) throws org.apache.thrift.TException {\n struct.validate();\n\n oprot.writeStructBegin(STRUCT_DESC);\n if (struct.taskId != null) {\n oprot.writeFieldBegin(TASK_ID_FIELD_DESC);\n struct.taskId.write(oprot);\n oprot.writeFieldEnd();\n }\n oprot.writeFieldBegin(STATUS_FIELD_DESC);\n oprot.writeI32(struct.status);\n oprot.writeFieldEnd();\n if (struct.message != null) {\n oprot.writeFieldBegin(MESSAGE_FIELD_DESC);\n oprot.writeBinary(struct.message);\n oprot.writeFieldEnd();\n }\n oprot.writeFieldStop();\n oprot.writeStructEnd();\n }\n\n }\n\n private static class frontendMessage_argsTupleSchemeFactory implements SchemeFactory {\n public frontendMessage_argsTupleScheme getScheme() {\n return new frontendMessage_argsTupleScheme();\n }\n }\n\n private static class frontendMessage_argsTupleScheme extends TupleScheme<frontendMessage_args> {\n\n @Override\n public void write(org.apache.thrift.protocol.TProtocol prot, frontendMessage_args struct) throws org.apache.thrift.TException {\n TTupleProtocol oprot = (TTupleProtocol) prot;\n BitSet optionals = new BitSet();\n if (struct.isSetTaskId()) {\n optionals.set(0);\n }\n if (struct.isSetStatus()) {\n optionals.set(1);\n }\n if (struct.isSetMessage()) {\n optionals.set(2);\n }\n oprot.writeBitSet(optionals, 3);\n if (struct.isSetTaskId()) {\n struct.taskId.write(oprot);\n }\n if (struct.isSetStatus()) {\n oprot.writeI32(struct.status);\n }\n if (struct.isSetMessage()) {\n oprot.writeBinary(struct.message);\n }\n }\n\n @Override\n public void read(org.apache.thrift.protocol.TProtocol prot, frontendMessage_args struct) throws org.apache.thrift.TException {\n TTupleProtocol iprot = (TTupleProtocol) prot;\n BitSet incoming = iprot.readBitSet(3);\n if (incoming.get(0)) {\n struct.taskId = new ch.epfl.eagle.thrift.TFullTaskId();\n struct.taskId.read(iprot);\n struct.setTaskIdIsSet(true);\n }\n if (incoming.get(1)) {\n struct.status = iprot.readI32();\n struct.setStatusIsSet(true);\n }\n if (incoming.get(2)) {\n struct.message = iprot.readBinary();\n struct.setMessageIsSet(true);\n }\n }\n }\n\n }\n\n public static class frontendMessage_result implements org.apache.thrift.TBase<frontendMessage_result, frontendMessage_result._Fields>, java.io.Serializable, Cloneable, Comparable<frontendMessage_result> {\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"frontendMessage_result\");\n\n\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\n static {\n schemes.put(StandardScheme.class, new frontendMessage_resultStandardSchemeFactory());\n schemes.put(TupleScheme.class, new frontendMessage_resultTupleSchemeFactory());\n }\n\n\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\n;\n\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\n\n static {\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\n byName.put(field.getFieldName(), field);\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, or null if its not found.\n */\n public static _Fields findByThriftId(int fieldId) {\n switch(fieldId) {\n default:\n return null;\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, throwing an exception\n * if it is not found.\n */\n public static _Fields findByThriftIdOrThrow(int fieldId) {\n _Fields fields = findByThriftId(fieldId);\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\n return fields;\n }\n\n /**\n * Find the _Fields constant that matches name, or null if its not found.\n */\n public static _Fields findByName(String name) {\n return byName.get(name);\n }\n\n private final short _thriftId;\n private final String _fieldName;\n\n _Fields(short thriftId, String fieldName) {\n _thriftId = thriftId;\n _fieldName = fieldName;\n }\n\n public short getThriftFieldId() {\n return _thriftId;\n }\n\n public String getFieldName() {\n return _fieldName;\n }\n }\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\n static {\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\n metaDataMap = Collections.unmodifiableMap(tmpMap);\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(frontendMessage_result.class, metaDataMap);\n }\n\n public frontendMessage_result() {\n }\n\n /**\n * Performs a deep copy on <i>other</i>.\n */\n public frontendMessage_result(frontendMessage_result other) {\n }\n\n public frontendMessage_result deepCopy() {\n return new frontendMessage_result(this);\n }\n\n @Override\n public void clear() {\n }\n\n public void setFieldValue(_Fields field, Object value) {\n switch (field) {\n }\n }\n\n public Object getFieldValue(_Fields field) {\n switch (field) {\n }\n throw new IllegalStateException();\n }\n\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\n public boolean isSet(_Fields field) {\n if (field == null) {\n throw new IllegalArgumentException();\n }\n\n switch (field) {\n }\n throw new IllegalStateException();\n }\n\n @Override\n public boolean equals(Object that) {\n if (that == null)\n return false;\n if (that instanceof frontendMessage_result)\n return this.equals((frontendMessage_result)that);\n return false;\n }\n\n public boolean equals(frontendMessage_result that) {\n if (that == null)\n return false;\n\n return true;\n }\n\n @Override\n public int hashCode() {\n List<Object> list = new ArrayList<Object>();\n\n return list.hashCode();\n }\n\n @Override\n public int compareTo(frontendMessage_result other) {\n if (!getClass().equals(other.getClass())) {\n return getClass().getName().compareTo(other.getClass().getName());\n }\n\n int lastComparison = 0;\n\n return 0;\n }\n\n public _Fields fieldForId(int fieldId) {\n return _Fields.findByThriftId(fieldId);\n }\n\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder(\"frontendMessage_result(\");\n boolean first = true;\n\n sb.append(\")\");\n return sb.toString();\n }\n\n public void validate() throws org.apache.thrift.TException {\n // check for required fields\n // check for sub-struct validity\n }\n\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\n try {\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\n try {\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private static class frontendMessage_resultStandardSchemeFactory implements SchemeFactory {\n public frontendMessage_resultStandardScheme getScheme() {\n return new frontendMessage_resultStandardScheme();\n }\n }\n\n private static class frontendMessage_resultStandardScheme extends StandardScheme<frontendMessage_result> {\n\n public void read(org.apache.thrift.protocol.TProtocol iprot, frontendMessage_result struct) throws org.apache.thrift.TException {\n org.apache.thrift.protocol.TField schemeField;\n iprot.readStructBegin();\n while (true)\n {\n schemeField = iprot.readFieldBegin();\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \n break;\n }\n switch (schemeField.id) {\n default:\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n iprot.readFieldEnd();\n }\n iprot.readStructEnd();\n\n // check for required fields of primitive type, which can't be checked in the validate method\n struct.validate();\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot, frontendMessage_result struct) throws org.apache.thrift.TException {\n struct.validate();\n\n oprot.writeStructBegin(STRUCT_DESC);\n oprot.writeFieldStop();\n oprot.writeStructEnd();\n }\n\n }\n\n private static class frontendMessage_resultTupleSchemeFactory implements SchemeFactory {\n public frontendMessage_resultTupleScheme getScheme() {\n return new frontendMessage_resultTupleScheme();\n }\n }\n\n private static class frontendMessage_resultTupleScheme extends TupleScheme<frontendMessage_result> {\n\n @Override\n public void write(org.apache.thrift.protocol.TProtocol prot, frontendMessage_result struct) throws org.apache.thrift.TException {\n TTupleProtocol oprot = (TTupleProtocol) prot;\n }\n\n @Override\n public void read(org.apache.thrift.protocol.TProtocol prot, frontendMessage_result struct) throws org.apache.thrift.TException {\n TTupleProtocol iprot = (TTupleProtocol) prot;\n }\n }\n\n }\n\n}", "@SuppressWarnings({\"cast\", \"rawtypes\", \"serial\", \"unchecked\"})\n@Generated(value = \"Autogenerated by Thrift Compiler (0.9.3)\", date = \"2016-03-03\")\npublic class IncompleteRequestException extends TException implements org.apache.thrift.TBase<IncompleteRequestException, IncompleteRequestException._Fields>, java.io.Serializable, Cloneable, Comparable<IncompleteRequestException> {\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"IncompleteRequestException\");\n\n private static final org.apache.thrift.protocol.TField MESSAGE_FIELD_DESC = new org.apache.thrift.protocol.TField(\"message\", org.apache.thrift.protocol.TType.STRING, (short)1);\n\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\n static {\n schemes.put(StandardScheme.class, new IncompleteRequestExceptionStandardSchemeFactory());\n schemes.put(TupleScheme.class, new IncompleteRequestExceptionTupleSchemeFactory());\n }\n\n public String message; // required\n\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\n MESSAGE((short)1, \"message\");\n\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\n\n static {\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\n byName.put(field.getFieldName(), field);\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, or null if its not found.\n */\n public static _Fields findByThriftId(int fieldId) {\n switch(fieldId) {\n case 1: // MESSAGE\n return MESSAGE;\n default:\n return null;\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, throwing an exception\n * if it is not found.\n */\n public static _Fields findByThriftIdOrThrow(int fieldId) {\n _Fields fields = findByThriftId(fieldId);\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\n return fields;\n }\n\n /**\n * Find the _Fields constant that matches name, or null if its not found.\n */\n public static _Fields findByName(String name) {\n return byName.get(name);\n }\n\n private final short _thriftId;\n private final String _fieldName;\n\n _Fields(short thriftId, String fieldName) {\n _thriftId = thriftId;\n _fieldName = fieldName;\n }\n\n public short getThriftFieldId() {\n return _thriftId;\n }\n\n public String getFieldName() {\n return _fieldName;\n }\n }\n\n // isset id assignments\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\n static {\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\n tmpMap.put(_Fields.MESSAGE, new org.apache.thrift.meta_data.FieldMetaData(\"message\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));\n metaDataMap = Collections.unmodifiableMap(tmpMap);\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(IncompleteRequestException.class, metaDataMap);\n }\n\n public IncompleteRequestException() {\n }\n\n public IncompleteRequestException(\n String message)\n {\n this();\n this.message = message;\n }\n\n /**\n * Performs a deep copy on <i>other</i>.\n */\n public IncompleteRequestException(IncompleteRequestException other) {\n if (other.isSetMessage()) {\n this.message = other.message;\n }\n }\n\n public IncompleteRequestException deepCopy() {\n return new IncompleteRequestException(this);\n }\n\n @Override\n public void clear() {\n this.message = null;\n }\n\n public String getMessage() {\n return this.message;\n }\n\n public IncompleteRequestException setMessage(String message) {\n this.message = message;\n return this;\n }\n\n public void unsetMessage() {\n this.message = null;\n }\n\n /** Returns true if field message is set (has been assigned a value) and false otherwise */\n public boolean isSetMessage() {\n return this.message != null;\n }\n\n public void setMessageIsSet(boolean value) {\n if (!value) {\n this.message = null;\n }\n }\n\n public void setFieldValue(_Fields field, Object value) {\n switch (field) {\n case MESSAGE:\n if (value == null) {\n unsetMessage();\n } else {\n setMessage((String)value);\n }\n break;\n\n }\n }\n\n public Object getFieldValue(_Fields field) {\n switch (field) {\n case MESSAGE:\n return getMessage();\n\n }\n throw new IllegalStateException();\n }\n\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\n public boolean isSet(_Fields field) {\n if (field == null) {\n throw new IllegalArgumentException();\n }\n\n switch (field) {\n case MESSAGE:\n return isSetMessage();\n }\n throw new IllegalStateException();\n }\n\n @Override\n public boolean equals(Object that) {\n if (that == null)\n return false;\n if (that instanceof IncompleteRequestException)\n return this.equals((IncompleteRequestException)that);\n return false;\n }\n\n public boolean equals(IncompleteRequestException that) {\n if (that == null)\n return false;\n\n boolean this_present_message = true && this.isSetMessage();\n boolean that_present_message = true && that.isSetMessage();\n if (this_present_message || that_present_message) {\n if (!(this_present_message && that_present_message))\n return false;\n if (!this.message.equals(that.message))\n return false;\n }\n\n return true;\n }\n\n @Override\n public int hashCode() {\n List<Object> list = new ArrayList<Object>();\n\n boolean present_message = true && (isSetMessage());\n list.add(present_message);\n if (present_message)\n list.add(message);\n\n return list.hashCode();\n }\n\n @Override\n public int compareTo(IncompleteRequestException other) {\n if (!getClass().equals(other.getClass())) {\n return getClass().getName().compareTo(other.getClass().getName());\n }\n\n int lastComparison = 0;\n\n lastComparison = Boolean.valueOf(isSetMessage()).compareTo(other.isSetMessage());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetMessage()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.message, other.message);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n return 0;\n }\n\n public _Fields fieldForId(int fieldId) {\n return _Fields.findByThriftId(fieldId);\n }\n\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder(\"IncompleteRequestException(\");\n boolean first = true;\n\n sb.append(\"message:\");\n if (this.message == null) {\n sb.append(\"null\");\n } else {\n sb.append(this.message);\n }\n first = false;\n sb.append(\")\");\n return sb.toString();\n }\n\n public void validate() throws org.apache.thrift.TException {\n // check for required fields\n // check for sub-struct validity\n }\n\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\n try {\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\n try {\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private static class IncompleteRequestExceptionStandardSchemeFactory implements SchemeFactory {\n public IncompleteRequestExceptionStandardScheme getScheme() {\n return new IncompleteRequestExceptionStandardScheme();\n }\n }\n\n private static class IncompleteRequestExceptionStandardScheme extends StandardScheme<IncompleteRequestException> {\n\n public void read(org.apache.thrift.protocol.TProtocol iprot, IncompleteRequestException struct) throws org.apache.thrift.TException {\n org.apache.thrift.protocol.TField schemeField;\n iprot.readStructBegin();\n while (true)\n {\n schemeField = iprot.readFieldBegin();\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \n break;\n }\n switch (schemeField.id) {\n case 1: // MESSAGE\n if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {\n struct.message = iprot.readString();\n struct.setMessageIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n default:\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n iprot.readFieldEnd();\n }\n iprot.readStructEnd();\n\n // check for required fields of primitive type, which can't be checked in the validate method\n struct.validate();\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot, IncompleteRequestException struct) throws org.apache.thrift.TException {\n struct.validate();\n\n oprot.writeStructBegin(STRUCT_DESC);\n if (struct.message != null) {\n oprot.writeFieldBegin(MESSAGE_FIELD_DESC);\n oprot.writeString(struct.message);\n oprot.writeFieldEnd();\n }\n oprot.writeFieldStop();\n oprot.writeStructEnd();\n }\n\n }\n\n private static class IncompleteRequestExceptionTupleSchemeFactory implements SchemeFactory {\n public IncompleteRequestExceptionTupleScheme getScheme() {\n return new IncompleteRequestExceptionTupleScheme();\n }\n }\n\n private static class IncompleteRequestExceptionTupleScheme extends TupleScheme<IncompleteRequestException> {\n\n @Override\n public void write(org.apache.thrift.protocol.TProtocol prot, IncompleteRequestException struct) throws org.apache.thrift.TException {\n TTupleProtocol oprot = (TTupleProtocol) prot;\n BitSet optionals = new BitSet();\n if (struct.isSetMessage()) {\n optionals.set(0);\n }\n oprot.writeBitSet(optionals, 1);\n if (struct.isSetMessage()) {\n oprot.writeString(struct.message);\n }\n }\n\n @Override\n public void read(org.apache.thrift.protocol.TProtocol prot, IncompleteRequestException struct) throws org.apache.thrift.TException {\n TTupleProtocol iprot = (TTupleProtocol) prot;\n BitSet incoming = iprot.readBitSet(1);\n if (incoming.get(0)) {\n struct.message = iprot.readString();\n struct.setMessageIsSet(true);\n }\n }\n }\n\n}", "@SuppressWarnings({\"cast\", \"rawtypes\", \"serial\", \"unchecked\"})\n@Generated(value = \"Autogenerated by Thrift Compiler (0.9.3)\", date = \"2016-03-03\")\npublic class SchedulerService {\n\n public interface Iface {\n\n public boolean registerFrontend(String app, String socketAddress) throws org.apache.thrift.TException;\n\n public void submitJob(ch.epfl.eagle.thrift.TSchedulingRequest req) throws ch.epfl.eagle.thrift.IncompleteRequestException, org.apache.thrift.TException;\n\n public void sendFrontendMessage(String app, ch.epfl.eagle.thrift.TFullTaskId taskId, int status, ByteBuffer message) throws org.apache.thrift.TException;\n\n }\n\n public interface AsyncIface {\n\n public void registerFrontend(String app, String socketAddress, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException;\n\n public void submitJob(ch.epfl.eagle.thrift.TSchedulingRequest req, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException;\n\n public void sendFrontendMessage(String app, ch.epfl.eagle.thrift.TFullTaskId taskId, int status, ByteBuffer message, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException;\n\n }\n\n public static class Client extends org.apache.thrift.TServiceClient implements Iface {\n public static class Factory implements org.apache.thrift.TServiceClientFactory<Client> {\n public Factory() {}\n public Client getClient(org.apache.thrift.protocol.TProtocol prot) {\n return new Client(prot);\n }\n public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {\n return new Client(iprot, oprot);\n }\n }\n\n public Client(org.apache.thrift.protocol.TProtocol prot)\n {\n super(prot, prot);\n }\n\n public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {\n super(iprot, oprot);\n }\n\n public boolean registerFrontend(String app, String socketAddress) throws org.apache.thrift.TException\n {\n send_registerFrontend(app, socketAddress);\n return recv_registerFrontend();\n }\n\n public void send_registerFrontend(String app, String socketAddress) throws org.apache.thrift.TException\n {\n registerFrontend_args args = new registerFrontend_args();\n args.setApp(app);\n args.setSocketAddress(socketAddress);\n sendBase(\"registerFrontend\", args);\n }\n\n public boolean recv_registerFrontend() throws org.apache.thrift.TException\n {\n registerFrontend_result result = new registerFrontend_result();\n receiveBase(result, \"registerFrontend\");\n if (result.isSetSuccess()) {\n return result.success;\n }\n throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, \"registerFrontend failed: unknown result\");\n }\n\n public void submitJob(ch.epfl.eagle.thrift.TSchedulingRequest req) throws ch.epfl.eagle.thrift.IncompleteRequestException, org.apache.thrift.TException\n {\n send_submitJob(req);\n recv_submitJob();\n }\n\n public void send_submitJob(ch.epfl.eagle.thrift.TSchedulingRequest req) throws org.apache.thrift.TException\n {\n submitJob_args args = new submitJob_args();\n args.setReq(req);\n sendBase(\"submitJob\", args);\n }\n\n public void recv_submitJob() throws ch.epfl.eagle.thrift.IncompleteRequestException, org.apache.thrift.TException\n {\n submitJob_result result = new submitJob_result();\n receiveBase(result, \"submitJob\");\n if (result.e != null) {\n throw result.e;\n }\n return;\n }\n\n public void sendFrontendMessage(String app, ch.epfl.eagle.thrift.TFullTaskId taskId, int status, ByteBuffer message) throws org.apache.thrift.TException\n {\n send_sendFrontendMessage(app, taskId, status, message);\n recv_sendFrontendMessage();\n }\n\n public void send_sendFrontendMessage(String app, ch.epfl.eagle.thrift.TFullTaskId taskId, int status, ByteBuffer message) throws org.apache.thrift.TException\n {\n sendFrontendMessage_args args = new sendFrontendMessage_args();\n args.setApp(app);\n args.setTaskId(taskId);\n args.setStatus(status);\n args.setMessage(message);\n sendBase(\"sendFrontendMessage\", args);\n }\n\n public void recv_sendFrontendMessage() throws org.apache.thrift.TException\n {\n sendFrontendMessage_result result = new sendFrontendMessage_result();\n receiveBase(result, \"sendFrontendMessage\");\n return;\n }\n\n }\n public static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface {\n public static class Factory implements org.apache.thrift.async.TAsyncClientFactory<AsyncClient> {\n private org.apache.thrift.async.TAsyncClientManager clientManager;\n private org.apache.thrift.protocol.TProtocolFactory protocolFactory;\n public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) {\n this.clientManager = clientManager;\n this.protocolFactory = protocolFactory;\n }\n public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) {\n return new AsyncClient(protocolFactory, clientManager, transport);\n }\n }\n\n public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.transport.TNonblockingTransport transport) {\n super(protocolFactory, clientManager, transport);\n }\n\n public void registerFrontend(String app, String socketAddress, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {\n checkReady();\n registerFrontend_call method_call = new registerFrontend_call(app, socketAddress, resultHandler, this, ___protocolFactory, ___transport);\n this.___currentMethod = method_call;\n ___manager.call(method_call);\n }\n\n public static class registerFrontend_call extends org.apache.thrift.async.TAsyncMethodCall {\n private String app;\n private String socketAddress;\n public registerFrontend_call(String app, String socketAddress, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {\n super(client, protocolFactory, transport, resultHandler, false);\n this.app = app;\n this.socketAddress = socketAddress;\n }\n\n public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {\n prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage(\"registerFrontend\", org.apache.thrift.protocol.TMessageType.CALL, 0));\n registerFrontend_args args = new registerFrontend_args();\n args.setApp(app);\n args.setSocketAddress(socketAddress);\n args.write(prot);\n prot.writeMessageEnd();\n }\n\n public boolean getResult() throws org.apache.thrift.TException {\n if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {\n throw new IllegalStateException(\"Method call not finished!\");\n }\n org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());\n org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);\n return (new Client(prot)).recv_registerFrontend();\n }\n }\n\n public void submitJob(ch.epfl.eagle.thrift.TSchedulingRequest req, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {\n checkReady();\n submitJob_call method_call = new submitJob_call(req, resultHandler, this, ___protocolFactory, ___transport);\n this.___currentMethod = method_call;\n ___manager.call(method_call);\n }\n\n public static class submitJob_call extends org.apache.thrift.async.TAsyncMethodCall {\n private ch.epfl.eagle.thrift.TSchedulingRequest req;\n public submitJob_call(ch.epfl.eagle.thrift.TSchedulingRequest req, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {\n super(client, protocolFactory, transport, resultHandler, false);\n this.req = req;\n }\n\n public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {\n prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage(\"submitJob\", org.apache.thrift.protocol.TMessageType.CALL, 0));\n submitJob_args args = new submitJob_args();\n args.setReq(req);\n args.write(prot);\n prot.writeMessageEnd();\n }\n\n public void getResult() throws ch.epfl.eagle.thrift.IncompleteRequestException, org.apache.thrift.TException {\n if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {\n throw new IllegalStateException(\"Method call not finished!\");\n }\n org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());\n org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);\n (new Client(prot)).recv_submitJob();\n }\n }\n\n public void sendFrontendMessage(String app, ch.epfl.eagle.thrift.TFullTaskId taskId, int status, ByteBuffer message, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {\n checkReady();\n sendFrontendMessage_call method_call = new sendFrontendMessage_call(app, taskId, status, message, resultHandler, this, ___protocolFactory, ___transport);\n this.___currentMethod = method_call;\n ___manager.call(method_call);\n }\n\n public static class sendFrontendMessage_call extends org.apache.thrift.async.TAsyncMethodCall {\n private String app;\n private ch.epfl.eagle.thrift.TFullTaskId taskId;\n private int status;\n private ByteBuffer message;\n public sendFrontendMessage_call(String app, ch.epfl.eagle.thrift.TFullTaskId taskId, int status, ByteBuffer message, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {\n super(client, protocolFactory, transport, resultHandler, false);\n this.app = app;\n this.taskId = taskId;\n this.status = status;\n this.message = message;\n }\n\n public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {\n prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage(\"sendFrontendMessage\", org.apache.thrift.protocol.TMessageType.CALL, 0));\n sendFrontendMessage_args args = new sendFrontendMessage_args();\n args.setApp(app);\n args.setTaskId(taskId);\n args.setStatus(status);\n args.setMessage(message);\n args.write(prot);\n prot.writeMessageEnd();\n }\n\n public void getResult() throws org.apache.thrift.TException {\n if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {\n throw new IllegalStateException(\"Method call not finished!\");\n }\n org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());\n org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);\n (new Client(prot)).recv_sendFrontendMessage();\n }\n }\n\n }\n\n public static class Processor<I extends Iface> extends org.apache.thrift.TBaseProcessor<I> implements org.apache.thrift.TProcessor {\n private static final Logger LOGGER = LoggerFactory.getLogger(Processor.class.getName());\n public Processor(I iface) {\n super(iface, getProcessMap(new HashMap<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>>()));\n }\n\n protected Processor(I iface, Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {\n super(iface, getProcessMap(processMap));\n }\n\n private static <I extends Iface> Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> getProcessMap(Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {\n processMap.put(\"registerFrontend\", new registerFrontend());\n processMap.put(\"submitJob\", new submitJob());\n processMap.put(\"sendFrontendMessage\", new sendFrontendMessage());\n return processMap;\n }\n\n public static class registerFrontend<I extends Iface> extends org.apache.thrift.ProcessFunction<I, registerFrontend_args> {\n public registerFrontend() {\n super(\"registerFrontend\");\n }\n\n public registerFrontend_args getEmptyArgsInstance() {\n return new registerFrontend_args();\n }\n\n protected boolean isOneway() {\n return false;\n }\n\n public registerFrontend_result getResult(I iface, registerFrontend_args args) throws org.apache.thrift.TException {\n registerFrontend_result result = new registerFrontend_result();\n result.success = iface.registerFrontend(args.app, args.socketAddress);\n result.setSuccessIsSet(true);\n return result;\n }\n }\n\n public static class submitJob<I extends Iface> extends org.apache.thrift.ProcessFunction<I, submitJob_args> {\n public submitJob() {\n super(\"submitJob\");\n }\n\n public submitJob_args getEmptyArgsInstance() {\n return new submitJob_args();\n }\n\n protected boolean isOneway() {\n return false;\n }\n\n public submitJob_result getResult(I iface, submitJob_args args) throws org.apache.thrift.TException {\n submitJob_result result = new submitJob_result();\n try {\n iface.submitJob(args.req);\n } catch (ch.epfl.eagle.thrift.IncompleteRequestException e) {\n result.e = e;\n }\n return result;\n }\n }\n\n public static class sendFrontendMessage<I extends Iface> extends org.apache.thrift.ProcessFunction<I, sendFrontendMessage_args> {\n public sendFrontendMessage() {\n super(\"sendFrontendMessage\");\n }\n\n public sendFrontendMessage_args getEmptyArgsInstance() {\n return new sendFrontendMessage_args();\n }\n\n protected boolean isOneway() {\n return false;\n }\n\n public sendFrontendMessage_result getResult(I iface, sendFrontendMessage_args args) throws org.apache.thrift.TException {\n sendFrontendMessage_result result = new sendFrontendMessage_result();\n iface.sendFrontendMessage(args.app, args.taskId, args.status, args.message);\n return result;\n }\n }\n\n }\n\n public static class AsyncProcessor<I extends AsyncIface> extends org.apache.thrift.TBaseAsyncProcessor<I> {\n private static final Logger LOGGER = LoggerFactory.getLogger(AsyncProcessor.class.getName());\n public AsyncProcessor(I iface) {\n super(iface, getProcessMap(new HashMap<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>>()));\n }\n\n protected AsyncProcessor(I iface, Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {\n super(iface, getProcessMap(processMap));\n }\n\n private static <I extends AsyncIface> Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase,?>> getProcessMap(Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {\n processMap.put(\"registerFrontend\", new registerFrontend());\n processMap.put(\"submitJob\", new submitJob());\n processMap.put(\"sendFrontendMessage\", new sendFrontendMessage());\n return processMap;\n }\n\n public static class registerFrontend<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, registerFrontend_args, Boolean> {\n public registerFrontend() {\n super(\"registerFrontend\");\n }\n\n public registerFrontend_args getEmptyArgsInstance() {\n return new registerFrontend_args();\n }\n\n public AsyncMethodCallback<Boolean> getResultHandler(final AsyncFrameBuffer fb, final int seqid) {\n final org.apache.thrift.AsyncProcessFunction fcall = this;\n return new AsyncMethodCallback<Boolean>() { \n public void onComplete(Boolean o) {\n registerFrontend_result result = new registerFrontend_result();\n result.success = o;\n result.setSuccessIsSet(true);\n try {\n fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);\n return;\n } catch (Exception e) {\n LOGGER.error(\"Exception writing to internal frame buffer\", e);\n }\n fb.close();\n }\n public void onError(Exception e) {\n byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;\n org.apache.thrift.TBase msg;\n registerFrontend_result result = new registerFrontend_result();\n {\n msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;\n msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());\n }\n try {\n fcall.sendResponse(fb,msg,msgType,seqid);\n return;\n } catch (Exception ex) {\n LOGGER.error(\"Exception writing to internal frame buffer\", ex);\n }\n fb.close();\n }\n };\n }\n\n protected boolean isOneway() {\n return false;\n }\n\n public void start(I iface, registerFrontend_args args, org.apache.thrift.async.AsyncMethodCallback<Boolean> resultHandler) throws TException {\n iface.registerFrontend(args.app, args.socketAddress,resultHandler);\n }\n }\n\n public static class submitJob<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, submitJob_args, Void> {\n public submitJob() {\n super(\"submitJob\");\n }\n\n public submitJob_args getEmptyArgsInstance() {\n return new submitJob_args();\n }\n\n public AsyncMethodCallback<Void> getResultHandler(final AsyncFrameBuffer fb, final int seqid) {\n final org.apache.thrift.AsyncProcessFunction fcall = this;\n return new AsyncMethodCallback<Void>() { \n public void onComplete(Void o) {\n submitJob_result result = new submitJob_result();\n try {\n fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);\n return;\n } catch (Exception e) {\n LOGGER.error(\"Exception writing to internal frame buffer\", e);\n }\n fb.close();\n }\n public void onError(Exception e) {\n byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;\n org.apache.thrift.TBase msg;\n submitJob_result result = new submitJob_result();\n if (e instanceof ch.epfl.eagle.thrift.IncompleteRequestException) {\n result.e = (ch.epfl.eagle.thrift.IncompleteRequestException) e;\n result.setEIsSet(true);\n msg = result;\n }\n else \n {\n msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;\n msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());\n }\n try {\n fcall.sendResponse(fb,msg,msgType,seqid);\n return;\n } catch (Exception ex) {\n LOGGER.error(\"Exception writing to internal frame buffer\", ex);\n }\n fb.close();\n }\n };\n }\n\n protected boolean isOneway() {\n return false;\n }\n\n public void start(I iface, submitJob_args args, org.apache.thrift.async.AsyncMethodCallback<Void> resultHandler) throws TException {\n iface.submitJob(args.req,resultHandler);\n }\n }\n\n public static class sendFrontendMessage<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, sendFrontendMessage_args, Void> {\n public sendFrontendMessage() {\n super(\"sendFrontendMessage\");\n }\n\n public sendFrontendMessage_args getEmptyArgsInstance() {\n return new sendFrontendMessage_args();\n }\n\n public AsyncMethodCallback<Void> getResultHandler(final AsyncFrameBuffer fb, final int seqid) {\n final org.apache.thrift.AsyncProcessFunction fcall = this;\n return new AsyncMethodCallback<Void>() { \n public void onComplete(Void o) {\n sendFrontendMessage_result result = new sendFrontendMessage_result();\n try {\n fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);\n return;\n } catch (Exception e) {\n LOGGER.error(\"Exception writing to internal frame buffer\", e);\n }\n fb.close();\n }\n public void onError(Exception e) {\n byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;\n org.apache.thrift.TBase msg;\n sendFrontendMessage_result result = new sendFrontendMessage_result();\n {\n msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;\n msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());\n }\n try {\n fcall.sendResponse(fb,msg,msgType,seqid);\n return;\n } catch (Exception ex) {\n LOGGER.error(\"Exception writing to internal frame buffer\", ex);\n }\n fb.close();\n }\n };\n }\n\n protected boolean isOneway() {\n return false;\n }\n\n public void start(I iface, sendFrontendMessage_args args, org.apache.thrift.async.AsyncMethodCallback<Void> resultHandler) throws TException {\n iface.sendFrontendMessage(args.app, args.taskId, args.status, args.message,resultHandler);\n }\n }\n\n }\n\n public static class registerFrontend_args implements org.apache.thrift.TBase<registerFrontend_args, registerFrontend_args._Fields>, java.io.Serializable, Cloneable, Comparable<registerFrontend_args> {\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"registerFrontend_args\");\n\n private static final org.apache.thrift.protocol.TField APP_FIELD_DESC = new org.apache.thrift.protocol.TField(\"app\", org.apache.thrift.protocol.TType.STRING, (short)1);\n private static final org.apache.thrift.protocol.TField SOCKET_ADDRESS_FIELD_DESC = new org.apache.thrift.protocol.TField(\"socketAddress\", org.apache.thrift.protocol.TType.STRING, (short)2);\n\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\n static {\n schemes.put(StandardScheme.class, new registerFrontend_argsStandardSchemeFactory());\n schemes.put(TupleScheme.class, new registerFrontend_argsTupleSchemeFactory());\n }\n\n public String app; // required\n public String socketAddress; // required\n\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\n APP((short)1, \"app\"),\n SOCKET_ADDRESS((short)2, \"socketAddress\");\n\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\n\n static {\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\n byName.put(field.getFieldName(), field);\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, or null if its not found.\n */\n public static _Fields findByThriftId(int fieldId) {\n switch(fieldId) {\n case 1: // APP\n return APP;\n case 2: // SOCKET_ADDRESS\n return SOCKET_ADDRESS;\n default:\n return null;\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, throwing an exception\n * if it is not found.\n */\n public static _Fields findByThriftIdOrThrow(int fieldId) {\n _Fields fields = findByThriftId(fieldId);\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\n return fields;\n }\n\n /**\n * Find the _Fields constant that matches name, or null if its not found.\n */\n public static _Fields findByName(String name) {\n return byName.get(name);\n }\n\n private final short _thriftId;\n private final String _fieldName;\n\n _Fields(short thriftId, String fieldName) {\n _thriftId = thriftId;\n _fieldName = fieldName;\n }\n\n public short getThriftFieldId() {\n return _thriftId;\n }\n\n public String getFieldName() {\n return _fieldName;\n }\n }\n\n // isset id assignments\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\n static {\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\n tmpMap.put(_Fields.APP, new org.apache.thrift.meta_data.FieldMetaData(\"app\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));\n tmpMap.put(_Fields.SOCKET_ADDRESS, new org.apache.thrift.meta_data.FieldMetaData(\"socketAddress\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));\n metaDataMap = Collections.unmodifiableMap(tmpMap);\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(registerFrontend_args.class, metaDataMap);\n }\n\n public registerFrontend_args() {\n }\n\n public registerFrontend_args(\n String app,\n String socketAddress)\n {\n this();\n this.app = app;\n this.socketAddress = socketAddress;\n }\n\n /**\n * Performs a deep copy on <i>other</i>.\n */\n public registerFrontend_args(registerFrontend_args other) {\n if (other.isSetApp()) {\n this.app = other.app;\n }\n if (other.isSetSocketAddress()) {\n this.socketAddress = other.socketAddress;\n }\n }\n\n public registerFrontend_args deepCopy() {\n return new registerFrontend_args(this);\n }\n\n @Override\n public void clear() {\n this.app = null;\n this.socketAddress = null;\n }\n\n public String getApp() {\n return this.app;\n }\n\n public registerFrontend_args setApp(String app) {\n this.app = app;\n return this;\n }\n\n public void unsetApp() {\n this.app = null;\n }\n\n /** Returns true if field app is set (has been assigned a value) and false otherwise */\n public boolean isSetApp() {\n return this.app != null;\n }\n\n public void setAppIsSet(boolean value) {\n if (!value) {\n this.app = null;\n }\n }\n\n public String getSocketAddress() {\n return this.socketAddress;\n }\n\n public registerFrontend_args setSocketAddress(String socketAddress) {\n this.socketAddress = socketAddress;\n return this;\n }\n\n public void unsetSocketAddress() {\n this.socketAddress = null;\n }\n\n /** Returns true if field socketAddress is set (has been assigned a value) and false otherwise */\n public boolean isSetSocketAddress() {\n return this.socketAddress != null;\n }\n\n public void setSocketAddressIsSet(boolean value) {\n if (!value) {\n this.socketAddress = null;\n }\n }\n\n public void setFieldValue(_Fields field, Object value) {\n switch (field) {\n case APP:\n if (value == null) {\n unsetApp();\n } else {\n setApp((String)value);\n }\n break;\n\n case SOCKET_ADDRESS:\n if (value == null) {\n unsetSocketAddress();\n } else {\n setSocketAddress((String)value);\n }\n break;\n\n }\n }\n\n public Object getFieldValue(_Fields field) {\n switch (field) {\n case APP:\n return getApp();\n\n case SOCKET_ADDRESS:\n return getSocketAddress();\n\n }\n throw new IllegalStateException();\n }\n\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\n public boolean isSet(_Fields field) {\n if (field == null) {\n throw new IllegalArgumentException();\n }\n\n switch (field) {\n case APP:\n return isSetApp();\n case SOCKET_ADDRESS:\n return isSetSocketAddress();\n }\n throw new IllegalStateException();\n }\n\n @Override\n public boolean equals(Object that) {\n if (that == null)\n return false;\n if (that instanceof registerFrontend_args)\n return this.equals((registerFrontend_args)that);\n return false;\n }\n\n public boolean equals(registerFrontend_args that) {\n if (that == null)\n return false;\n\n boolean this_present_app = true && this.isSetApp();\n boolean that_present_app = true && that.isSetApp();\n if (this_present_app || that_present_app) {\n if (!(this_present_app && that_present_app))\n return false;\n if (!this.app.equals(that.app))\n return false;\n }\n\n boolean this_present_socketAddress = true && this.isSetSocketAddress();\n boolean that_present_socketAddress = true && that.isSetSocketAddress();\n if (this_present_socketAddress || that_present_socketAddress) {\n if (!(this_present_socketAddress && that_present_socketAddress))\n return false;\n if (!this.socketAddress.equals(that.socketAddress))\n return false;\n }\n\n return true;\n }\n\n @Override\n public int hashCode() {\n List<Object> list = new ArrayList<Object>();\n\n boolean present_app = true && (isSetApp());\n list.add(present_app);\n if (present_app)\n list.add(app);\n\n boolean present_socketAddress = true && (isSetSocketAddress());\n list.add(present_socketAddress);\n if (present_socketAddress)\n list.add(socketAddress);\n\n return list.hashCode();\n }\n\n @Override\n public int compareTo(registerFrontend_args other) {\n if (!getClass().equals(other.getClass())) {\n return getClass().getName().compareTo(other.getClass().getName());\n }\n\n int lastComparison = 0;\n\n lastComparison = Boolean.valueOf(isSetApp()).compareTo(other.isSetApp());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetApp()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.app, other.app);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n lastComparison = Boolean.valueOf(isSetSocketAddress()).compareTo(other.isSetSocketAddress());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetSocketAddress()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.socketAddress, other.socketAddress);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n return 0;\n }\n\n public _Fields fieldForId(int fieldId) {\n return _Fields.findByThriftId(fieldId);\n }\n\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder(\"registerFrontend_args(\");\n boolean first = true;\n\n sb.append(\"app:\");\n if (this.app == null) {\n sb.append(\"null\");\n } else {\n sb.append(this.app);\n }\n first = false;\n if (!first) sb.append(\", \");\n sb.append(\"socketAddress:\");\n if (this.socketAddress == null) {\n sb.append(\"null\");\n } else {\n sb.append(this.socketAddress);\n }\n first = false;\n sb.append(\")\");\n return sb.toString();\n }\n\n public void validate() throws org.apache.thrift.TException {\n // check for required fields\n // check for sub-struct validity\n }\n\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\n try {\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\n try {\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private static class registerFrontend_argsStandardSchemeFactory implements SchemeFactory {\n public registerFrontend_argsStandardScheme getScheme() {\n return new registerFrontend_argsStandardScheme();\n }\n }\n\n private static class registerFrontend_argsStandardScheme extends StandardScheme<registerFrontend_args> {\n\n public void read(org.apache.thrift.protocol.TProtocol iprot, registerFrontend_args struct) throws org.apache.thrift.TException {\n org.apache.thrift.protocol.TField schemeField;\n iprot.readStructBegin();\n while (true)\n {\n schemeField = iprot.readFieldBegin();\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \n break;\n }\n switch (schemeField.id) {\n case 1: // APP\n if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {\n struct.app = iprot.readString();\n struct.setAppIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n case 2: // SOCKET_ADDRESS\n if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {\n struct.socketAddress = iprot.readString();\n struct.setSocketAddressIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n default:\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n iprot.readFieldEnd();\n }\n iprot.readStructEnd();\n\n // check for required fields of primitive type, which can't be checked in the validate method\n struct.validate();\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot, registerFrontend_args struct) throws org.apache.thrift.TException {\n struct.validate();\n\n oprot.writeStructBegin(STRUCT_DESC);\n if (struct.app != null) {\n oprot.writeFieldBegin(APP_FIELD_DESC);\n oprot.writeString(struct.app);\n oprot.writeFieldEnd();\n }\n if (struct.socketAddress != null) {\n oprot.writeFieldBegin(SOCKET_ADDRESS_FIELD_DESC);\n oprot.writeString(struct.socketAddress);\n oprot.writeFieldEnd();\n }\n oprot.writeFieldStop();\n oprot.writeStructEnd();\n }\n\n }\n\n private static class registerFrontend_argsTupleSchemeFactory implements SchemeFactory {\n public registerFrontend_argsTupleScheme getScheme() {\n return new registerFrontend_argsTupleScheme();\n }\n }\n\n private static class registerFrontend_argsTupleScheme extends TupleScheme<registerFrontend_args> {\n\n @Override\n public void write(org.apache.thrift.protocol.TProtocol prot, registerFrontend_args struct) throws org.apache.thrift.TException {\n TTupleProtocol oprot = (TTupleProtocol) prot;\n BitSet optionals = new BitSet();\n if (struct.isSetApp()) {\n optionals.set(0);\n }\n if (struct.isSetSocketAddress()) {\n optionals.set(1);\n }\n oprot.writeBitSet(optionals, 2);\n if (struct.isSetApp()) {\n oprot.writeString(struct.app);\n }\n if (struct.isSetSocketAddress()) {\n oprot.writeString(struct.socketAddress);\n }\n }\n\n @Override\n public void read(org.apache.thrift.protocol.TProtocol prot, registerFrontend_args struct) throws org.apache.thrift.TException {\n TTupleProtocol iprot = (TTupleProtocol) prot;\n BitSet incoming = iprot.readBitSet(2);\n if (incoming.get(0)) {\n struct.app = iprot.readString();\n struct.setAppIsSet(true);\n }\n if (incoming.get(1)) {\n struct.socketAddress = iprot.readString();\n struct.setSocketAddressIsSet(true);\n }\n }\n }\n\n }\n\n public static class registerFrontend_result implements org.apache.thrift.TBase<registerFrontend_result, registerFrontend_result._Fields>, java.io.Serializable, Cloneable, Comparable<registerFrontend_result> {\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"registerFrontend_result\");\n\n private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField(\"success\", org.apache.thrift.protocol.TType.BOOL, (short)0);\n\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\n static {\n schemes.put(StandardScheme.class, new registerFrontend_resultStandardSchemeFactory());\n schemes.put(TupleScheme.class, new registerFrontend_resultTupleSchemeFactory());\n }\n\n public boolean success; // required\n\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\n SUCCESS((short)0, \"success\");\n\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\n\n static {\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\n byName.put(field.getFieldName(), field);\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, or null if its not found.\n */\n public static _Fields findByThriftId(int fieldId) {\n switch(fieldId) {\n case 0: // SUCCESS\n return SUCCESS;\n default:\n return null;\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, throwing an exception\n * if it is not found.\n */\n public static _Fields findByThriftIdOrThrow(int fieldId) {\n _Fields fields = findByThriftId(fieldId);\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\n return fields;\n }\n\n /**\n * Find the _Fields constant that matches name, or null if its not found.\n */\n public static _Fields findByName(String name) {\n return byName.get(name);\n }\n\n private final short _thriftId;\n private final String _fieldName;\n\n _Fields(short thriftId, String fieldName) {\n _thriftId = thriftId;\n _fieldName = fieldName;\n }\n\n public short getThriftFieldId() {\n return _thriftId;\n }\n\n public String getFieldName() {\n return _fieldName;\n }\n }\n\n // isset id assignments\n private static final int __SUCCESS_ISSET_ID = 0;\n private byte __isset_bitfield = 0;\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\n static {\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\n tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData(\"success\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL)));\n metaDataMap = Collections.unmodifiableMap(tmpMap);\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(registerFrontend_result.class, metaDataMap);\n }\n\n public registerFrontend_result() {\n }\n\n public registerFrontend_result(\n boolean success)\n {\n this();\n this.success = success;\n setSuccessIsSet(true);\n }\n\n /**\n * Performs a deep copy on <i>other</i>.\n */\n public registerFrontend_result(registerFrontend_result other) {\n __isset_bitfield = other.__isset_bitfield;\n this.success = other.success;\n }\n\n public registerFrontend_result deepCopy() {\n return new registerFrontend_result(this);\n }\n\n @Override\n public void clear() {\n setSuccessIsSet(false);\n this.success = false;\n }\n\n public boolean isSuccess() {\n return this.success;\n }\n\n public registerFrontend_result setSuccess(boolean success) {\n this.success = success;\n setSuccessIsSet(true);\n return this;\n }\n\n public void unsetSuccess() {\n __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __SUCCESS_ISSET_ID);\n }\n\n /** Returns true if field success is set (has been assigned a value) and false otherwise */\n public boolean isSetSuccess() {\n return EncodingUtils.testBit(__isset_bitfield, __SUCCESS_ISSET_ID);\n }\n\n public void setSuccessIsSet(boolean value) {\n __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __SUCCESS_ISSET_ID, value);\n }\n\n public void setFieldValue(_Fields field, Object value) {\n switch (field) {\n case SUCCESS:\n if (value == null) {\n unsetSuccess();\n } else {\n setSuccess((Boolean)value);\n }\n break;\n\n }\n }\n\n public Object getFieldValue(_Fields field) {\n switch (field) {\n case SUCCESS:\n return isSuccess();\n\n }\n throw new IllegalStateException();\n }\n\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\n public boolean isSet(_Fields field) {\n if (field == null) {\n throw new IllegalArgumentException();\n }\n\n switch (field) {\n case SUCCESS:\n return isSetSuccess();\n }\n throw new IllegalStateException();\n }\n\n @Override\n public boolean equals(Object that) {\n if (that == null)\n return false;\n if (that instanceof registerFrontend_result)\n return this.equals((registerFrontend_result)that);\n return false;\n }\n\n public boolean equals(registerFrontend_result that) {\n if (that == null)\n return false;\n\n boolean this_present_success = true;\n boolean that_present_success = true;\n if (this_present_success || that_present_success) {\n if (!(this_present_success && that_present_success))\n return false;\n if (this.success != that.success)\n return false;\n }\n\n return true;\n }\n\n @Override\n public int hashCode() {\n List<Object> list = new ArrayList<Object>();\n\n boolean present_success = true;\n list.add(present_success);\n if (present_success)\n list.add(success);\n\n return list.hashCode();\n }\n\n @Override\n public int compareTo(registerFrontend_result other) {\n if (!getClass().equals(other.getClass())) {\n return getClass().getName().compareTo(other.getClass().getName());\n }\n\n int lastComparison = 0;\n\n lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetSuccess()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n return 0;\n }\n\n public _Fields fieldForId(int fieldId) {\n return _Fields.findByThriftId(fieldId);\n }\n\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder(\"registerFrontend_result(\");\n boolean first = true;\n\n sb.append(\"success:\");\n sb.append(this.success);\n first = false;\n sb.append(\")\");\n return sb.toString();\n }\n\n public void validate() throws org.apache.thrift.TException {\n // check for required fields\n // check for sub-struct validity\n }\n\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\n try {\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\n try {\n // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.\n __isset_bitfield = 0;\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private static class registerFrontend_resultStandardSchemeFactory implements SchemeFactory {\n public registerFrontend_resultStandardScheme getScheme() {\n return new registerFrontend_resultStandardScheme();\n }\n }\n\n private static class registerFrontend_resultStandardScheme extends StandardScheme<registerFrontend_result> {\n\n public void read(org.apache.thrift.protocol.TProtocol iprot, registerFrontend_result struct) throws org.apache.thrift.TException {\n org.apache.thrift.protocol.TField schemeField;\n iprot.readStructBegin();\n while (true)\n {\n schemeField = iprot.readFieldBegin();\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \n break;\n }\n switch (schemeField.id) {\n case 0: // SUCCESS\n if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) {\n struct.success = iprot.readBool();\n struct.setSuccessIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n default:\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n iprot.readFieldEnd();\n }\n iprot.readStructEnd();\n\n // check for required fields of primitive type, which can't be checked in the validate method\n struct.validate();\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot, registerFrontend_result struct) throws org.apache.thrift.TException {\n struct.validate();\n\n oprot.writeStructBegin(STRUCT_DESC);\n if (struct.isSetSuccess()) {\n oprot.writeFieldBegin(SUCCESS_FIELD_DESC);\n oprot.writeBool(struct.success);\n oprot.writeFieldEnd();\n }\n oprot.writeFieldStop();\n oprot.writeStructEnd();\n }\n\n }\n\n private static class registerFrontend_resultTupleSchemeFactory implements SchemeFactory {\n public registerFrontend_resultTupleScheme getScheme() {\n return new registerFrontend_resultTupleScheme();\n }\n }\n\n private static class registerFrontend_resultTupleScheme extends TupleScheme<registerFrontend_result> {\n\n @Override\n public void write(org.apache.thrift.protocol.TProtocol prot, registerFrontend_result struct) throws org.apache.thrift.TException {\n TTupleProtocol oprot = (TTupleProtocol) prot;\n BitSet optionals = new BitSet();\n if (struct.isSetSuccess()) {\n optionals.set(0);\n }\n oprot.writeBitSet(optionals, 1);\n if (struct.isSetSuccess()) {\n oprot.writeBool(struct.success);\n }\n }\n\n @Override\n public void read(org.apache.thrift.protocol.TProtocol prot, registerFrontend_result struct) throws org.apache.thrift.TException {\n TTupleProtocol iprot = (TTupleProtocol) prot;\n BitSet incoming = iprot.readBitSet(1);\n if (incoming.get(0)) {\n struct.success = iprot.readBool();\n struct.setSuccessIsSet(true);\n }\n }\n }\n\n }\n\n public static class submitJob_args implements org.apache.thrift.TBase<submitJob_args, submitJob_args._Fields>, java.io.Serializable, Cloneable, Comparable<submitJob_args> {\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"submitJob_args\");\n\n private static final org.apache.thrift.protocol.TField REQ_FIELD_DESC = new org.apache.thrift.protocol.TField(\"req\", org.apache.thrift.protocol.TType.STRUCT, (short)1);\n\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\n static {\n schemes.put(StandardScheme.class, new submitJob_argsStandardSchemeFactory());\n schemes.put(TupleScheme.class, new submitJob_argsTupleSchemeFactory());\n }\n\n public ch.epfl.eagle.thrift.TSchedulingRequest req; // required\n\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\n REQ((short)1, \"req\");\n\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\n\n static {\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\n byName.put(field.getFieldName(), field);\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, or null if its not found.\n */\n public static _Fields findByThriftId(int fieldId) {\n switch(fieldId) {\n case 1: // REQ\n return REQ;\n default:\n return null;\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, throwing an exception\n * if it is not found.\n */\n public static _Fields findByThriftIdOrThrow(int fieldId) {\n _Fields fields = findByThriftId(fieldId);\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\n return fields;\n }\n\n /**\n * Find the _Fields constant that matches name, or null if its not found.\n */\n public static _Fields findByName(String name) {\n return byName.get(name);\n }\n\n private final short _thriftId;\n private final String _fieldName;\n\n _Fields(short thriftId, String fieldName) {\n _thriftId = thriftId;\n _fieldName = fieldName;\n }\n\n public short getThriftFieldId() {\n return _thriftId;\n }\n\n public String getFieldName() {\n return _fieldName;\n }\n }\n\n // isset id assignments\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\n static {\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\n tmpMap.put(_Fields.REQ, new org.apache.thrift.meta_data.FieldMetaData(\"req\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, ch.epfl.eagle.thrift.TSchedulingRequest.class)));\n metaDataMap = Collections.unmodifiableMap(tmpMap);\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(submitJob_args.class, metaDataMap);\n }\n\n public submitJob_args() {\n }\n\n public submitJob_args(\n ch.epfl.eagle.thrift.TSchedulingRequest req)\n {\n this();\n this.req = req;\n }\n\n /**\n * Performs a deep copy on <i>other</i>.\n */\n public submitJob_args(submitJob_args other) {\n if (other.isSetReq()) {\n this.req = new ch.epfl.eagle.thrift.TSchedulingRequest(other.req);\n }\n }\n\n public submitJob_args deepCopy() {\n return new submitJob_args(this);\n }\n\n @Override\n public void clear() {\n this.req = null;\n }\n\n public ch.epfl.eagle.thrift.TSchedulingRequest getReq() {\n return this.req;\n }\n\n public submitJob_args setReq(ch.epfl.eagle.thrift.TSchedulingRequest req) {\n this.req = req;\n return this;\n }\n\n public void unsetReq() {\n this.req = null;\n }\n\n /** Returns true if field req is set (has been assigned a value) and false otherwise */\n public boolean isSetReq() {\n return this.req != null;\n }\n\n public void setReqIsSet(boolean value) {\n if (!value) {\n this.req = null;\n }\n }\n\n public void setFieldValue(_Fields field, Object value) {\n switch (field) {\n case REQ:\n if (value == null) {\n unsetReq();\n } else {\n setReq((ch.epfl.eagle.thrift.TSchedulingRequest)value);\n }\n break;\n\n }\n }\n\n public Object getFieldValue(_Fields field) {\n switch (field) {\n case REQ:\n return getReq();\n\n }\n throw new IllegalStateException();\n }\n\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\n public boolean isSet(_Fields field) {\n if (field == null) {\n throw new IllegalArgumentException();\n }\n\n switch (field) {\n case REQ:\n return isSetReq();\n }\n throw new IllegalStateException();\n }\n\n @Override\n public boolean equals(Object that) {\n if (that == null)\n return false;\n if (that instanceof submitJob_args)\n return this.equals((submitJob_args)that);\n return false;\n }\n\n public boolean equals(submitJob_args that) {\n if (that == null)\n return false;\n\n boolean this_present_req = true && this.isSetReq();\n boolean that_present_req = true && that.isSetReq();\n if (this_present_req || that_present_req) {\n if (!(this_present_req && that_present_req))\n return false;\n if (!this.req.equals(that.req))\n return false;\n }\n\n return true;\n }\n\n @Override\n public int hashCode() {\n List<Object> list = new ArrayList<Object>();\n\n boolean present_req = true && (isSetReq());\n list.add(present_req);\n if (present_req)\n list.add(req);\n\n return list.hashCode();\n }\n\n @Override\n public int compareTo(submitJob_args other) {\n if (!getClass().equals(other.getClass())) {\n return getClass().getName().compareTo(other.getClass().getName());\n }\n\n int lastComparison = 0;\n\n lastComparison = Boolean.valueOf(isSetReq()).compareTo(other.isSetReq());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetReq()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.req, other.req);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n return 0;\n }\n\n public _Fields fieldForId(int fieldId) {\n return _Fields.findByThriftId(fieldId);\n }\n\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder(\"submitJob_args(\");\n boolean first = true;\n\n sb.append(\"req:\");\n if (this.req == null) {\n sb.append(\"null\");\n } else {\n sb.append(this.req);\n }\n first = false;\n sb.append(\")\");\n return sb.toString();\n }\n\n public void validate() throws org.apache.thrift.TException {\n // check for required fields\n // check for sub-struct validity\n if (req != null) {\n req.validate();\n }\n }\n\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\n try {\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\n try {\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private static class submitJob_argsStandardSchemeFactory implements SchemeFactory {\n public submitJob_argsStandardScheme getScheme() {\n return new submitJob_argsStandardScheme();\n }\n }\n\n private static class submitJob_argsStandardScheme extends StandardScheme<submitJob_args> {\n\n public void read(org.apache.thrift.protocol.TProtocol iprot, submitJob_args struct) throws org.apache.thrift.TException {\n org.apache.thrift.protocol.TField schemeField;\n iprot.readStructBegin();\n while (true)\n {\n schemeField = iprot.readFieldBegin();\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \n break;\n }\n switch (schemeField.id) {\n case 1: // REQ\n if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) {\n struct.req = new ch.epfl.eagle.thrift.TSchedulingRequest();\n struct.req.read(iprot);\n struct.setReqIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n default:\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n iprot.readFieldEnd();\n }\n iprot.readStructEnd();\n\n // check for required fields of primitive type, which can't be checked in the validate method\n struct.validate();\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot, submitJob_args struct) throws org.apache.thrift.TException {\n struct.validate();\n\n oprot.writeStructBegin(STRUCT_DESC);\n if (struct.req != null) {\n oprot.writeFieldBegin(REQ_FIELD_DESC);\n struct.req.write(oprot);\n oprot.writeFieldEnd();\n }\n oprot.writeFieldStop();\n oprot.writeStructEnd();\n }\n\n }\n\n private static class submitJob_argsTupleSchemeFactory implements SchemeFactory {\n public submitJob_argsTupleScheme getScheme() {\n return new submitJob_argsTupleScheme();\n }\n }\n\n private static class submitJob_argsTupleScheme extends TupleScheme<submitJob_args> {\n\n @Override\n public void write(org.apache.thrift.protocol.TProtocol prot, submitJob_args struct) throws org.apache.thrift.TException {\n TTupleProtocol oprot = (TTupleProtocol) prot;\n BitSet optionals = new BitSet();\n if (struct.isSetReq()) {\n optionals.set(0);\n }\n oprot.writeBitSet(optionals, 1);\n if (struct.isSetReq()) {\n struct.req.write(oprot);\n }\n }\n\n @Override\n public void read(org.apache.thrift.protocol.TProtocol prot, submitJob_args struct) throws org.apache.thrift.TException {\n TTupleProtocol iprot = (TTupleProtocol) prot;\n BitSet incoming = iprot.readBitSet(1);\n if (incoming.get(0)) {\n struct.req = new ch.epfl.eagle.thrift.TSchedulingRequest();\n struct.req.read(iprot);\n struct.setReqIsSet(true);\n }\n }\n }\n\n }\n\n public static class submitJob_result implements org.apache.thrift.TBase<submitJob_result, submitJob_result._Fields>, java.io.Serializable, Cloneable, Comparable<submitJob_result> {\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"submitJob_result\");\n\n private static final org.apache.thrift.protocol.TField E_FIELD_DESC = new org.apache.thrift.protocol.TField(\"e\", org.apache.thrift.protocol.TType.STRUCT, (short)1);\n\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\n static {\n schemes.put(StandardScheme.class, new submitJob_resultStandardSchemeFactory());\n schemes.put(TupleScheme.class, new submitJob_resultTupleSchemeFactory());\n }\n\n public ch.epfl.eagle.thrift.IncompleteRequestException e; // required\n\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\n E((short)1, \"e\");\n\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\n\n static {\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\n byName.put(field.getFieldName(), field);\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, or null if its not found.\n */\n public static _Fields findByThriftId(int fieldId) {\n switch(fieldId) {\n case 1: // E\n return E;\n default:\n return null;\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, throwing an exception\n * if it is not found.\n */\n public static _Fields findByThriftIdOrThrow(int fieldId) {\n _Fields fields = findByThriftId(fieldId);\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\n return fields;\n }\n\n /**\n * Find the _Fields constant that matches name, or null if its not found.\n */\n public static _Fields findByName(String name) {\n return byName.get(name);\n }\n\n private final short _thriftId;\n private final String _fieldName;\n\n _Fields(short thriftId, String fieldName) {\n _thriftId = thriftId;\n _fieldName = fieldName;\n }\n\n public short getThriftFieldId() {\n return _thriftId;\n }\n\n public String getFieldName() {\n return _fieldName;\n }\n }\n\n // isset id assignments\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\n static {\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\n tmpMap.put(_Fields.E, new org.apache.thrift.meta_data.FieldMetaData(\"e\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT)));\n metaDataMap = Collections.unmodifiableMap(tmpMap);\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(submitJob_result.class, metaDataMap);\n }\n\n public submitJob_result() {\n }\n\n public submitJob_result(\n ch.epfl.eagle.thrift.IncompleteRequestException e)\n {\n this();\n this.e = e;\n }\n\n /**\n * Performs a deep copy on <i>other</i>.\n */\n public submitJob_result(submitJob_result other) {\n if (other.isSetE()) {\n this.e = new ch.epfl.eagle.thrift.IncompleteRequestException(other.e);\n }\n }\n\n public submitJob_result deepCopy() {\n return new submitJob_result(this);\n }\n\n @Override\n public void clear() {\n this.e = null;\n }\n\n public ch.epfl.eagle.thrift.IncompleteRequestException getE() {\n return this.e;\n }\n\n public submitJob_result setE(ch.epfl.eagle.thrift.IncompleteRequestException e) {\n this.e = e;\n return this;\n }\n\n public void unsetE() {\n this.e = null;\n }\n\n /** Returns true if field e is set (has been assigned a value) and false otherwise */\n public boolean isSetE() {\n return this.e != null;\n }\n\n public void setEIsSet(boolean value) {\n if (!value) {\n this.e = null;\n }\n }\n\n public void setFieldValue(_Fields field, Object value) {\n switch (field) {\n case E:\n if (value == null) {\n unsetE();\n } else {\n setE((ch.epfl.eagle.thrift.IncompleteRequestException)value);\n }\n break;\n\n }\n }\n\n public Object getFieldValue(_Fields field) {\n switch (field) {\n case E:\n return getE();\n\n }\n throw new IllegalStateException();\n }\n\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\n public boolean isSet(_Fields field) {\n if (field == null) {\n throw new IllegalArgumentException();\n }\n\n switch (field) {\n case E:\n return isSetE();\n }\n throw new IllegalStateException();\n }\n\n @Override\n public boolean equals(Object that) {\n if (that == null)\n return false;\n if (that instanceof submitJob_result)\n return this.equals((submitJob_result)that);\n return false;\n }\n\n public boolean equals(submitJob_result that) {\n if (that == null)\n return false;\n\n boolean this_present_e = true && this.isSetE();\n boolean that_present_e = true && that.isSetE();\n if (this_present_e || that_present_e) {\n if (!(this_present_e && that_present_e))\n return false;\n if (!this.e.equals(that.e))\n return false;\n }\n\n return true;\n }\n\n @Override\n public int hashCode() {\n List<Object> list = new ArrayList<Object>();\n\n boolean present_e = true && (isSetE());\n list.add(present_e);\n if (present_e)\n list.add(e);\n\n return list.hashCode();\n }\n\n @Override\n public int compareTo(submitJob_result other) {\n if (!getClass().equals(other.getClass())) {\n return getClass().getName().compareTo(other.getClass().getName());\n }\n\n int lastComparison = 0;\n\n lastComparison = Boolean.valueOf(isSetE()).compareTo(other.isSetE());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetE()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.e, other.e);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n return 0;\n }\n\n public _Fields fieldForId(int fieldId) {\n return _Fields.findByThriftId(fieldId);\n }\n\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder(\"submitJob_result(\");\n boolean first = true;\n\n sb.append(\"e:\");\n if (this.e == null) {\n sb.append(\"null\");\n } else {\n sb.append(this.e);\n }\n first = false;\n sb.append(\")\");\n return sb.toString();\n }\n\n public void validate() throws org.apache.thrift.TException {\n // check for required fields\n // check for sub-struct validity\n }\n\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\n try {\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\n try {\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private static class submitJob_resultStandardSchemeFactory implements SchemeFactory {\n public submitJob_resultStandardScheme getScheme() {\n return new submitJob_resultStandardScheme();\n }\n }\n\n private static class submitJob_resultStandardScheme extends StandardScheme<submitJob_result> {\n\n public void read(org.apache.thrift.protocol.TProtocol iprot, submitJob_result struct) throws org.apache.thrift.TException {\n org.apache.thrift.protocol.TField schemeField;\n iprot.readStructBegin();\n while (true)\n {\n schemeField = iprot.readFieldBegin();\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \n break;\n }\n switch (schemeField.id) {\n case 1: // E\n if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) {\n struct.e = new ch.epfl.eagle.thrift.IncompleteRequestException();\n struct.e.read(iprot);\n struct.setEIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n default:\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n iprot.readFieldEnd();\n }\n iprot.readStructEnd();\n\n // check for required fields of primitive type, which can't be checked in the validate method\n struct.validate();\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot, submitJob_result struct) throws org.apache.thrift.TException {\n struct.validate();\n\n oprot.writeStructBegin(STRUCT_DESC);\n if (struct.e != null) {\n oprot.writeFieldBegin(E_FIELD_DESC);\n struct.e.write(oprot);\n oprot.writeFieldEnd();\n }\n oprot.writeFieldStop();\n oprot.writeStructEnd();\n }\n\n }\n\n private static class submitJob_resultTupleSchemeFactory implements SchemeFactory {\n public submitJob_resultTupleScheme getScheme() {\n return new submitJob_resultTupleScheme();\n }\n }\n\n private static class submitJob_resultTupleScheme extends TupleScheme<submitJob_result> {\n\n @Override\n public void write(org.apache.thrift.protocol.TProtocol prot, submitJob_result struct) throws org.apache.thrift.TException {\n TTupleProtocol oprot = (TTupleProtocol) prot;\n BitSet optionals = new BitSet();\n if (struct.isSetE()) {\n optionals.set(0);\n }\n oprot.writeBitSet(optionals, 1);\n if (struct.isSetE()) {\n struct.e.write(oprot);\n }\n }\n\n @Override\n public void read(org.apache.thrift.protocol.TProtocol prot, submitJob_result struct) throws org.apache.thrift.TException {\n TTupleProtocol iprot = (TTupleProtocol) prot;\n BitSet incoming = iprot.readBitSet(1);\n if (incoming.get(0)) {\n struct.e = new ch.epfl.eagle.thrift.IncompleteRequestException();\n struct.e.read(iprot);\n struct.setEIsSet(true);\n }\n }\n }\n\n }\n\n public static class sendFrontendMessage_args implements org.apache.thrift.TBase<sendFrontendMessage_args, sendFrontendMessage_args._Fields>, java.io.Serializable, Cloneable, Comparable<sendFrontendMessage_args> {\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"sendFrontendMessage_args\");\n\n private static final org.apache.thrift.protocol.TField APP_FIELD_DESC = new org.apache.thrift.protocol.TField(\"app\", org.apache.thrift.protocol.TType.STRING, (short)1);\n private static final org.apache.thrift.protocol.TField TASK_ID_FIELD_DESC = new org.apache.thrift.protocol.TField(\"taskId\", org.apache.thrift.protocol.TType.STRUCT, (short)2);\n private static final org.apache.thrift.protocol.TField STATUS_FIELD_DESC = new org.apache.thrift.protocol.TField(\"status\", org.apache.thrift.protocol.TType.I32, (short)3);\n private static final org.apache.thrift.protocol.TField MESSAGE_FIELD_DESC = new org.apache.thrift.protocol.TField(\"message\", org.apache.thrift.protocol.TType.STRING, (short)4);\n\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\n static {\n schemes.put(StandardScheme.class, new sendFrontendMessage_argsStandardSchemeFactory());\n schemes.put(TupleScheme.class, new sendFrontendMessage_argsTupleSchemeFactory());\n }\n\n public String app; // required\n public ch.epfl.eagle.thrift.TFullTaskId taskId; // required\n public int status; // required\n public ByteBuffer message; // required\n\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\n APP((short)1, \"app\"),\n TASK_ID((short)2, \"taskId\"),\n STATUS((short)3, \"status\"),\n MESSAGE((short)4, \"message\");\n\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\n\n static {\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\n byName.put(field.getFieldName(), field);\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, or null if its not found.\n */\n public static _Fields findByThriftId(int fieldId) {\n switch(fieldId) {\n case 1: // APP\n return APP;\n case 2: // TASK_ID\n return TASK_ID;\n case 3: // STATUS\n return STATUS;\n case 4: // MESSAGE\n return MESSAGE;\n default:\n return null;\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, throwing an exception\n * if it is not found.\n */\n public static _Fields findByThriftIdOrThrow(int fieldId) {\n _Fields fields = findByThriftId(fieldId);\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\n return fields;\n }\n\n /**\n * Find the _Fields constant that matches name, or null if its not found.\n */\n public static _Fields findByName(String name) {\n return byName.get(name);\n }\n\n private final short _thriftId;\n private final String _fieldName;\n\n _Fields(short thriftId, String fieldName) {\n _thriftId = thriftId;\n _fieldName = fieldName;\n }\n\n public short getThriftFieldId() {\n return _thriftId;\n }\n\n public String getFieldName() {\n return _fieldName;\n }\n }\n\n // isset id assignments\n private static final int __STATUS_ISSET_ID = 0;\n private byte __isset_bitfield = 0;\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\n static {\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\n tmpMap.put(_Fields.APP, new org.apache.thrift.meta_data.FieldMetaData(\"app\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));\n tmpMap.put(_Fields.TASK_ID, new org.apache.thrift.meta_data.FieldMetaData(\"taskId\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, ch.epfl.eagle.thrift.TFullTaskId.class)));\n tmpMap.put(_Fields.STATUS, new org.apache.thrift.meta_data.FieldMetaData(\"status\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));\n tmpMap.put(_Fields.MESSAGE, new org.apache.thrift.meta_data.FieldMetaData(\"message\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING , true)));\n metaDataMap = Collections.unmodifiableMap(tmpMap);\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(sendFrontendMessage_args.class, metaDataMap);\n }\n\n public sendFrontendMessage_args() {\n }\n\n public sendFrontendMessage_args(\n String app,\n ch.epfl.eagle.thrift.TFullTaskId taskId,\n int status,\n ByteBuffer message)\n {\n this();\n this.app = app;\n this.taskId = taskId;\n this.status = status;\n setStatusIsSet(true);\n this.message = org.apache.thrift.TBaseHelper.copyBinary(message);\n }\n\n /**\n * Performs a deep copy on <i>other</i>.\n */\n public sendFrontendMessage_args(sendFrontendMessage_args other) {\n __isset_bitfield = other.__isset_bitfield;\n if (other.isSetApp()) {\n this.app = other.app;\n }\n if (other.isSetTaskId()) {\n this.taskId = new ch.epfl.eagle.thrift.TFullTaskId(other.taskId);\n }\n this.status = other.status;\n if (other.isSetMessage()) {\n this.message = org.apache.thrift.TBaseHelper.copyBinary(other.message);\n }\n }\n\n public sendFrontendMessage_args deepCopy() {\n return new sendFrontendMessage_args(this);\n }\n\n @Override\n public void clear() {\n this.app = null;\n this.taskId = null;\n setStatusIsSet(false);\n this.status = 0;\n this.message = null;\n }\n\n public String getApp() {\n return this.app;\n }\n\n public sendFrontendMessage_args setApp(String app) {\n this.app = app;\n return this;\n }\n\n public void unsetApp() {\n this.app = null;\n }\n\n /** Returns true if field app is set (has been assigned a value) and false otherwise */\n public boolean isSetApp() {\n return this.app != null;\n }\n\n public void setAppIsSet(boolean value) {\n if (!value) {\n this.app = null;\n }\n }\n\n public ch.epfl.eagle.thrift.TFullTaskId getTaskId() {\n return this.taskId;\n }\n\n public sendFrontendMessage_args setTaskId(ch.epfl.eagle.thrift.TFullTaskId taskId) {\n this.taskId = taskId;\n return this;\n }\n\n public void unsetTaskId() {\n this.taskId = null;\n }\n\n /** Returns true if field taskId is set (has been assigned a value) and false otherwise */\n public boolean isSetTaskId() {\n return this.taskId != null;\n }\n\n public void setTaskIdIsSet(boolean value) {\n if (!value) {\n this.taskId = null;\n }\n }\n\n public int getStatus() {\n return this.status;\n }\n\n public sendFrontendMessage_args setStatus(int status) {\n this.status = status;\n setStatusIsSet(true);\n return this;\n }\n\n public void unsetStatus() {\n __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __STATUS_ISSET_ID);\n }\n\n /** Returns true if field status is set (has been assigned a value) and false otherwise */\n public boolean isSetStatus() {\n return EncodingUtils.testBit(__isset_bitfield, __STATUS_ISSET_ID);\n }\n\n public void setStatusIsSet(boolean value) {\n __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __STATUS_ISSET_ID, value);\n }\n\n public byte[] getMessage() {\n setMessage(org.apache.thrift.TBaseHelper.rightSize(message));\n return message == null ? null : message.array();\n }\n\n public ByteBuffer bufferForMessage() {\n return org.apache.thrift.TBaseHelper.copyBinary(message);\n }\n\n public sendFrontendMessage_args setMessage(byte[] message) {\n this.message = message == null ? (ByteBuffer)null : ByteBuffer.wrap(Arrays.copyOf(message, message.length));\n return this;\n }\n\n public sendFrontendMessage_args setMessage(ByteBuffer message) {\n this.message = org.apache.thrift.TBaseHelper.copyBinary(message);\n return this;\n }\n\n public void unsetMessage() {\n this.message = null;\n }\n\n /** Returns true if field message is set (has been assigned a value) and false otherwise */\n public boolean isSetMessage() {\n return this.message != null;\n }\n\n public void setMessageIsSet(boolean value) {\n if (!value) {\n this.message = null;\n }\n }\n\n public void setFieldValue(_Fields field, Object value) {\n switch (field) {\n case APP:\n if (value == null) {\n unsetApp();\n } else {\n setApp((String)value);\n }\n break;\n\n case TASK_ID:\n if (value == null) {\n unsetTaskId();\n } else {\n setTaskId((ch.epfl.eagle.thrift.TFullTaskId)value);\n }\n break;\n\n case STATUS:\n if (value == null) {\n unsetStatus();\n } else {\n setStatus((Integer)value);\n }\n break;\n\n case MESSAGE:\n if (value == null) {\n unsetMessage();\n } else {\n setMessage((ByteBuffer)value);\n }\n break;\n\n }\n }\n\n public Object getFieldValue(_Fields field) {\n switch (field) {\n case APP:\n return getApp();\n\n case TASK_ID:\n return getTaskId();\n\n case STATUS:\n return getStatus();\n\n case MESSAGE:\n return getMessage();\n\n }\n throw new IllegalStateException();\n }\n\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\n public boolean isSet(_Fields field) {\n if (field == null) {\n throw new IllegalArgumentException();\n }\n\n switch (field) {\n case APP:\n return isSetApp();\n case TASK_ID:\n return isSetTaskId();\n case STATUS:\n return isSetStatus();\n case MESSAGE:\n return isSetMessage();\n }\n throw new IllegalStateException();\n }\n\n @Override\n public boolean equals(Object that) {\n if (that == null)\n return false;\n if (that instanceof sendFrontendMessage_args)\n return this.equals((sendFrontendMessage_args)that);\n return false;\n }\n\n public boolean equals(sendFrontendMessage_args that) {\n if (that == null)\n return false;\n\n boolean this_present_app = true && this.isSetApp();\n boolean that_present_app = true && that.isSetApp();\n if (this_present_app || that_present_app) {\n if (!(this_present_app && that_present_app))\n return false;\n if (!this.app.equals(that.app))\n return false;\n }\n\n boolean this_present_taskId = true && this.isSetTaskId();\n boolean that_present_taskId = true && that.isSetTaskId();\n if (this_present_taskId || that_present_taskId) {\n if (!(this_present_taskId && that_present_taskId))\n return false;\n if (!this.taskId.equals(that.taskId))\n return false;\n }\n\n boolean this_present_status = true;\n boolean that_present_status = true;\n if (this_present_status || that_present_status) {\n if (!(this_present_status && that_present_status))\n return false;\n if (this.status != that.status)\n return false;\n }\n\n boolean this_present_message = true && this.isSetMessage();\n boolean that_present_message = true && that.isSetMessage();\n if (this_present_message || that_present_message) {\n if (!(this_present_message && that_present_message))\n return false;\n if (!this.message.equals(that.message))\n return false;\n }\n\n return true;\n }\n\n @Override\n public int hashCode() {\n List<Object> list = new ArrayList<Object>();\n\n boolean present_app = true && (isSetApp());\n list.add(present_app);\n if (present_app)\n list.add(app);\n\n boolean present_taskId = true && (isSetTaskId());\n list.add(present_taskId);\n if (present_taskId)\n list.add(taskId);\n\n boolean present_status = true;\n list.add(present_status);\n if (present_status)\n list.add(status);\n\n boolean present_message = true && (isSetMessage());\n list.add(present_message);\n if (present_message)\n list.add(message);\n\n return list.hashCode();\n }\n\n @Override\n public int compareTo(sendFrontendMessage_args other) {\n if (!getClass().equals(other.getClass())) {\n return getClass().getName().compareTo(other.getClass().getName());\n }\n\n int lastComparison = 0;\n\n lastComparison = Boolean.valueOf(isSetApp()).compareTo(other.isSetApp());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetApp()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.app, other.app);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n lastComparison = Boolean.valueOf(isSetTaskId()).compareTo(other.isSetTaskId());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetTaskId()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.taskId, other.taskId);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n lastComparison = Boolean.valueOf(isSetStatus()).compareTo(other.isSetStatus());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetStatus()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.status, other.status);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n lastComparison = Boolean.valueOf(isSetMessage()).compareTo(other.isSetMessage());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetMessage()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.message, other.message);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n return 0;\n }\n\n public _Fields fieldForId(int fieldId) {\n return _Fields.findByThriftId(fieldId);\n }\n\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder(\"sendFrontendMessage_args(\");\n boolean first = true;\n\n sb.append(\"app:\");\n if (this.app == null) {\n sb.append(\"null\");\n } else {\n sb.append(this.app);\n }\n first = false;\n if (!first) sb.append(\", \");\n sb.append(\"taskId:\");\n if (this.taskId == null) {\n sb.append(\"null\");\n } else {\n sb.append(this.taskId);\n }\n first = false;\n if (!first) sb.append(\", \");\n sb.append(\"status:\");\n sb.append(this.status);\n first = false;\n if (!first) sb.append(\", \");\n sb.append(\"message:\");\n if (this.message == null) {\n sb.append(\"null\");\n } else {\n org.apache.thrift.TBaseHelper.toString(this.message, sb);\n }\n first = false;\n sb.append(\")\");\n return sb.toString();\n }\n\n public void validate() throws org.apache.thrift.TException {\n // check for required fields\n // check for sub-struct validity\n if (taskId != null) {\n taskId.validate();\n }\n }\n\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\n try {\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\n try {\n // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.\n __isset_bitfield = 0;\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private static class sendFrontendMessage_argsStandardSchemeFactory implements SchemeFactory {\n public sendFrontendMessage_argsStandardScheme getScheme() {\n return new sendFrontendMessage_argsStandardScheme();\n }\n }\n\n private static class sendFrontendMessage_argsStandardScheme extends StandardScheme<sendFrontendMessage_args> {\n\n public void read(org.apache.thrift.protocol.TProtocol iprot, sendFrontendMessage_args struct) throws org.apache.thrift.TException {\n org.apache.thrift.protocol.TField schemeField;\n iprot.readStructBegin();\n while (true)\n {\n schemeField = iprot.readFieldBegin();\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \n break;\n }\n switch (schemeField.id) {\n case 1: // APP\n if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {\n struct.app = iprot.readString();\n struct.setAppIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n case 2: // TASK_ID\n if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) {\n struct.taskId = new ch.epfl.eagle.thrift.TFullTaskId();\n struct.taskId.read(iprot);\n struct.setTaskIdIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n case 3: // STATUS\n if (schemeField.type == org.apache.thrift.protocol.TType.I32) {\n struct.status = iprot.readI32();\n struct.setStatusIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n case 4: // MESSAGE\n if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {\n struct.message = iprot.readBinary();\n struct.setMessageIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n default:\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n iprot.readFieldEnd();\n }\n iprot.readStructEnd();\n\n // check for required fields of primitive type, which can't be checked in the validate method\n struct.validate();\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot, sendFrontendMessage_args struct) throws org.apache.thrift.TException {\n struct.validate();\n\n oprot.writeStructBegin(STRUCT_DESC);\n if (struct.app != null) {\n oprot.writeFieldBegin(APP_FIELD_DESC);\n oprot.writeString(struct.app);\n oprot.writeFieldEnd();\n }\n if (struct.taskId != null) {\n oprot.writeFieldBegin(TASK_ID_FIELD_DESC);\n struct.taskId.write(oprot);\n oprot.writeFieldEnd();\n }\n oprot.writeFieldBegin(STATUS_FIELD_DESC);\n oprot.writeI32(struct.status);\n oprot.writeFieldEnd();\n if (struct.message != null) {\n oprot.writeFieldBegin(MESSAGE_FIELD_DESC);\n oprot.writeBinary(struct.message);\n oprot.writeFieldEnd();\n }\n oprot.writeFieldStop();\n oprot.writeStructEnd();\n }\n\n }\n\n private static class sendFrontendMessage_argsTupleSchemeFactory implements SchemeFactory {\n public sendFrontendMessage_argsTupleScheme getScheme() {\n return new sendFrontendMessage_argsTupleScheme();\n }\n }\n\n private static class sendFrontendMessage_argsTupleScheme extends TupleScheme<sendFrontendMessage_args> {\n\n @Override\n public void write(org.apache.thrift.protocol.TProtocol prot, sendFrontendMessage_args struct) throws org.apache.thrift.TException {\n TTupleProtocol oprot = (TTupleProtocol) prot;\n BitSet optionals = new BitSet();\n if (struct.isSetApp()) {\n optionals.set(0);\n }\n if (struct.isSetTaskId()) {\n optionals.set(1);\n }\n if (struct.isSetStatus()) {\n optionals.set(2);\n }\n if (struct.isSetMessage()) {\n optionals.set(3);\n }\n oprot.writeBitSet(optionals, 4);\n if (struct.isSetApp()) {\n oprot.writeString(struct.app);\n }\n if (struct.isSetTaskId()) {\n struct.taskId.write(oprot);\n }\n if (struct.isSetStatus()) {\n oprot.writeI32(struct.status);\n }\n if (struct.isSetMessage()) {\n oprot.writeBinary(struct.message);\n }\n }\n\n @Override\n public void read(org.apache.thrift.protocol.TProtocol prot, sendFrontendMessage_args struct) throws org.apache.thrift.TException {\n TTupleProtocol iprot = (TTupleProtocol) prot;\n BitSet incoming = iprot.readBitSet(4);\n if (incoming.get(0)) {\n struct.app = iprot.readString();\n struct.setAppIsSet(true);\n }\n if (incoming.get(1)) {\n struct.taskId = new ch.epfl.eagle.thrift.TFullTaskId();\n struct.taskId.read(iprot);\n struct.setTaskIdIsSet(true);\n }\n if (incoming.get(2)) {\n struct.status = iprot.readI32();\n struct.setStatusIsSet(true);\n }\n if (incoming.get(3)) {\n struct.message = iprot.readBinary();\n struct.setMessageIsSet(true);\n }\n }\n }\n\n }\n\n public static class sendFrontendMessage_result implements org.apache.thrift.TBase<sendFrontendMessage_result, sendFrontendMessage_result._Fields>, java.io.Serializable, Cloneable, Comparable<sendFrontendMessage_result> {\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"sendFrontendMessage_result\");\n\n\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\n static {\n schemes.put(StandardScheme.class, new sendFrontendMessage_resultStandardSchemeFactory());\n schemes.put(TupleScheme.class, new sendFrontendMessage_resultTupleSchemeFactory());\n }\n\n\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\n;\n\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\n\n static {\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\n byName.put(field.getFieldName(), field);\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, or null if its not found.\n */\n public static _Fields findByThriftId(int fieldId) {\n switch(fieldId) {\n default:\n return null;\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, throwing an exception\n * if it is not found.\n */\n public static _Fields findByThriftIdOrThrow(int fieldId) {\n _Fields fields = findByThriftId(fieldId);\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\n return fields;\n }\n\n /**\n * Find the _Fields constant that matches name, or null if its not found.\n */\n public static _Fields findByName(String name) {\n return byName.get(name);\n }\n\n private final short _thriftId;\n private final String _fieldName;\n\n _Fields(short thriftId, String fieldName) {\n _thriftId = thriftId;\n _fieldName = fieldName;\n }\n\n public short getThriftFieldId() {\n return _thriftId;\n }\n\n public String getFieldName() {\n return _fieldName;\n }\n }\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\n static {\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\n metaDataMap = Collections.unmodifiableMap(tmpMap);\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(sendFrontendMessage_result.class, metaDataMap);\n }\n\n public sendFrontendMessage_result() {\n }\n\n /**\n * Performs a deep copy on <i>other</i>.\n */\n public sendFrontendMessage_result(sendFrontendMessage_result other) {\n }\n\n public sendFrontendMessage_result deepCopy() {\n return new sendFrontendMessage_result(this);\n }\n\n @Override\n public void clear() {\n }\n\n public void setFieldValue(_Fields field, Object value) {\n switch (field) {\n }\n }\n\n public Object getFieldValue(_Fields field) {\n switch (field) {\n }\n throw new IllegalStateException();\n }\n\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\n public boolean isSet(_Fields field) {\n if (field == null) {\n throw new IllegalArgumentException();\n }\n\n switch (field) {\n }\n throw new IllegalStateException();\n }\n\n @Override\n public boolean equals(Object that) {\n if (that == null)\n return false;\n if (that instanceof sendFrontendMessage_result)\n return this.equals((sendFrontendMessage_result)that);\n return false;\n }\n\n public boolean equals(sendFrontendMessage_result that) {\n if (that == null)\n return false;\n\n return true;\n }\n\n @Override\n public int hashCode() {\n List<Object> list = new ArrayList<Object>();\n\n return list.hashCode();\n }\n\n @Override\n public int compareTo(sendFrontendMessage_result other) {\n if (!getClass().equals(other.getClass())) {\n return getClass().getName().compareTo(other.getClass().getName());\n }\n\n int lastComparison = 0;\n\n return 0;\n }\n\n public _Fields fieldForId(int fieldId) {\n return _Fields.findByThriftId(fieldId);\n }\n\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder(\"sendFrontendMessage_result(\");\n boolean first = true;\n\n sb.append(\")\");\n return sb.toString();\n }\n\n public void validate() throws org.apache.thrift.TException {\n // check for required fields\n // check for sub-struct validity\n }\n\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\n try {\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\n try {\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private static class sendFrontendMessage_resultStandardSchemeFactory implements SchemeFactory {\n public sendFrontendMessage_resultStandardScheme getScheme() {\n return new sendFrontendMessage_resultStandardScheme();\n }\n }\n\n private static class sendFrontendMessage_resultStandardScheme extends StandardScheme<sendFrontendMessage_result> {\n\n public void read(org.apache.thrift.protocol.TProtocol iprot, sendFrontendMessage_result struct) throws org.apache.thrift.TException {\n org.apache.thrift.protocol.TField schemeField;\n iprot.readStructBegin();\n while (true)\n {\n schemeField = iprot.readFieldBegin();\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \n break;\n }\n switch (schemeField.id) {\n default:\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n iprot.readFieldEnd();\n }\n iprot.readStructEnd();\n\n // check for required fields of primitive type, which can't be checked in the validate method\n struct.validate();\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot, sendFrontendMessage_result struct) throws org.apache.thrift.TException {\n struct.validate();\n\n oprot.writeStructBegin(STRUCT_DESC);\n oprot.writeFieldStop();\n oprot.writeStructEnd();\n }\n\n }\n\n private static class sendFrontendMessage_resultTupleSchemeFactory implements SchemeFactory {\n public sendFrontendMessage_resultTupleScheme getScheme() {\n return new sendFrontendMessage_resultTupleScheme();\n }\n }\n\n private static class sendFrontendMessage_resultTupleScheme extends TupleScheme<sendFrontendMessage_result> {\n\n @Override\n public void write(org.apache.thrift.protocol.TProtocol prot, sendFrontendMessage_result struct) throws org.apache.thrift.TException {\n TTupleProtocol oprot = (TTupleProtocol) prot;\n }\n\n @Override\n public void read(org.apache.thrift.protocol.TProtocol prot, sendFrontendMessage_result struct) throws org.apache.thrift.TException {\n TTupleProtocol iprot = (TTupleProtocol) prot;\n }\n }\n\n }\n\n}", "public static class Client extends org.apache.thrift.TServiceClient implements Iface {\n public static class Factory implements org.apache.thrift.TServiceClientFactory<Client> {\n public Factory() {}\n public Client getClient(org.apache.thrift.protocol.TProtocol prot) {\n return new Client(prot);\n }\n public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {\n return new Client(iprot, oprot);\n }\n }\n\n public Client(org.apache.thrift.protocol.TProtocol prot)\n {\n super(prot, prot);\n }\n\n public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {\n super(iprot, oprot);\n }\n\n public boolean registerFrontend(String app, String socketAddress) throws org.apache.thrift.TException\n {\n send_registerFrontend(app, socketAddress);\n return recv_registerFrontend();\n }\n\n public void send_registerFrontend(String app, String socketAddress) throws org.apache.thrift.TException\n {\n registerFrontend_args args = new registerFrontend_args();\n args.setApp(app);\n args.setSocketAddress(socketAddress);\n sendBase(\"registerFrontend\", args);\n }\n\n public boolean recv_registerFrontend() throws org.apache.thrift.TException\n {\n registerFrontend_result result = new registerFrontend_result();\n receiveBase(result, \"registerFrontend\");\n if (result.isSetSuccess()) {\n return result.success;\n }\n throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, \"registerFrontend failed: unknown result\");\n }\n\n public void submitJob(ch.epfl.eagle.thrift.TSchedulingRequest req) throws ch.epfl.eagle.thrift.IncompleteRequestException, org.apache.thrift.TException\n {\n send_submitJob(req);\n recv_submitJob();\n }\n\n public void send_submitJob(ch.epfl.eagle.thrift.TSchedulingRequest req) throws org.apache.thrift.TException\n {\n submitJob_args args = new submitJob_args();\n args.setReq(req);\n sendBase(\"submitJob\", args);\n }\n\n public void recv_submitJob() throws ch.epfl.eagle.thrift.IncompleteRequestException, org.apache.thrift.TException\n {\n submitJob_result result = new submitJob_result();\n receiveBase(result, \"submitJob\");\n if (result.e != null) {\n throw result.e;\n }\n return;\n }\n\n public void sendFrontendMessage(String app, ch.epfl.eagle.thrift.TFullTaskId taskId, int status, ByteBuffer message) throws org.apache.thrift.TException\n {\n send_sendFrontendMessage(app, taskId, status, message);\n recv_sendFrontendMessage();\n }\n\n public void send_sendFrontendMessage(String app, ch.epfl.eagle.thrift.TFullTaskId taskId, int status, ByteBuffer message) throws org.apache.thrift.TException\n {\n sendFrontendMessage_args args = new sendFrontendMessage_args();\n args.setApp(app);\n args.setTaskId(taskId);\n args.setStatus(status);\n args.setMessage(message);\n sendBase(\"sendFrontendMessage\", args);\n }\n\n public void recv_sendFrontendMessage() throws org.apache.thrift.TException\n {\n sendFrontendMessage_result result = new sendFrontendMessage_result();\n receiveBase(result, \"sendFrontendMessage\");\n return;\n }\n\n}", "@SuppressWarnings({\"cast\", \"rawtypes\", \"serial\", \"unchecked\"})\n@Generated(value = \"Autogenerated by Thrift Compiler (0.9.3)\", date = \"2016-03-03\")\npublic class TSchedulingRequest implements org.apache.thrift.TBase<TSchedulingRequest, TSchedulingRequest._Fields>, java.io.Serializable, Cloneable, Comparable<TSchedulingRequest> {\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"TSchedulingRequest\");\n\n private static final org.apache.thrift.protocol.TField APP_FIELD_DESC = new org.apache.thrift.protocol.TField(\"app\", org.apache.thrift.protocol.TType.STRING, (short)1);\n private static final org.apache.thrift.protocol.TField TASKS_FIELD_DESC = new org.apache.thrift.protocol.TField(\"tasks\", org.apache.thrift.protocol.TType.LIST, (short)2);\n private static final org.apache.thrift.protocol.TField SHORT_JOB_FIELD_DESC = new org.apache.thrift.protocol.TField(\"shortJob\", org.apache.thrift.protocol.TType.BOOL, (short)3);\n private static final org.apache.thrift.protocol.TField ESTIMATED_DURATION_FIELD_DESC = new org.apache.thrift.protocol.TField(\"estimatedDuration\", org.apache.thrift.protocol.TType.DOUBLE, (short)4);\n private static final org.apache.thrift.protocol.TField USER_FIELD_DESC = new org.apache.thrift.protocol.TField(\"user\", org.apache.thrift.protocol.TType.STRUCT, (short)5);\n private static final org.apache.thrift.protocol.TField DESCRIPTION_FIELD_DESC = new org.apache.thrift.protocol.TField(\"description\", org.apache.thrift.protocol.TType.STRING, (short)6);\n private static final org.apache.thrift.protocol.TField PROBE_RATIO_FIELD_DESC = new org.apache.thrift.protocol.TField(\"probeRatio\", org.apache.thrift.protocol.TType.DOUBLE, (short)7);\n\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\n static {\n schemes.put(StandardScheme.class, new TSchedulingRequestStandardSchemeFactory());\n schemes.put(TupleScheme.class, new TSchedulingRequestTupleSchemeFactory());\n }\n\n public String app; // required\n public List<TTaskSpec> tasks; // required\n public boolean shortJob; // required\n public double estimatedDuration; // required\n public TUserGroupInfo user; // required\n public String description; // optional\n public double probeRatio; // optional\n\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\n APP((short)1, \"app\"),\n TASKS((short)2, \"tasks\"),\n SHORT_JOB((short)3, \"shortJob\"),\n ESTIMATED_DURATION((short)4, \"estimatedDuration\"),\n USER((short)5, \"user\"),\n DESCRIPTION((short)6, \"description\"),\n PROBE_RATIO((short)7, \"probeRatio\");\n\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\n\n static {\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\n byName.put(field.getFieldName(), field);\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, or null if its not found.\n */\n public static _Fields findByThriftId(int fieldId) {\n switch(fieldId) {\n case 1: // APP\n return APP;\n case 2: // TASKS\n return TASKS;\n case 3: // SHORT_JOB\n return SHORT_JOB;\n case 4: // ESTIMATED_DURATION\n return ESTIMATED_DURATION;\n case 5: // USER\n return USER;\n case 6: // DESCRIPTION\n return DESCRIPTION;\n case 7: // PROBE_RATIO\n return PROBE_RATIO;\n default:\n return null;\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, throwing an exception\n * if it is not found.\n */\n public static _Fields findByThriftIdOrThrow(int fieldId) {\n _Fields fields = findByThriftId(fieldId);\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\n return fields;\n }\n\n /**\n * Find the _Fields constant that matches name, or null if its not found.\n */\n public static _Fields findByName(String name) {\n return byName.get(name);\n }\n\n private final short _thriftId;\n private final String _fieldName;\n\n _Fields(short thriftId, String fieldName) {\n _thriftId = thriftId;\n _fieldName = fieldName;\n }\n\n public short getThriftFieldId() {\n return _thriftId;\n }\n\n public String getFieldName() {\n return _fieldName;\n }\n }\n\n // isset id assignments\n private static final int __SHORTJOB_ISSET_ID = 0;\n private static final int __ESTIMATEDDURATION_ISSET_ID = 1;\n private static final int __PROBERATIO_ISSET_ID = 2;\n private byte __isset_bitfield = 0;\n private static final _Fields optionals[] = {_Fields.DESCRIPTION,_Fields.PROBE_RATIO};\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\n static {\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\n tmpMap.put(_Fields.APP, new org.apache.thrift.meta_data.FieldMetaData(\"app\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));\n tmpMap.put(_Fields.TASKS, new org.apache.thrift.meta_data.FieldMetaData(\"tasks\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST, \n new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, TTaskSpec.class))));\n tmpMap.put(_Fields.SHORT_JOB, new org.apache.thrift.meta_data.FieldMetaData(\"shortJob\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL)));\n tmpMap.put(_Fields.ESTIMATED_DURATION, new org.apache.thrift.meta_data.FieldMetaData(\"estimatedDuration\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.DOUBLE)));\n tmpMap.put(_Fields.USER, new org.apache.thrift.meta_data.FieldMetaData(\"user\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, TUserGroupInfo.class)));\n tmpMap.put(_Fields.DESCRIPTION, new org.apache.thrift.meta_data.FieldMetaData(\"description\", org.apache.thrift.TFieldRequirementType.OPTIONAL, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));\n tmpMap.put(_Fields.PROBE_RATIO, new org.apache.thrift.meta_data.FieldMetaData(\"probeRatio\", org.apache.thrift.TFieldRequirementType.OPTIONAL, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.DOUBLE)));\n metaDataMap = Collections.unmodifiableMap(tmpMap);\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(TSchedulingRequest.class, metaDataMap);\n }\n\n public TSchedulingRequest() {\n }\n\n public TSchedulingRequest(\n String app,\n List<TTaskSpec> tasks,\n boolean shortJob,\n double estimatedDuration,\n TUserGroupInfo user)\n {\n this();\n this.app = app;\n this.tasks = tasks;\n this.shortJob = shortJob;\n setShortJobIsSet(true);\n this.estimatedDuration = estimatedDuration;\n setEstimatedDurationIsSet(true);\n this.user = user;\n }\n\n /**\n * Performs a deep copy on <i>other</i>.\n */\n public TSchedulingRequest(TSchedulingRequest other) {\n __isset_bitfield = other.__isset_bitfield;\n if (other.isSetApp()) {\n this.app = other.app;\n }\n if (other.isSetTasks()) {\n List<TTaskSpec> __this__tasks = new ArrayList<TTaskSpec>(other.tasks.size());\n for (TTaskSpec other_element : other.tasks) {\n __this__tasks.add(new TTaskSpec(other_element));\n }\n this.tasks = __this__tasks;\n }\n this.shortJob = other.shortJob;\n this.estimatedDuration = other.estimatedDuration;\n if (other.isSetUser()) {\n this.user = new TUserGroupInfo(other.user);\n }\n if (other.isSetDescription()) {\n this.description = other.description;\n }\n this.probeRatio = other.probeRatio;\n }\n\n public TSchedulingRequest deepCopy() {\n return new TSchedulingRequest(this);\n }\n\n @Override\n public void clear() {\n this.app = null;\n this.tasks = null;\n setShortJobIsSet(false);\n this.shortJob = false;\n setEstimatedDurationIsSet(false);\n this.estimatedDuration = 0.0;\n this.user = null;\n this.description = null;\n setProbeRatioIsSet(false);\n this.probeRatio = 0.0;\n }\n\n public String getApp() {\n return this.app;\n }\n\n public TSchedulingRequest setApp(String app) {\n this.app = app;\n return this;\n }\n\n public void unsetApp() {\n this.app = null;\n }\n\n /** Returns true if field app is set (has been assigned a value) and false otherwise */\n public boolean isSetApp() {\n return this.app != null;\n }\n\n public void setAppIsSet(boolean value) {\n if (!value) {\n this.app = null;\n }\n }\n\n public int getTasksSize() {\n return (this.tasks == null) ? 0 : this.tasks.size();\n }\n\n public java.util.Iterator<TTaskSpec> getTasksIterator() {\n return (this.tasks == null) ? null : this.tasks.iterator();\n }\n\n public void addToTasks(TTaskSpec elem) {\n if (this.tasks == null) {\n this.tasks = new ArrayList<TTaskSpec>();\n }\n this.tasks.add(elem);\n }\n\n public List<TTaskSpec> getTasks() {\n return this.tasks;\n }\n\n public TSchedulingRequest setTasks(List<TTaskSpec> tasks) {\n this.tasks = tasks;\n return this;\n }\n\n public void unsetTasks() {\n this.tasks = null;\n }\n\n /** Returns true if field tasks is set (has been assigned a value) and false otherwise */\n public boolean isSetTasks() {\n return this.tasks != null;\n }\n\n public void setTasksIsSet(boolean value) {\n if (!value) {\n this.tasks = null;\n }\n }\n\n public boolean isShortJob() {\n return this.shortJob;\n }\n\n public TSchedulingRequest setShortJob(boolean shortJob) {\n this.shortJob = shortJob;\n setShortJobIsSet(true);\n return this;\n }\n\n public void unsetShortJob() {\n __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __SHORTJOB_ISSET_ID);\n }\n\n /** Returns true if field shortJob is set (has been assigned a value) and false otherwise */\n public boolean isSetShortJob() {\n return EncodingUtils.testBit(__isset_bitfield, __SHORTJOB_ISSET_ID);\n }\n\n public void setShortJobIsSet(boolean value) {\n __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __SHORTJOB_ISSET_ID, value);\n }\n\n public double getEstimatedDuration() {\n return this.estimatedDuration;\n }\n\n public TSchedulingRequest setEstimatedDuration(double estimatedDuration) {\n this.estimatedDuration = estimatedDuration;\n setEstimatedDurationIsSet(true);\n return this;\n }\n\n public void unsetEstimatedDuration() {\n __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __ESTIMATEDDURATION_ISSET_ID);\n }\n\n /** Returns true if field estimatedDuration is set (has been assigned a value) and false otherwise */\n public boolean isSetEstimatedDuration() {\n return EncodingUtils.testBit(__isset_bitfield, __ESTIMATEDDURATION_ISSET_ID);\n }\n\n public void setEstimatedDurationIsSet(boolean value) {\n __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __ESTIMATEDDURATION_ISSET_ID, value);\n }\n\n public TUserGroupInfo getUser() {\n return this.user;\n }\n\n public TSchedulingRequest setUser(TUserGroupInfo user) {\n this.user = user;\n return this;\n }\n\n public void unsetUser() {\n this.user = null;\n }\n\n /** Returns true if field user is set (has been assigned a value) and false otherwise */\n public boolean isSetUser() {\n return this.user != null;\n }\n\n public void setUserIsSet(boolean value) {\n if (!value) {\n this.user = null;\n }\n }\n\n public String getDescription() {\n return this.description;\n }\n\n public TSchedulingRequest setDescription(String description) {\n this.description = description;\n return this;\n }\n\n public void unsetDescription() {\n this.description = null;\n }\n\n /** Returns true if field description is set (has been assigned a value) and false otherwise */\n public boolean isSetDescription() {\n return this.description != null;\n }\n\n public void setDescriptionIsSet(boolean value) {\n if (!value) {\n this.description = null;\n }\n }\n\n public double getProbeRatio() {\n return this.probeRatio;\n }\n\n public TSchedulingRequest setProbeRatio(double probeRatio) {\n this.probeRatio = probeRatio;\n setProbeRatioIsSet(true);\n return this;\n }\n\n public void unsetProbeRatio() {\n __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __PROBERATIO_ISSET_ID);\n }\n\n /** Returns true if field probeRatio is set (has been assigned a value) and false otherwise */\n public boolean isSetProbeRatio() {\n return EncodingUtils.testBit(__isset_bitfield, __PROBERATIO_ISSET_ID);\n }\n\n public void setProbeRatioIsSet(boolean value) {\n __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __PROBERATIO_ISSET_ID, value);\n }\n\n public void setFieldValue(_Fields field, Object value) {\n switch (field) {\n case APP:\n if (value == null) {\n unsetApp();\n } else {\n setApp((String)value);\n }\n break;\n\n case TASKS:\n if (value == null) {\n unsetTasks();\n } else {\n setTasks((List<TTaskSpec>)value);\n }\n break;\n\n case SHORT_JOB:\n if (value == null) {\n unsetShortJob();\n } else {\n setShortJob((Boolean)value);\n }\n break;\n\n case ESTIMATED_DURATION:\n if (value == null) {\n unsetEstimatedDuration();\n } else {\n setEstimatedDuration((Double)value);\n }\n break;\n\n case USER:\n if (value == null) {\n unsetUser();\n } else {\n setUser((TUserGroupInfo)value);\n }\n break;\n\n case DESCRIPTION:\n if (value == null) {\n unsetDescription();\n } else {\n setDescription((String)value);\n }\n break;\n\n case PROBE_RATIO:\n if (value == null) {\n unsetProbeRatio();\n } else {\n setProbeRatio((Double)value);\n }\n break;\n\n }\n }\n\n public Object getFieldValue(_Fields field) {\n switch (field) {\n case APP:\n return getApp();\n\n case TASKS:\n return getTasks();\n\n case SHORT_JOB:\n return isShortJob();\n\n case ESTIMATED_DURATION:\n return getEstimatedDuration();\n\n case USER:\n return getUser();\n\n case DESCRIPTION:\n return getDescription();\n\n case PROBE_RATIO:\n return getProbeRatio();\n\n }\n throw new IllegalStateException();\n }\n\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\n public boolean isSet(_Fields field) {\n if (field == null) {\n throw new IllegalArgumentException();\n }\n\n switch (field) {\n case APP:\n return isSetApp();\n case TASKS:\n return isSetTasks();\n case SHORT_JOB:\n return isSetShortJob();\n case ESTIMATED_DURATION:\n return isSetEstimatedDuration();\n case USER:\n return isSetUser();\n case DESCRIPTION:\n return isSetDescription();\n case PROBE_RATIO:\n return isSetProbeRatio();\n }\n throw new IllegalStateException();\n }\n\n @Override\n public boolean equals(Object that) {\n if (that == null)\n return false;\n if (that instanceof TSchedulingRequest)\n return this.equals((TSchedulingRequest)that);\n return false;\n }\n\n public boolean equals(TSchedulingRequest that) {\n if (that == null)\n return false;\n\n boolean this_present_app = true && this.isSetApp();\n boolean that_present_app = true && that.isSetApp();\n if (this_present_app || that_present_app) {\n if (!(this_present_app && that_present_app))\n return false;\n if (!this.app.equals(that.app))\n return false;\n }\n\n boolean this_present_tasks = true && this.isSetTasks();\n boolean that_present_tasks = true && that.isSetTasks();\n if (this_present_tasks || that_present_tasks) {\n if (!(this_present_tasks && that_present_tasks))\n return false;\n if (!this.tasks.equals(that.tasks))\n return false;\n }\n\n boolean this_present_shortJob = true;\n boolean that_present_shortJob = true;\n if (this_present_shortJob || that_present_shortJob) {\n if (!(this_present_shortJob && that_present_shortJob))\n return false;\n if (this.shortJob != that.shortJob)\n return false;\n }\n\n boolean this_present_estimatedDuration = true;\n boolean that_present_estimatedDuration = true;\n if (this_present_estimatedDuration || that_present_estimatedDuration) {\n if (!(this_present_estimatedDuration && that_present_estimatedDuration))\n return false;\n if (this.estimatedDuration != that.estimatedDuration)\n return false;\n }\n\n boolean this_present_user = true && this.isSetUser();\n boolean that_present_user = true && that.isSetUser();\n if (this_present_user || that_present_user) {\n if (!(this_present_user && that_present_user))\n return false;\n if (!this.user.equals(that.user))\n return false;\n }\n\n boolean this_present_description = true && this.isSetDescription();\n boolean that_present_description = true && that.isSetDescription();\n if (this_present_description || that_present_description) {\n if (!(this_present_description && that_present_description))\n return false;\n if (!this.description.equals(that.description))\n return false;\n }\n\n boolean this_present_probeRatio = true && this.isSetProbeRatio();\n boolean that_present_probeRatio = true && that.isSetProbeRatio();\n if (this_present_probeRatio || that_present_probeRatio) {\n if (!(this_present_probeRatio && that_present_probeRatio))\n return false;\n if (this.probeRatio != that.probeRatio)\n return false;\n }\n\n return true;\n }\n\n @Override\n public int hashCode() {\n List<Object> list = new ArrayList<Object>();\n\n boolean present_app = true && (isSetApp());\n list.add(present_app);\n if (present_app)\n list.add(app);\n\n boolean present_tasks = true && (isSetTasks());\n list.add(present_tasks);\n if (present_tasks)\n list.add(tasks);\n\n boolean present_shortJob = true;\n list.add(present_shortJob);\n if (present_shortJob)\n list.add(shortJob);\n\n boolean present_estimatedDuration = true;\n list.add(present_estimatedDuration);\n if (present_estimatedDuration)\n list.add(estimatedDuration);\n\n boolean present_user = true && (isSetUser());\n list.add(present_user);\n if (present_user)\n list.add(user);\n\n boolean present_description = true && (isSetDescription());\n list.add(present_description);\n if (present_description)\n list.add(description);\n\n boolean present_probeRatio = true && (isSetProbeRatio());\n list.add(present_probeRatio);\n if (present_probeRatio)\n list.add(probeRatio);\n\n return list.hashCode();\n }\n\n @Override\n public int compareTo(TSchedulingRequest other) {\n if (!getClass().equals(other.getClass())) {\n return getClass().getName().compareTo(other.getClass().getName());\n }\n\n int lastComparison = 0;\n\n lastComparison = Boolean.valueOf(isSetApp()).compareTo(other.isSetApp());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetApp()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.app, other.app);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n lastComparison = Boolean.valueOf(isSetTasks()).compareTo(other.isSetTasks());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetTasks()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.tasks, other.tasks);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n lastComparison = Boolean.valueOf(isSetShortJob()).compareTo(other.isSetShortJob());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetShortJob()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.shortJob, other.shortJob);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n lastComparison = Boolean.valueOf(isSetEstimatedDuration()).compareTo(other.isSetEstimatedDuration());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetEstimatedDuration()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.estimatedDuration, other.estimatedDuration);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n lastComparison = Boolean.valueOf(isSetUser()).compareTo(other.isSetUser());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetUser()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.user, other.user);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n lastComparison = Boolean.valueOf(isSetDescription()).compareTo(other.isSetDescription());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetDescription()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.description, other.description);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n lastComparison = Boolean.valueOf(isSetProbeRatio()).compareTo(other.isSetProbeRatio());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetProbeRatio()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.probeRatio, other.probeRatio);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n return 0;\n }\n\n public _Fields fieldForId(int fieldId) {\n return _Fields.findByThriftId(fieldId);\n }\n\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder(\"TSchedulingRequest(\");\n boolean first = true;\n\n sb.append(\"app:\");\n if (this.app == null) {\n sb.append(\"null\");\n } else {\n sb.append(this.app);\n }\n first = false;\n if (!first) sb.append(\", \");\n sb.append(\"tasks:\");\n if (this.tasks == null) {\n sb.append(\"null\");\n } else {\n sb.append(this.tasks);\n }\n first = false;\n if (!first) sb.append(\", \");\n sb.append(\"shortJob:\");\n sb.append(this.shortJob);\n first = false;\n if (!first) sb.append(\", \");\n sb.append(\"estimatedDuration:\");\n sb.append(this.estimatedDuration);\n first = false;\n if (!first) sb.append(\", \");\n sb.append(\"user:\");\n if (this.user == null) {\n sb.append(\"null\");\n } else {\n sb.append(this.user);\n }\n first = false;\n if (isSetDescription()) {\n if (!first) sb.append(\", \");\n sb.append(\"description:\");\n if (this.description == null) {\n sb.append(\"null\");\n } else {\n sb.append(this.description);\n }\n first = false;\n }\n if (isSetProbeRatio()) {\n if (!first) sb.append(\", \");\n sb.append(\"probeRatio:\");\n sb.append(this.probeRatio);\n first = false;\n }\n sb.append(\")\");\n return sb.toString();\n }\n\n public void validate() throws org.apache.thrift.TException {\n // check for required fields\n // check for sub-struct validity\n if (user != null) {\n user.validate();\n }\n }\n\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\n try {\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\n try {\n // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.\n __isset_bitfield = 0;\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private static class TSchedulingRequestStandardSchemeFactory implements SchemeFactory {\n public TSchedulingRequestStandardScheme getScheme() {\n return new TSchedulingRequestStandardScheme();\n }\n }\n\n private static class TSchedulingRequestStandardScheme extends StandardScheme<TSchedulingRequest> {\n\n public void read(org.apache.thrift.protocol.TProtocol iprot, TSchedulingRequest struct) throws org.apache.thrift.TException {\n org.apache.thrift.protocol.TField schemeField;\n iprot.readStructBegin();\n while (true)\n {\n schemeField = iprot.readFieldBegin();\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \n break;\n }\n switch (schemeField.id) {\n case 1: // APP\n if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {\n struct.app = iprot.readString();\n struct.setAppIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n case 2: // TASKS\n if (schemeField.type == org.apache.thrift.protocol.TType.LIST) {\n {\n org.apache.thrift.protocol.TList _list16 = iprot.readListBegin();\n struct.tasks = new ArrayList<TTaskSpec>(_list16.size);\n TTaskSpec _elem17;\n for (int _i18 = 0; _i18 < _list16.size; ++_i18)\n {\n _elem17 = new TTaskSpec();\n _elem17.read(iprot);\n struct.tasks.add(_elem17);\n }\n iprot.readListEnd();\n }\n struct.setTasksIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n case 3: // SHORT_JOB\n if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) {\n struct.shortJob = iprot.readBool();\n struct.setShortJobIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n case 4: // ESTIMATED_DURATION\n if (schemeField.type == org.apache.thrift.protocol.TType.DOUBLE) {\n struct.estimatedDuration = iprot.readDouble();\n struct.setEstimatedDurationIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n case 5: // USER\n if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) {\n struct.user = new TUserGroupInfo();\n struct.user.read(iprot);\n struct.setUserIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n case 6: // DESCRIPTION\n if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {\n struct.description = iprot.readString();\n struct.setDescriptionIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n case 7: // PROBE_RATIO\n if (schemeField.type == org.apache.thrift.protocol.TType.DOUBLE) {\n struct.probeRatio = iprot.readDouble();\n struct.setProbeRatioIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n default:\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n iprot.readFieldEnd();\n }\n iprot.readStructEnd();\n\n // check for required fields of primitive type, which can't be checked in the validate method\n struct.validate();\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot, TSchedulingRequest struct) throws org.apache.thrift.TException {\n struct.validate();\n\n oprot.writeStructBegin(STRUCT_DESC);\n if (struct.app != null) {\n oprot.writeFieldBegin(APP_FIELD_DESC);\n oprot.writeString(struct.app);\n oprot.writeFieldEnd();\n }\n if (struct.tasks != null) {\n oprot.writeFieldBegin(TASKS_FIELD_DESC);\n {\n oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.tasks.size()));\n for (TTaskSpec _iter19 : struct.tasks)\n {\n _iter19.write(oprot);\n }\n oprot.writeListEnd();\n }\n oprot.writeFieldEnd();\n }\n oprot.writeFieldBegin(SHORT_JOB_FIELD_DESC);\n oprot.writeBool(struct.shortJob);\n oprot.writeFieldEnd();\n oprot.writeFieldBegin(ESTIMATED_DURATION_FIELD_DESC);\n oprot.writeDouble(struct.estimatedDuration);\n oprot.writeFieldEnd();\n if (struct.user != null) {\n oprot.writeFieldBegin(USER_FIELD_DESC);\n struct.user.write(oprot);\n oprot.writeFieldEnd();\n }\n if (struct.description != null) {\n if (struct.isSetDescription()) {\n oprot.writeFieldBegin(DESCRIPTION_FIELD_DESC);\n oprot.writeString(struct.description);\n oprot.writeFieldEnd();\n }\n }\n if (struct.isSetProbeRatio()) {\n oprot.writeFieldBegin(PROBE_RATIO_FIELD_DESC);\n oprot.writeDouble(struct.probeRatio);\n oprot.writeFieldEnd();\n }\n oprot.writeFieldStop();\n oprot.writeStructEnd();\n }\n\n }\n\n private static class TSchedulingRequestTupleSchemeFactory implements SchemeFactory {\n public TSchedulingRequestTupleScheme getScheme() {\n return new TSchedulingRequestTupleScheme();\n }\n }\n\n private static class TSchedulingRequestTupleScheme extends TupleScheme<TSchedulingRequest> {\n\n @Override\n public void write(org.apache.thrift.protocol.TProtocol prot, TSchedulingRequest struct) throws org.apache.thrift.TException {\n TTupleProtocol oprot = (TTupleProtocol) prot;\n BitSet optionals = new BitSet();\n if (struct.isSetApp()) {\n optionals.set(0);\n }\n if (struct.isSetTasks()) {\n optionals.set(1);\n }\n if (struct.isSetShortJob()) {\n optionals.set(2);\n }\n if (struct.isSetEstimatedDuration()) {\n optionals.set(3);\n }\n if (struct.isSetUser()) {\n optionals.set(4);\n }\n if (struct.isSetDescription()) {\n optionals.set(5);\n }\n if (struct.isSetProbeRatio()) {\n optionals.set(6);\n }\n oprot.writeBitSet(optionals, 7);\n if (struct.isSetApp()) {\n oprot.writeString(struct.app);\n }\n if (struct.isSetTasks()) {\n {\n oprot.writeI32(struct.tasks.size());\n for (TTaskSpec _iter20 : struct.tasks)\n {\n _iter20.write(oprot);\n }\n }\n }\n if (struct.isSetShortJob()) {\n oprot.writeBool(struct.shortJob);\n }\n if (struct.isSetEstimatedDuration()) {\n oprot.writeDouble(struct.estimatedDuration);\n }\n if (struct.isSetUser()) {\n struct.user.write(oprot);\n }\n if (struct.isSetDescription()) {\n oprot.writeString(struct.description);\n }\n if (struct.isSetProbeRatio()) {\n oprot.writeDouble(struct.probeRatio);\n }\n }\n\n @Override\n public void read(org.apache.thrift.protocol.TProtocol prot, TSchedulingRequest struct) throws org.apache.thrift.TException {\n TTupleProtocol iprot = (TTupleProtocol) prot;\n BitSet incoming = iprot.readBitSet(7);\n if (incoming.get(0)) {\n struct.app = iprot.readString();\n struct.setAppIsSet(true);\n }\n if (incoming.get(1)) {\n {\n org.apache.thrift.protocol.TList _list21 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, iprot.readI32());\n struct.tasks = new ArrayList<TTaskSpec>(_list21.size);\n TTaskSpec _elem22;\n for (int _i23 = 0; _i23 < _list21.size; ++_i23)\n {\n _elem22 = new TTaskSpec();\n _elem22.read(iprot);\n struct.tasks.add(_elem22);\n }\n }\n struct.setTasksIsSet(true);\n }\n if (incoming.get(2)) {\n struct.shortJob = iprot.readBool();\n struct.setShortJobIsSet(true);\n }\n if (incoming.get(3)) {\n struct.estimatedDuration = iprot.readDouble();\n struct.setEstimatedDurationIsSet(true);\n }\n if (incoming.get(4)) {\n struct.user = new TUserGroupInfo();\n struct.user.read(iprot);\n struct.setUserIsSet(true);\n }\n if (incoming.get(5)) {\n struct.description = iprot.readString();\n struct.setDescriptionIsSet(true);\n }\n if (incoming.get(6)) {\n struct.probeRatio = iprot.readDouble();\n struct.setProbeRatioIsSet(true);\n }\n }\n }\n\n}", "@SuppressWarnings({\"cast\", \"rawtypes\", \"serial\", \"unchecked\"})\n@Generated(value = \"Autogenerated by Thrift Compiler (0.9.3)\", date = \"2016-03-03\")\npublic class TUserGroupInfo implements org.apache.thrift.TBase<TUserGroupInfo, TUserGroupInfo._Fields>, java.io.Serializable, Cloneable, Comparable<TUserGroupInfo> {\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"TUserGroupInfo\");\n\n private static final org.apache.thrift.protocol.TField USER_FIELD_DESC = new org.apache.thrift.protocol.TField(\"user\", org.apache.thrift.protocol.TType.STRING, (short)1);\n private static final org.apache.thrift.protocol.TField GROUP_FIELD_DESC = new org.apache.thrift.protocol.TField(\"group\", org.apache.thrift.protocol.TType.STRING, (short)2);\n private static final org.apache.thrift.protocol.TField PRIORITY_FIELD_DESC = new org.apache.thrift.protocol.TField(\"priority\", org.apache.thrift.protocol.TType.I32, (short)3);\n\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\n static {\n schemes.put(StandardScheme.class, new TUserGroupInfoStandardSchemeFactory());\n schemes.put(TupleScheme.class, new TUserGroupInfoTupleSchemeFactory());\n }\n\n public String user; // required\n public String group; // required\n public int priority; // required\n\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\n USER((short)1, \"user\"),\n GROUP((short)2, \"group\"),\n PRIORITY((short)3, \"priority\");\n\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\n\n static {\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\n byName.put(field.getFieldName(), field);\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, or null if its not found.\n */\n public static _Fields findByThriftId(int fieldId) {\n switch(fieldId) {\n case 1: // USER\n return USER;\n case 2: // GROUP\n return GROUP;\n case 3: // PRIORITY\n return PRIORITY;\n default:\n return null;\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, throwing an exception\n * if it is not found.\n */\n public static _Fields findByThriftIdOrThrow(int fieldId) {\n _Fields fields = findByThriftId(fieldId);\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\n return fields;\n }\n\n /**\n * Find the _Fields constant that matches name, or null if its not found.\n */\n public static _Fields findByName(String name) {\n return byName.get(name);\n }\n\n private final short _thriftId;\n private final String _fieldName;\n\n _Fields(short thriftId, String fieldName) {\n _thriftId = thriftId;\n _fieldName = fieldName;\n }\n\n public short getThriftFieldId() {\n return _thriftId;\n }\n\n public String getFieldName() {\n return _fieldName;\n }\n }\n\n // isset id assignments\n private static final int __PRIORITY_ISSET_ID = 0;\n private byte __isset_bitfield = 0;\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\n static {\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\n tmpMap.put(_Fields.USER, new org.apache.thrift.meta_data.FieldMetaData(\"user\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));\n tmpMap.put(_Fields.GROUP, new org.apache.thrift.meta_data.FieldMetaData(\"group\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));\n tmpMap.put(_Fields.PRIORITY, new org.apache.thrift.meta_data.FieldMetaData(\"priority\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));\n metaDataMap = Collections.unmodifiableMap(tmpMap);\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(TUserGroupInfo.class, metaDataMap);\n }\n\n public TUserGroupInfo() {\n }\n\n public TUserGroupInfo(\n String user,\n String group,\n int priority)\n {\n this();\n this.user = user;\n this.group = group;\n this.priority = priority;\n setPriorityIsSet(true);\n }\n\n /**\n * Performs a deep copy on <i>other</i>.\n */\n public TUserGroupInfo(TUserGroupInfo other) {\n __isset_bitfield = other.__isset_bitfield;\n if (other.isSetUser()) {\n this.user = other.user;\n }\n if (other.isSetGroup()) {\n this.group = other.group;\n }\n this.priority = other.priority;\n }\n\n public TUserGroupInfo deepCopy() {\n return new TUserGroupInfo(this);\n }\n\n @Override\n public void clear() {\n this.user = null;\n this.group = null;\n setPriorityIsSet(false);\n this.priority = 0;\n }\n\n public String getUser() {\n return this.user;\n }\n\n public TUserGroupInfo setUser(String user) {\n this.user = user;\n return this;\n }\n\n public void unsetUser() {\n this.user = null;\n }\n\n /** Returns true if field user is set (has been assigned a value) and false otherwise */\n public boolean isSetUser() {\n return this.user != null;\n }\n\n public void setUserIsSet(boolean value) {\n if (!value) {\n this.user = null;\n }\n }\n\n public String getGroup() {\n return this.group;\n }\n\n public TUserGroupInfo setGroup(String group) {\n this.group = group;\n return this;\n }\n\n public void unsetGroup() {\n this.group = null;\n }\n\n /** Returns true if field group is set (has been assigned a value) and false otherwise */\n public boolean isSetGroup() {\n return this.group != null;\n }\n\n public void setGroupIsSet(boolean value) {\n if (!value) {\n this.group = null;\n }\n }\n\n public int getPriority() {\n return this.priority;\n }\n\n public TUserGroupInfo setPriority(int priority) {\n this.priority = priority;\n setPriorityIsSet(true);\n return this;\n }\n\n public void unsetPriority() {\n __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __PRIORITY_ISSET_ID);\n }\n\n /** Returns true if field priority is set (has been assigned a value) and false otherwise */\n public boolean isSetPriority() {\n return EncodingUtils.testBit(__isset_bitfield, __PRIORITY_ISSET_ID);\n }\n\n public void setPriorityIsSet(boolean value) {\n __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __PRIORITY_ISSET_ID, value);\n }\n\n public void setFieldValue(_Fields field, Object value) {\n switch (field) {\n case USER:\n if (value == null) {\n unsetUser();\n } else {\n setUser((String)value);\n }\n break;\n\n case GROUP:\n if (value == null) {\n unsetGroup();\n } else {\n setGroup((String)value);\n }\n break;\n\n case PRIORITY:\n if (value == null) {\n unsetPriority();\n } else {\n setPriority((Integer)value);\n }\n break;\n\n }\n }\n\n public Object getFieldValue(_Fields field) {\n switch (field) {\n case USER:\n return getUser();\n\n case GROUP:\n return getGroup();\n\n case PRIORITY:\n return getPriority();\n\n }\n throw new IllegalStateException();\n }\n\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\n public boolean isSet(_Fields field) {\n if (field == null) {\n throw new IllegalArgumentException();\n }\n\n switch (field) {\n case USER:\n return isSetUser();\n case GROUP:\n return isSetGroup();\n case PRIORITY:\n return isSetPriority();\n }\n throw new IllegalStateException();\n }\n\n @Override\n public boolean equals(Object that) {\n if (that == null)\n return false;\n if (that instanceof TUserGroupInfo)\n return this.equals((TUserGroupInfo)that);\n return false;\n }\n\n public boolean equals(TUserGroupInfo that) {\n if (that == null)\n return false;\n\n boolean this_present_user = true && this.isSetUser();\n boolean that_present_user = true && that.isSetUser();\n if (this_present_user || that_present_user) {\n if (!(this_present_user && that_present_user))\n return false;\n if (!this.user.equals(that.user))\n return false;\n }\n\n boolean this_present_group = true && this.isSetGroup();\n boolean that_present_group = true && that.isSetGroup();\n if (this_present_group || that_present_group) {\n if (!(this_present_group && that_present_group))\n return false;\n if (!this.group.equals(that.group))\n return false;\n }\n\n boolean this_present_priority = true;\n boolean that_present_priority = true;\n if (this_present_priority || that_present_priority) {\n if (!(this_present_priority && that_present_priority))\n return false;\n if (this.priority != that.priority)\n return false;\n }\n\n return true;\n }\n\n @Override\n public int hashCode() {\n List<Object> list = new ArrayList<Object>();\n\n boolean present_user = true && (isSetUser());\n list.add(present_user);\n if (present_user)\n list.add(user);\n\n boolean present_group = true && (isSetGroup());\n list.add(present_group);\n if (present_group)\n list.add(group);\n\n boolean present_priority = true;\n list.add(present_priority);\n if (present_priority)\n list.add(priority);\n\n return list.hashCode();\n }\n\n @Override\n public int compareTo(TUserGroupInfo other) {\n if (!getClass().equals(other.getClass())) {\n return getClass().getName().compareTo(other.getClass().getName());\n }\n\n int lastComparison = 0;\n\n lastComparison = Boolean.valueOf(isSetUser()).compareTo(other.isSetUser());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetUser()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.user, other.user);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n lastComparison = Boolean.valueOf(isSetGroup()).compareTo(other.isSetGroup());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetGroup()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.group, other.group);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n lastComparison = Boolean.valueOf(isSetPriority()).compareTo(other.isSetPriority());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetPriority()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.priority, other.priority);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n return 0;\n }\n\n public _Fields fieldForId(int fieldId) {\n return _Fields.findByThriftId(fieldId);\n }\n\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder(\"TUserGroupInfo(\");\n boolean first = true;\n\n sb.append(\"user:\");\n if (this.user == null) {\n sb.append(\"null\");\n } else {\n sb.append(this.user);\n }\n first = false;\n if (!first) sb.append(\", \");\n sb.append(\"group:\");\n if (this.group == null) {\n sb.append(\"null\");\n } else {\n sb.append(this.group);\n }\n first = false;\n if (!first) sb.append(\", \");\n sb.append(\"priority:\");\n sb.append(this.priority);\n first = false;\n sb.append(\")\");\n return sb.toString();\n }\n\n public void validate() throws org.apache.thrift.TException {\n // check for required fields\n // check for sub-struct validity\n }\n\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\n try {\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\n try {\n // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.\n __isset_bitfield = 0;\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private static class TUserGroupInfoStandardSchemeFactory implements SchemeFactory {\n public TUserGroupInfoStandardScheme getScheme() {\n return new TUserGroupInfoStandardScheme();\n }\n }\n\n private static class TUserGroupInfoStandardScheme extends StandardScheme<TUserGroupInfo> {\n\n public void read(org.apache.thrift.protocol.TProtocol iprot, TUserGroupInfo struct) throws org.apache.thrift.TException {\n org.apache.thrift.protocol.TField schemeField;\n iprot.readStructBegin();\n while (true)\n {\n schemeField = iprot.readFieldBegin();\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \n break;\n }\n switch (schemeField.id) {\n case 1: // USER\n if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {\n struct.user = iprot.readString();\n struct.setUserIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n case 2: // GROUP\n if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {\n struct.group = iprot.readString();\n struct.setGroupIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n case 3: // PRIORITY\n if (schemeField.type == org.apache.thrift.protocol.TType.I32) {\n struct.priority = iprot.readI32();\n struct.setPriorityIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n default:\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n iprot.readFieldEnd();\n }\n iprot.readStructEnd();\n\n // check for required fields of primitive type, which can't be checked in the validate method\n struct.validate();\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot, TUserGroupInfo struct) throws org.apache.thrift.TException {\n struct.validate();\n\n oprot.writeStructBegin(STRUCT_DESC);\n if (struct.user != null) {\n oprot.writeFieldBegin(USER_FIELD_DESC);\n oprot.writeString(struct.user);\n oprot.writeFieldEnd();\n }\n if (struct.group != null) {\n oprot.writeFieldBegin(GROUP_FIELD_DESC);\n oprot.writeString(struct.group);\n oprot.writeFieldEnd();\n }\n oprot.writeFieldBegin(PRIORITY_FIELD_DESC);\n oprot.writeI32(struct.priority);\n oprot.writeFieldEnd();\n oprot.writeFieldStop();\n oprot.writeStructEnd();\n }\n\n }\n\n private static class TUserGroupInfoTupleSchemeFactory implements SchemeFactory {\n public TUserGroupInfoTupleScheme getScheme() {\n return new TUserGroupInfoTupleScheme();\n }\n }\n\n private static class TUserGroupInfoTupleScheme extends TupleScheme<TUserGroupInfo> {\n\n @Override\n public void write(org.apache.thrift.protocol.TProtocol prot, TUserGroupInfo struct) throws org.apache.thrift.TException {\n TTupleProtocol oprot = (TTupleProtocol) prot;\n BitSet optionals = new BitSet();\n if (struct.isSetUser()) {\n optionals.set(0);\n }\n if (struct.isSetGroup()) {\n optionals.set(1);\n }\n if (struct.isSetPriority()) {\n optionals.set(2);\n }\n oprot.writeBitSet(optionals, 3);\n if (struct.isSetUser()) {\n oprot.writeString(struct.user);\n }\n if (struct.isSetGroup()) {\n oprot.writeString(struct.group);\n }\n if (struct.isSetPriority()) {\n oprot.writeI32(struct.priority);\n }\n }\n\n @Override\n public void read(org.apache.thrift.protocol.TProtocol prot, TUserGroupInfo struct) throws org.apache.thrift.TException {\n TTupleProtocol iprot = (TTupleProtocol) prot;\n BitSet incoming = iprot.readBitSet(3);\n if (incoming.get(0)) {\n struct.user = iprot.readString();\n struct.setUserIsSet(true);\n }\n if (incoming.get(1)) {\n struct.group = iprot.readString();\n struct.setGroupIsSet(true);\n }\n if (incoming.get(2)) {\n struct.priority = iprot.readI32();\n struct.setPriorityIsSet(true);\n }\n }\n }\n\n}" ]
import ch.epfl.eagle.daemon.util.Network; import ch.epfl.eagle.daemon.util.TClients; import ch.epfl.eagle.daemon.util.TServers; import ch.epfl.eagle.thrift.FrontendService; import ch.epfl.eagle.thrift.IncompleteRequestException; import ch.epfl.eagle.thrift.SchedulerService; import ch.epfl.eagle.thrift.SchedulerService.Client; import ch.epfl.eagle.thrift.TSchedulingRequest; import ch.epfl.eagle.thrift.TUserGroupInfo; import java.util.Random; import java.io.IOException; import java.net.InetSocketAddress; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.log4j.Logger; import org.apache.thrift.TException;
/* * EAGLE * * Copyright 2016 Operating Systems Laboratory EPFL * * Modified from Sparrow - University of California, Berkeley * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ch.epfl.eagle.api; //[[FLORIN /** * Java client to Eagle scheduling service. Once a client is initialize()'d it * can be used safely from multiple threads. */ public class EagleFrontendClient { public static boolean launchedServerAlready = false; private final static Logger LOG = Logger.getLogger(EagleFrontendClient.class); private final static int NUM_CLIENTS = 8; // Number of concurrent requests we support //[[FLORIN private final static int DEFAULT_LISTEN_PORT = new Random().nextInt(30000)+20000; BlockingQueue<SchedulerService.Client> clients = new LinkedBlockingQueue<SchedulerService.Client>(); /** * Initialize a connection to an eagle scheduler. * @param eagleSchedulerAddr. The socket address of the Eagle scheduler. * @param app. The application id. Note that this must be consistent across frontends * and backends. * @param frontendServer. A class which implements the frontend server interface (for * communication from Eagle). * @throws IOException */ public void initialize(InetSocketAddress eagleSchedulerAddr, String app, FrontendService.Iface frontendServer) throws TException, IOException { LOG.info("EagleFrontendClient using port: "+DEFAULT_LISTEN_PORT); initialize(eagleSchedulerAddr, app, frontendServer, DEFAULT_LISTEN_PORT); } /** * Initialize a connection to an eagle scheduler. * @param eagleSchedulerAddr. The socket address of the Eagle scheduler. * @param app. The application id. Note that this must be consistent across frontends * and backends. * @param frontendServer. A class which implements the frontend server interface (for * communication from Eagle). * @param listenPort. The port on which to listen for request from the scheduler. * @throws IOException */ public void initialize(InetSocketAddress eagleSchedulerAddr, String app, FrontendService.Iface frontendServer, int listenPort) throws TException, IOException { FrontendService.Processor<FrontendService.Iface> processor = new FrontendService.Processor<FrontendService.Iface>(frontendServer); if (!launchedServerAlready) { try { TServers.launchThreadedThriftServer(listenPort, 8, processor); } catch (IOException e) { LOG.fatal("Couldn't launch server side of frontend", e); } launchedServerAlready = true; } for (int i = 0; i < NUM_CLIENTS; i++) { Client client = TClients.createBlockingSchedulerClient( eagleSchedulerAddr.getAddress().getHostAddress(), eagleSchedulerAddr.getPort(), 60000); clients.add(client); }
clients.peek().registerFrontend(app, Network.getIPAddress(new PropertiesConfiguration())
0
cjstehno/ersatz
ersatz/src/test/java/io/github/cjstehno/ersatz/impl/RequestMatcherTest.java
[ "public enum HttpMethod {\r\n\r\n /**\r\n * Wildcard matching any HTTP method.\r\n */\r\n ANY(\"*\"),\r\n\r\n /**\r\n * HTTP GET method matcher.\r\n */\r\n GET(\"GET\"),\r\n\r\n /**\r\n * HTTP HEAD method matcher.\r\n */\r\n HEAD(\"HEAD\"),\r\n\r\n /**\r\n * HTTP POST method matcher.\r\n */\r\n POST(\"POST\"),\r\n\r\n /**\r\n * HTTP PUT method matcher.\r\n */\r\n PUT(\"PUT\"),\r\n\r\n /**\r\n * HTTP DELETE method matcher.\r\n */\r\n DELETE(\"DELETE\"),\r\n\r\n /**\r\n * HTTP PATCH method matcher.\r\n */\r\n PATCH(\"PATCH\"),\r\n\r\n /**\r\n * HTTP OPTIONS method matcher.\r\n */\r\n OPTIONS(\"OPTIONS\"),\r\n\r\n /**\r\n * HTTP TRACE method matcher.\r\n */\r\n TRACE(\"TRACE\");\r\n\r\n private final String value;\r\n\r\n HttpMethod(final String value) {\r\n this.value = value;\r\n }\r\n\r\n /**\r\n * Retrieve the text value for the method.\r\n *\r\n * @return the method label.\r\n */\r\n public String getValue() {\r\n return value;\r\n }\r\n\r\n @Override public String toString() {\r\n return value;\r\n }\r\n}", "public class DecoderChain extends FunctionChain<RequestDecoders> {\r\n\r\n /**\r\n * Creates a chain of decoders with the given initial item.\r\n *\r\n * @param firstItem the first decoders in the chain\r\n */\r\n public DecoderChain(final RequestDecoders firstItem) {\r\n super(firstItem);\r\n }\r\n\r\n /**\r\n * Resolves the decoder for the specified request content-type.\r\n *\r\n * @param contentType the request content-type\r\n * @return the decoder function\r\n */\r\n public BiFunction<byte[], DecodingContext, Object> resolve(final String contentType) {\r\n return resolveWith(d -> d.findDecoder(contentType));\r\n }\r\n\r\n /**\r\n * Resolves the decoder for the specified request content-type.\r\n *\r\n * @param contentType the request content-type\r\n * @return the decoder function\r\n */\r\n public BiFunction<byte[], DecodingContext, Object> resolve(final ContentType contentType) {\r\n return resolve(contentType.getValue());\r\n }\r\n}\r", "public interface Decoders {\r\n\r\n /**\r\n * Decoder that simply passes the content bytes through as an array of bytes.\r\n */\r\n BiFunction<byte[], DecodingContext, Object> passthrough = (content, ctx) -> content;\r\n\r\n /**\r\n * Decoder that converts request content bytes into a UTF-8 string.\r\n */\r\n BiFunction<byte[], DecodingContext, Object> utf8String = string(UTF_8);\r\n\r\n /**\r\n * Decoder that converts request content bytes into a UTF-8 string.\r\n *\r\n * @return the decoded bytes as a string\r\n */\r\n static BiFunction<byte[], DecodingContext, Object> string() {\r\n return string(UTF_8);\r\n }\r\n\r\n /**\r\n * Decoder that converts request content bytes into a string of the specified charset.\r\n *\r\n * @param charset the name of the charset\r\n * @return the decoded bytes as a string\r\n */\r\n static BiFunction<byte[], DecodingContext, Object> string(final String charset) {\r\n return string(Charset.forName(charset));\r\n }\r\n\r\n /**\r\n * Decoder that converts request content bytes into a string of the specified charset.\r\n *\r\n * @param charset the charset to be used\r\n * @return the decoded bytes as a string\r\n */\r\n static BiFunction<byte[], DecodingContext, Object> string(final Charset charset) {\r\n return (content, ctx) -> content != null ? new String(content, charset) : \"\";\r\n }\r\n\r\n /**\r\n * Decoder that converts request content bytes in a url-encoded format into a map of name/value pairs.\r\n */\r\n BiFunction<byte[], DecodingContext, Object> urlEncoded = (content, ctx) -> {\r\n val map = new HashMap<String, String>();\r\n\r\n if (content != null) {\r\n for (val nvp : new String(content, UTF_8).split(\"&\")) {\r\n val parts = nvp.split(\"=\");\r\n try {\r\n if (parts.length == 2) {\r\n map.put(decode(parts[0], UTF_8.name()), decode(parts[1], UTF_8.name()));\r\n }\r\n } catch (Exception e) {\r\n throw new IllegalArgumentException(e.getMessage());\r\n }\r\n }\r\n }\r\n\r\n return map;\r\n };\r\n\r\n /**\r\n * Decoder that converts request content bytes into a <code>MultipartRequestContent</code> object populated with the multipart request content.\r\n */\r\n BiFunction<byte[], DecodingContext, Object> multipart = (content, ctx) -> {\r\n List<FileItem> parts;\r\n try {\r\n val tempDir = Files.createTempDirectory(\"ersatz-multipart-\").toFile();\r\n parts = new FileUpload(new DiskFileItemFactory(10_000, tempDir)).parseRequest(new UploadContext() {\r\n @Override\r\n public long contentLength() {\r\n return ctx.getContentLength();\r\n }\r\n\r\n @Override\r\n public String getCharacterEncoding() {\r\n return ctx.getCharacterEncoding();\r\n }\r\n\r\n @Override\r\n public String getContentType() {\r\n return ctx.getContentType();\r\n }\r\n\r\n @Override\r\n public int getContentLength() {\r\n return (int) ctx.getContentLength();\r\n }\r\n\r\n @Override\r\n public InputStream getInputStream() throws IOException {\r\n return new ByteArrayInputStream(content);\r\n }\r\n });\r\n } catch (final Exception e) {\r\n throw new IllegalArgumentException(e.getMessage());\r\n }\r\n\r\n val multipartRequest = new MultipartRequestContent();\r\n\r\n parts.forEach(part -> {\r\n val partCtx = new DecodingContext(part.getSize(), part.getContentType(), null, ctx.getDecoderChain());\r\n\r\n if (part.isFormField()) {\r\n multipartRequest.part(part.getFieldName(), TEXT_PLAIN, ctx.getDecoderChain().resolve(TEXT_PLAIN).apply(part.get(), partCtx));\r\n } else {\r\n multipartRequest.part(\r\n part.getFieldName(),\r\n part.getName(),\r\n part.getContentType(),\r\n ctx.getDecoderChain().resolve(part.getContentType()).apply(part.get(), partCtx)\r\n );\r\n }\r\n });\r\n\r\n return multipartRequest;\r\n };\r\n}\r", "public class RequestDecoders {\r\n\r\n private final List<DecoderMapping> decoders = new LinkedList<>();\r\n\r\n /**\r\n * Creates a new request decoder container based on the configuration consumer.\r\n *\r\n * @param consumer the decoder configuration consumer\r\n * @return the configured decoders\r\n */\r\n public static RequestDecoders decoders(final Consumer<RequestDecoders> consumer) {\r\n final var decoders = new RequestDecoders();\r\n consumer.accept(decoders);\r\n return decoders;\r\n }\r\n\r\n /**\r\n * Registers the decoder function with the collection\r\n *\r\n * @param contentType the content type\r\n * @param decoder the decoder function\r\n */\r\n public void register(final ContentType contentType, final BiFunction<byte[], DecodingContext, Object> decoder) {\r\n register(contentType.getValue(), decoder);\r\n }\r\n\r\n /**\r\n * Registers the decoder function with the collection\r\n *\r\n * @param contentType the content type\r\n * @param decoder the decoder function\r\n */\r\n public void register(final String contentType, final BiFunction<byte[], DecodingContext, Object> decoder) {\r\n decoders.stream()\r\n .filter(m -> m.mimeType.toString().equals(contentType))\r\n .findFirst()\r\n .ifPresent(decoders::remove);\r\n\r\n decoders.add(new DecoderMapping(createMimeType(contentType), decoder));\r\n }\r\n\r\n /**\r\n * Finds a decoder for the specified content type.\r\n *\r\n * @param contentType the content type\r\n * @return the decoder function\r\n */\r\n public BiFunction<byte[], DecodingContext, Object> findDecoder(final ContentType contentType) {\r\n return findDecoder(contentType.getValue());\r\n }\r\n\r\n /**\r\n * Finds a decoder for the specified content type.\r\n *\r\n * @param contentType the content type\r\n * @return the decoder function\r\n */\r\n public BiFunction<byte[], DecodingContext, Object> findDecoder(final String contentType) {\r\n final MimeType mimeType = createMimeType(contentType);\r\n\r\n final List<DecoderMapping> found = decoders.stream()\r\n .filter(c -> c.mimeType.match(mimeType))\r\n .collect(Collectors.toList());\r\n\r\n if (found.isEmpty()) {\r\n return null;\r\n\r\n } else if (found.size() > 1) {\r\n return found.stream()\r\n .filter(f -> f.mimeType.toString().equals(contentType))\r\n .findFirst()\r\n .map(m -> m.decoder)\r\n .orElse(null);\r\n\r\n } else {\r\n return found.get(0).decoder;\r\n }\r\n }\r\n\r\n private static class DecoderMapping {\r\n\r\n final MimeType mimeType;\r\n final BiFunction<byte[], DecodingContext, Object> decoder;\r\n\r\n DecoderMapping(MimeType mimeType, BiFunction<byte[], DecodingContext, Object> decoder) {\r\n this.mimeType = mimeType;\r\n this.decoder = decoder;\r\n }\r\n }\r\n}", "public class CookieMatcher extends BaseMatcher<Cookie> {\r\n\r\n private final Map<CookieField, Matcher> matchers = new EnumMap<>(CookieField.class);\r\n\r\n /**\r\n * Configures the cookie matcher with a consumer which is passed a <code>CookieMatcher</code> instance to configure.\r\n *\r\n * @param consumer the configuration consumer\r\n * @return the configured matcher\r\n */\r\n public static CookieMatcher cookieMatcher(final Consumer<CookieMatcher> consumer) {\r\n CookieMatcher cookieMatcher = new CookieMatcher();\r\n consumer.accept(cookieMatcher);\r\n return cookieMatcher;\r\n }\r\n\r\n /**\r\n * Applies a matcher for the specified cookie value. This is equivalent to calling <code>value(Matchers.equalTo('some value'))</code>.\r\n *\r\n * @param val the value string\r\n * @return a reference to the matcher being configured\r\n */\r\n public CookieMatcher value(final String val) {\r\n return value(equalTo(val));\r\n }\r\n\r\n /**\r\n * Applies the specified matcher to the cookie value.\r\n *\r\n * @param matcher the matcher to be used\r\n * @return a reference to the matcher being configured\r\n */\r\n public CookieMatcher value(final Matcher<String> matcher) {\r\n matchers.put(CookieField.VALUE, matcher);\r\n return this;\r\n }\r\n\r\n /**\r\n * Applies a matcher for the specified cookie comment value. This is equivalent to calling <code>comment(Matchers.equalTo('some value'))</code>.\r\n *\r\n * @param str the comment string\r\n * @return a reference to the matcher being configured\r\n */\r\n public CookieMatcher comment(final String str) {\r\n return comment(equalTo(str));\r\n }\r\n\r\n /**\r\n * Applies the specified matcher to the cookie comment.\r\n *\r\n * @param matcher the matcher to be used\r\n * @return a reference to the matcher being configured\r\n */\r\n public CookieMatcher comment(final Matcher<String> matcher) {\r\n matchers.put(CookieField.COMMENT, matcher);\r\n return this;\r\n }\r\n\r\n /**\r\n * Applies a matcher for the specified cookie domain value. This is equivalent to calling <code>domain(Matchers.equalTo('some value'))</code>.\r\n *\r\n * @param str the domain string\r\n * @return a reference to the matcher being configured\r\n */\r\n public CookieMatcher domain(final String str) {\r\n return domain(equalTo(str));\r\n }\r\n\r\n /**\r\n * Applies the specified matcher to the cookie domain.\r\n *\r\n * @param matcher the matcher to be used\r\n * @return a reference to the matcher being configured\r\n */\r\n public CookieMatcher domain(final Matcher<String> matcher) {\r\n matchers.put(CookieField.DOMAIN, matcher);\r\n return this;\r\n }\r\n\r\n /**\r\n * Applies a matcher for the specified cookie path value. This is equivalent to calling <code>path(Matchers.equalTo('some value'))</code>.\r\n *\r\n * @param str the path string\r\n * @return a reference to the matcher being configured\r\n */\r\n public CookieMatcher path(final String str) {\r\n return path(equalTo(str));\r\n }\r\n\r\n /**\r\n * Applies the specified matcher to the cookie path.\r\n *\r\n * @param matcher the matcher to be used\r\n * @return a reference to the matcher being configured\r\n */\r\n public CookieMatcher path(final Matcher<String> matcher) {\r\n matchers.put(CookieField.PATH, matcher);\r\n return this;\r\n }\r\n\r\n /**\r\n * Applies a matcher for the specified cookie version value. This is equivalent to calling <code>version(Matchers.equalTo(1))</code>.\r\n *\r\n * @param vers the version string\r\n * @return a reference to the matcher being configured\r\n */\r\n public CookieMatcher version(final int vers) {\r\n return version(equalTo(vers));\r\n }\r\n\r\n /**\r\n * Applies the specified matcher to the cookie version.\r\n *\r\n * @param matcher the matcher to be used\r\n * @return a reference to the matcher being configured\r\n */\r\n public CookieMatcher version(final Matcher<Integer> matcher) {\r\n matchers.put(CookieField.VERSION, matcher);\r\n return this;\r\n }\r\n\r\n /**\r\n * Applies a matcher for the specified cookie http-only value.\r\n *\r\n * @param httpOnly the httpOnly state\r\n * @return a reference to the matcher being configured\r\n */\r\n public CookieMatcher httpOnly(final boolean httpOnly) {\r\n matchers.put(CookieField.HTTP_ONLY, equalTo(httpOnly));\r\n return this;\r\n }\r\n\r\n /**\r\n * Applies a matcher for the specified cookie max-age value. This is equivalent to calling <code>maxAge(Matchers.equalTo(age))</code>.\r\n *\r\n * @param age the max-age value\r\n * @return a reference to the matcher being configured\r\n */\r\n public CookieMatcher maxAge(final int age) {\r\n return maxAge(equalTo(age));\r\n }\r\n\r\n /**\r\n * Applies the specified matcher to the cookie max-age value.\r\n *\r\n * @param matcher the matcher to be used\r\n * @return a reference to the matcher being configured\r\n */\r\n public CookieMatcher maxAge(final Matcher<Integer> matcher) {\r\n matchers.put(CookieField.MAX_AGE, matcher);\r\n return this;\r\n }\r\n\r\n /**\r\n * Applies a matcher for the specified cookie secure value.\r\n *\r\n * @param secure the secure state\r\n * @return a reference to the matcher being configured\r\n */\r\n public CookieMatcher secure(final boolean secure) {\r\n matchers.put(CookieField.SECURE, equalTo(secure));\r\n return this;\r\n }\r\n\r\n @Override\r\n public boolean matches(final Object item) {\r\n if (!(item instanceof Cookie)) {\r\n return false;\r\n }\r\n\r\n val cookie = (Cookie) item;\r\n\r\n return matchers.entrySet().stream().allMatch(entry -> {\r\n val matcher = entry.getValue();\r\n\r\n return switch (entry.getKey()) {\r\n case VALUE -> matcher.matches(cookie.getValue());\r\n case COMMENT -> matcher.matches(cookie.getComment());\r\n case DOMAIN -> matcher.matches(cookie.getDomain());\r\n case PATH -> matcher.matches(cookie.getPath());\r\n case MAX_AGE -> matcher.matches(cookie.getMaxAge());\r\n case HTTP_ONLY -> matcher.matches(cookie.isHttpOnly());\r\n case SECURE -> matcher.matches(cookie.isSecure());\r\n case VERSION -> matcher.matches(cookie.getVersion());\r\n };\r\n });\r\n }\r\n\r\n @Override\r\n public void describeTo(final Description description) {\r\n description.appendText(\"Cookie matching \");\r\n\r\n matchers.forEach((field, matcher) -> {\r\n description.appendText(field + \"(\");\r\n matcher.describeTo(description);\r\n description.appendText(\") \");\r\n });\r\n }\r\n\r\n private enum CookieField {\r\n VALUE, COMMENT, DOMAIN, PATH, MAX_AGE, HTTP_ONLY, SECURE, VERSION;\r\n }\r\n}\r", "public class MockClientRequest implements ClientRequest {\r\n\r\n private HttpMethod method;\r\n private String protocol;\r\n private String path;\r\n private final Map<String, Deque<String>> queryParams = new LinkedHashMap<>();\r\n private final Map<String, Deque<String>> headers = new LinkedHashMap<>();\r\n private final Map<String, Deque<String>> bodyParameters = new LinkedHashMap<>();\r\n private Map<String, Cookie> cookies = new LinkedHashMap<>();\r\n private byte[] body;\r\n private int contentLength;\r\n private String characterEncoding;\r\n\r\n public MockClientRequest() {\r\n // nothing\r\n }\r\n\r\n public MockClientRequest(final HttpMethod method) {\r\n this.method = method;\r\n }\r\n\r\n public MockClientRequest(final HttpMethod method, final String path){\r\n this(method);\r\n setPath(path);\r\n }\r\n\r\n public MockClientRequest(final byte[] content){\r\n setBody(content);\r\n }\r\n\r\n public void setCookies(Map<String, Cookie> cookies) {\r\n this.cookies = cookies;\r\n }\r\n\r\n public void setHeaders(Map<String, Deque<String>> headers) {\r\n this.headers.clear();\r\n this.headers.putAll(headers);\r\n }\r\n\r\n @Override public HttpMethod getMethod() {\r\n return method;\r\n }\r\n\r\n @Override public String getProtocol() {\r\n return protocol;\r\n }\r\n\r\n @Override public String getPath() {\r\n return path;\r\n }\r\n\r\n @Override public Map<String, Deque<String>> getQueryParams() {\r\n return queryParams;\r\n }\r\n\r\n @Override public Map<String, Deque<String>> getHeaders() {\r\n return headers;\r\n }\r\n\r\n @Override public Map<String, Cookie> getCookies() {\r\n return cookies;\r\n }\r\n\r\n @Override public byte[] getBody() {\r\n return body;\r\n }\r\n\r\n @Override public Map<String, Deque<String>> getBodyParameters() {\r\n return bodyParameters;\r\n }\r\n\r\n public void setBodyParameters(final Map<String, Deque<String>> params) {\r\n bodyParameters.clear();\r\n bodyParameters.putAll(params);\r\n }\r\n\r\n @Override public long getContentLength() {\r\n return contentLength;\r\n }\r\n\r\n @Override public String getCharacterEncoding() {\r\n return characterEncoding;\r\n }\r\n\r\n @Override public String getContentType() {\r\n return headers.containsKey(CONTENT_TYPE_HEADER) ? headers.get(CONTENT_TYPE_HEADER).getFirst() : null;\r\n }\r\n\r\n public MockClientRequest header(final String name, final String value) {\r\n headers.computeIfAbsent(name, s -> new ArrayDeque<>()).add(value);\r\n return this;\r\n }\r\n\r\n public MockClientRequest query(final String name, final String... values) {\r\n final var params = queryParams.computeIfAbsent(name, s -> new ArrayDeque<>());\r\n\r\n if (values != null) {\r\n for (String value : values) {\r\n if (value != null) {\r\n params.add(value);\r\n }\r\n }\r\n }\r\n\r\n return this;\r\n }\r\n\r\n public void setContentType(String contentType) {\r\n header(CONTENT_TYPE_HEADER, contentType);\r\n }\r\n\r\n public void setMethod(HttpMethod method) {\r\n this.method = method;\r\n }\r\n\r\n public void setProtocol(String protocol) {\r\n this.protocol = protocol;\r\n }\r\n\r\n public void setPath(String path) {\r\n this.path = path;\r\n }\r\n\r\n public void setBody(byte[] body) {\r\n this.body = body;\r\n }\r\n\r\n public void setContentLength(int contentLength) {\r\n this.contentLength = contentLength;\r\n }\r\n\r\n public void setCharacterEncoding(String characterEncoding) {\r\n this.characterEncoding = characterEncoding;\r\n }\r\n\r\n public MockClientRequest cookie(String name, String value) {\r\n return cookie(name, value, null, null, null, 0, false, false, 0);\r\n }\r\n\r\n public MockClientRequest cookie(final String name, String value, String comment, String domain, String path, Integer maxAge, Boolean httpOnly, Boolean secure, Integer version) {\r\n cookies.put(name, new Cookie(value, comment, domain, path, version, httpOnly, maxAge, secure));\r\n return this;\r\n }\r\n}\r", "public static final ContentType TEXT_PLAIN = new ContentType(\"text/plain\");\r", "static Matcher<Iterable<? super String>> stringIterableMatcher(final Collection<Matcher<? super String>> matchers) {\r\n return new StringIterableMatcher(matchers);\r\n}\r" ]
import io.github.cjstehno.ersatz.cfg.HttpMethod; import io.github.cjstehno.ersatz.encdec.DecoderChain; import io.github.cjstehno.ersatz.encdec.Decoders; import io.github.cjstehno.ersatz.encdec.RequestDecoders; import io.github.cjstehno.ersatz.match.CookieMatcher; import io.github.cjstehno.ersatz.server.MockClientRequest; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.MethodSource; import java.util.ArrayDeque; import java.util.Deque; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Stream; import static io.github.cjstehno.ersatz.cfg.ContentType.TEXT_PLAIN; import static io.github.cjstehno.ersatz.cfg.HttpMethod.GET; import static io.github.cjstehno.ersatz.cfg.HttpMethod.HEAD; import static io.github.cjstehno.ersatz.match.ErsatzMatchers.stringIterableMatcher; import static org.hamcrest.Matchers.*; import static org.hamcrest.core.IsIterableContaining.hasItem; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.params.provider.Arguments.arguments;
/** * Copyright (C) 2022 Christopher J. Stehno * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cjstehno.ersatz.impl; class RequestMatcherTest { @ParameterizedTest @DisplayName("method") @MethodSource("methodProvider") void method(final HttpMethod method, final boolean result) { assertEquals(result, RequestMatcher.method(equalTo(HEAD)).matches(new MockClientRequest(method))); } private static Stream<Arguments> methodProvider() { return Stream.of( arguments(HEAD, true), arguments(GET, false) ); } @ParameterizedTest @DisplayName("path") @CsvSource({ "/something,true", "/some,false" }) void path(final String path, final boolean result) { assertEquals(result, RequestMatcher.path(equalTo("/something")).matches(new MockClientRequest(GET, path))); } @ParameterizedTest @DisplayName("content-type") @MethodSource("contentTypeProvider") void contentType(final MockClientRequest request, final boolean result) { assertEquals(result, RequestMatcher.contentType(startsWith("application/")).matches(request)); } private static Stream<Arguments> contentTypeProvider() { final var factory = new Function<String, MockClientRequest>() { @Override public MockClientRequest apply(String ctype) { final var mcr = new MockClientRequest(); mcr.setContentType(ctype); return mcr; } }; return Stream.of( arguments(factory.apply("application/json"), true), arguments(factory.apply("application/"), true), arguments(new MockClientRequest(), false) ); } @ParameterizedTest @DisplayName("header") @MethodSource("headerProvider") void header(final MockClientRequest request, final boolean result) { assertEquals(result, RequestMatcher.header("foo", hasItem("bar")).matches(request)); } private static Stream<Arguments> headerProvider() { return Stream.of( arguments(new MockClientRequest().header("foo", "bar"), true), arguments(new MockClientRequest().header("one", "two"), false), arguments(new MockClientRequest().header("Foo", "bar"), true), arguments(new MockClientRequest().header("Foo", "Bar"), false), arguments(new MockClientRequest(), false) ); } @ParameterizedTest @DisplayName("query") @MethodSource("queryProvider") void query(final MockClientRequest request, final boolean result) { assertEquals( result, RequestMatcher.query( "name",
stringIterableMatcher(List.of(equalTo("alpha"), equalTo("blah")))
7
socialize/loopy-sdk-android
test/src/com/sharethis/loopy/test/ApiClientIntegrationTest.java
[ "public abstract class ApiCallback {\n\n /**\n * Called when the API request succeeded.\n * This method executes on the main UI thread.\n * @param result The result from the API call.\n */\n\tpublic abstract void onSuccess(JSONObject result);\n\n /**\n * Called when an unrecoverable error occurred during the API call.\n * This method executes on the main UI thread.\n * @param e The exception thrown within the async task.\n */\n\tpublic void onError(Throwable e) {}\n\n /**\n * Called within the async task. Implement this if you want additional work in the async task thread.\n * This method is NOT called on the main UI thread.\n * @param result The result from the API call.\n */\n public void onProcess(JSONObject result) {}\n\n /**\n * For internal use only\n * @param payload The payload to be sent to the server\n */\n public void onBeforePost(Map<String, String> headers, JSONObject payload) {}\n}", "public class ApiClient {\n\n public static final String SHORTLINK = \"shortlink\";\n public static final String SHARE = \"share\";\n public static final String SHARELINK = \"sharelink\";\n public static final String INSTALL = \"install\";\n public static final String REFERRER = \"referrer\";\n public static final String OPEN = \"open\";\n public static final String LOG = \"log\";\n\n public static final String AUTH_HEADER_KEY = \"X-LoopyAppID\";\n public static final String AUTH_HEADER_SECRET = \"X-LoopyKey\";\n\n private static final ShortlinkCache shortlinkCache = new ShortlinkCache();\n private boolean useShortlinkCache = true;\n\n private HttpClientFactory httpClientFactory;\n\n public void start(Session session) {\n httpClientFactory = new HttpClientFactory();\n httpClientFactory.start(session.getConfig().getApiTimeout());\n }\n\n public void stop() {\n if(httpClientFactory != null) {\n httpClientFactory.stop();\n }\n }\n\n /**\n * Correlates to the /install endpoint of the Loopy API\n *\n * @param referrer The referrer that lead to the installation of the app.\n * @param callback A callback to handle the result.\n */\n @SuppressWarnings(\"unused\")\n public void install(String apiKey, String apiSecret, String stdid, String referrer, ApiCallback callback) {\n\n if (Logger.isDebugEnabled()) {\n Logger.d(\"install called for \" + referrer);\n }\n\n try {\n JSONObject payload = getInstallOpenPayload(stdid, referrer, true);\n callAsync(getAuthHeader(apiKey, apiSecret), payload, INSTALL, true, callback);\n } catch (Exception e) {\n Logger.e(e);\n if (callback != null) {\n callback.onError(e);\n }\n }\n }\n\n void installDirect(String apiKey, String apiSecret, String stdid, String referrer) throws Exception {\n if (Logger.isDebugEnabled()) {\n Logger.d(\"install called for \" + referrer);\n }\n JSONObject payload = getInstallOpenPayload(stdid, referrer, true);\n call(getAuthHeader(apiKey, apiSecret), payload, INSTALL, true);\n }\n\n\n /**\n * Correlates to the /open endpoint of the Loopy API\n *\n * @param referrer The referrer that lead to the open of the app.\n * @param callback A callback to handle the result.\n */\n @SuppressWarnings(\"unused\")\n public void open(String apiKey, String apiSecret, String referrer, ApiCallback callback) {\n\n if (Logger.isDebugEnabled()) {\n Logger.d(\"open called for \" + referrer);\n }\n\n try {\n JSONObject payload = getInstallOpenPayload(null, referrer, false);\n doAsyncCall(apiKey, apiSecret, payload, OPEN, false, callback, null);\n } catch (Exception e) {\n Logger.e(e);\n if (callback != null) {\n callback.onError(e);\n }\n }\n }\n\n void openDirect(String apiKey, String apiSecret, String stdid, String referrer) throws Exception {\n\n if (Logger.isDebugEnabled()) {\n Logger.d(\"open called for \" + referrer);\n }\n JSONObject payload = getInstallOpenPayload(stdid, referrer, false);\n call(getAuthHeader(apiKey, apiSecret), payload, OPEN, true);\n }\n\n /**\n * Correlates to the /referrer endpoint of the Loopy API\n *\n * @param referrer The referrer that lead to the installation of the app.\n * @param callback A callback to handle the result.\n */\n public void referrer(String apiKey, String apiSecret, String referrer, ApiCallback callback) {\n\n if (Logger.isDebugEnabled()) {\n Logger.d(\"referrer called for \" + referrer);\n }\n\n try {\n JSONObject payload = newJSONObject();\n\n payload.put(\"referrer\", referrer);\n\n addDevice(payload);\n addApp(payload);\n addClient(payload);\n\n doAsyncCall(apiKey, apiSecret, payload, REFERRER, false, callback, null);\n } catch (Exception e) {\n Logger.e(e);\n if (callback != null) {\n callback.onError(e);\n }\n }\n }\n\n /**\n * Correlates to the /shortlink endpoint of the Loopy API\n *\n * @param item The item being shared.\n * @param callback A callback to handle the response.\n */\n public void shortlink(String apiKey, String apiSecret, final Item item, final ApiCallback callback) {\n\n if (Logger.isDebugEnabled()) {\n Logger.d(\"shortlink called for \" + item);\n }\n\n try {\n\n if (useShortlinkCache) {\n String shortlink = shortlinkCache.getShortlink(item);\n if (shortlink != null && callback != null) {\n JSONObject result = newJSONObject();\n result.put(\"shortlink\", shortlink);\n callback.onSuccess(result);\n return;\n }\n }\n\n JSONObject payload = newJSONObject();\n Device device = getDevice();\n\n if (device != null) {\n payload.put(\"md5id\", device.getMd5Id());\n }\n\n payload.put(\"item\", getItemPayload(item));\n\n if (item.tags != null && item.tags.size() > 0) {\n JSONUtils.put(payload, \"tags\", item.tags);\n }\n\n doAsyncCall(apiKey, apiSecret, payload, SHORTLINK, false, callback, new ApiClientCallback() {\n @Override\n public void onSuccess(JSONObject result) {\n if (useShortlinkCache) {\n String shortlink = JSONUtils.getString(result, \"shortlink\");\n if (shortlink != null) {\n shortlinkCache.add(shortlink, item);\n }\n }\n }\n });\n } catch (Exception e) {\n Logger.e(e);\n if (callback != null) {\n callback.onError(e);\n }\n }\n }\n\n /**\n * Correlates to the /sharelink endpoint of the Loopy API. This creates a shortlink and generates a share event\n * in a single call.\n * @param item The item being shared.\n * @param channel The channel through which the share is occurring (e.g. facebook, email etc)\n * @param callback A callback to handle the response.\n */\n @SuppressWarnings(\"unused\")\n public void shareLink(String apiKey, String apiSecret, final Item item, String channel, final ApiCallback callback) {\n if (Logger.isDebugEnabled()) {\n Logger.d(\"shareLink called for \" + item + \" via channel \" + channel);\n }\n\n try {\n JSONObject payload = newJSONObject();\n payload.put(\"item\", getItemPayload(item));\n payload.put(\"channel\", channel);\n\n addDevice(payload);\n addApp(payload);\n addClient(payload);\n\n doAsyncCall(apiKey, apiSecret, payload, SHARELINK, false, callback, new ApiClientCallback() {\n @Override\n public void onSuccess(JSONObject result) {\n if (useShortlinkCache) {\n String shortlink = JSONUtils.getString(result, \"shortlink\");\n if (shortlink != null) {\n shortlinkCache.remove(shortlink);\n }\n }\n }\n });\n } catch (Exception e) {\n Logger.e(e);\n if (callback != null) {\n callback.onError(e);\n }\n }\n }\n\n /**\n * Correlates to the /share endpoint of the Loopy API\n *\n * @param shortlink The original shortlink generated from the /shortlink endpoint.\n * @param channel The channel through which the share is occurring (e.g. facebook, email etc)\n * @param callback A callback to handle the response.\n */\n public void share(String apiKey, String apiSecret, final String shortlink, String channel, final ApiCallback callback) {\n\n if (Logger.isDebugEnabled()) {\n Logger.d(\"share called for \" + shortlink + \" via channel \" + channel);\n }\n\n try {\n JSONObject payload = newJSONObject();\n payload.put(\"shortlink\", shortlink);\n payload.put(\"channel\", channel);\n\n addDevice(payload);\n addApp(payload);\n addClient(payload);\n\n doAsyncCall(apiKey, apiSecret, payload, SHARE, false, callback, new ApiClientCallback() {\n @Override\n public void onSuccess(JSONObject result) {\n if (useShortlinkCache) {\n shortlinkCache.remove(shortlink);\n }\n }\n });\n } catch (Exception e) {\n Logger.e(e);\n if (callback != null) {\n callback.onError(e);\n }\n }\n }\n\n /**\n * Correlates to the /log endpoint of the Loopy API\n *\n * @param event The event being logged.\n * @param callback A callback to handle the result.\n */\n @SuppressWarnings(\"unused\")\n public void log(String apiKey, String apiSecret, Event event, ApiCallback callback) {\n\n if (Logger.isDebugEnabled()) {\n Logger.d(\"log called for \" + event);\n }\n\n try {\n JSONObject eventJSON = new JSONObject();\n\n if(event != null) {\n JSONUtils.put(eventJSON, \"type\", event.getType());\n JSONUtils.put(eventJSON, \"meta\", event.getMeta());\n }\n\n JSONObject payload = newJSONObject();\n\n payload.put(\"event\", eventJSON);\n\n addDevice(payload);\n addApp(payload);\n addClient(payload);\n\n doAsyncCall(apiKey, apiSecret, payload, LOG, false, callback, null);\n } catch (Exception e) {\n Logger.e(e);\n if (callback != null) {\n callback.onError(e);\n }\n }\n }\n\n protected void callAsync(final Map<String, String> headers, final JSONObject payload, final String endpoint, final boolean secure, final ApiCallback cb) {\n\n if (cb != null) {\n cb.onBeforePost(headers, payload);\n }\n\n new AsyncTask<JSONObject, Void, JSONObject>() {\n\n Exception error;\n\n @Override\n protected JSONObject doInBackground(JSONObject... params) {\n try {\n JSONObject result = call(headers, payload, endpoint, secure);\n\n if (cb != null) {\n cb.onProcess(result);\n }\n\n return result;\n } catch (Exception e) {\n Logger.e(e);\n error = e;\n return null;\n }\n }\n\n @Override\n protected void onPostExecute(JSONObject result) {\n\n try {\n if (cb != null) {\n if (error != null) {\n if (error instanceof SocketTimeoutException) {\n cb.onError(LoopyException.wrap(error, LoopyException.CLIENT_TIMEOUT));\n } else {\n // Hack for Android <= 2.3\n if(error instanceof IOException && error.getMessage().equals(\"Request aborted\")) {\n cb.onError(LoopyException.wrap(error, LoopyException.CLIENT_TIMEOUT));\n } else {\n cb.onError(error);\n }\n }\n } else {\n // Check for api error\n if (!JSONUtils.isNull(result, \"error\")) {\n try {\n JSONObject error = result.getJSONObject(\"error\");\n StringBuilder builder = new StringBuilder();\n\n if (!JSONUtils.isNull(error, \"message\")) {\n JSONArray messages = error.getJSONArray(\"message\");\n for (int i = 0; i < messages.length(); i++) {\n if (i > 0) {\n builder.append(\",\");\n }\n builder.append(messages.getString(i));\n }\n }\n\n cb.onError(new LoopyException(builder.toString(), error.getInt(\"code\")));\n } catch (Exception e) {\n Logger.e(e);\n cb.onError(new LoopyException(\"An error was returned but the error data could not be parsed\", e, LoopyException.PARSE_ERROR));\n }\n } else {\n cb.onSuccess(result);\n }\n }\n }\n } catch (Throwable e) {\n // We NEVER want to bubble any exception up to the calling/ui thread.\n Logger.e(e);\n }\n }\n }.execute();\n }\n\n protected JSONObject call(Map<String, String> headers, JSONObject payload, String endpoint, boolean secure) throws Exception {\n\n HttpEntity entity = null;\n\n try {\n\n Session session = Session.getInstance().waitForStart();\n String url;\n\n if (secure) {\n url = session.getConfig().getSecureAPIUrl();\n } else {\n url = session.getConfig().getAPIUrl();\n }\n\n url += endpoint;\n\n HttpClient client = httpClientFactory.getClient();\n HttpPost post = new HttpPost(url);\n\n post.setHeader(\"Content-Type\", \"application/json\");\n\n if (headers != null) {\n for (Map.Entry<String, String> header : headers.entrySet()) {\n post.addHeader(header.getKey(), header.getValue());\n }\n }\n\n post.setEntity(new StringEntity(payload.toString(), HTTP.UTF_8));\n\n if (Logger.isDebugEnabled()) {\n Logger.d(\"calling endpoint url \" + url + \" with POST data [\" +\n payload +\n \"]\");\n }\n\n HttpResponse response = client.execute(post);\n\n if (response != null) {\n int statusCode = response.getStatusLine().getStatusCode();\n entity = response.getEntity();\n String sResponseText = EntityUtils.toString(entity, HTTP.UTF_8);\n\n if (Logger.isDebugEnabled()) {\n Logger.d(\"got result [\" +\n statusCode +\n \"] with data [\" +\n sResponseText +\n \"]\");\n }\n\n if (statusCode != 200) {\n throw new LoopyException(response.getStatusLine().getReasonPhrase() + \":\\n\" + sResponseText, statusCode);\n } else {\n return new JSONObject(sResponseText);\n }\n } else {\n throw new LoopyException(\"Empty Response\", 204); // 204 is \"no content\"\n }\n } finally {\n if (entity != null) {\n entity.consumeContent();\n }\n }\n }\n\n void doAsyncCall(String apiKey, String apiSecret, JSONObject payload, final String endpoint, boolean secure, final ApiCallback callback, final ApiClientCallback apiCallback) {\n\n try {\n\n LoopyState state = getState();\n\n if (state.hasSTDID()) {\n\n payload.put(\"stdid\", state.getSTDID());\n payload.put(\"timestamp\", getCurrentTimestamp());\n\n callAsync(getAuthHeader(apiKey, apiSecret), payload, endpoint, secure, new ApiCallback() {\n @Override\n public void onSuccess(JSONObject result) {\n\n if (apiCallback != null) {\n apiCallback.onSuccess(result);\n }\n\n if (callback != null) {\n callback.onSuccess(result);\n }\n }\n\n @Override\n public void onBeforePost(Map<String, String> headers, JSONObject payload) {\n if (callback != null) {\n callback.onBeforePost(headers, payload);\n }\n }\n\n @Override\n public void onProcess(JSONObject result) {\n if (callback != null) {\n callback.onProcess(result);\n }\n }\n\n @Override\n public void onError(Throwable e) {\n if (callback != null) {\n callback.onError(e);\n }\n }\n });\n } else {\n LoopyException error = new LoopyException(\"Internal STDID not found. Make sure you call \\\"install\\\" before calling share\", LoopyException.PARAMETER_MISSING);\n if (callback != null) {\n callback.onError(error);\n }\n Logger.e(error);\n }\n } catch (Exception e) {\n Logger.e(e);\n if (callback != null) {\n callback.onError(e);\n }\n }\n }\n\n protected void addApp(JSONObject payload) throws JSONException {\n App app = getApp();\n if (app != null) {\n JSONObject a = new JSONObject();\n JSONUtils.put(a, \"id\", app.getId());\n JSONUtils.put(a, \"name\", app.getName());\n JSONUtils.put(a, \"version\", app.getVersion());\n payload.put(\"app\", a);\n }\n }\n\n protected void addClient(JSONObject payload) throws JSONException {\n JSONObject c = new JSONObject();\n JSONUtils.put(c, \"lang\", \"java\");\n JSONUtils.put(c, \"version\", Loopy.VERSION);\n payload.put(\"client\", c);\n }\n\n // Mockable\n protected App getApp() {\n return Loopy.getInstance().getApp();\n }\n\n // Mockable\n protected Device getDevice() {\n return Loopy.getInstance().getDevice();\n }\n\n // Mockable\n protected Geo getGeo() {\n return Loopy.getInstance().getGeo();\n }\n\n // Mockable\n protected long getCurrentTimestamp() {\n return System.currentTimeMillis();\n }\n\n public LoopyState getState() {\n Session instance = Session.getInstance();\n if (instance.isStarted()) {\n instance.waitForStart();\n return instance.getState();\n } else {\n throw new LoopyException(\"Session not started. Make sure you have called Loopy.onStart in the onStart method of your Activity\", LoopyException.LIFECYCLE_ERROR);\n }\n }\n\n protected void addDevice(JSONObject payload) throws JSONException {\n addDevice(payload, false);\n }\n\n protected void addDevice(JSONObject payload, boolean id) throws JSONException {\n Device device = getDevice();\n if (device != null) {\n payload.put(\"md5id\", device.getMd5Id());\n\n JSONObject d = newJSONObject();\n\n if (id) {\n d.put(\"id\", device.getAndroidId());\n }\n\n JSONUtils.put(d, \"model\", device.getModelName());\n JSONUtils.put(d, \"os\", \"android\");\n JSONUtils.put(d, \"osv\", device.getAndroidVersion());\n JSONUtils.put(d, \"carrier\", device.getCarrier());\n JSONUtils.put(d, \"wifi\", device.getWifiState().state);\n\n Geo geo = getGeo();\n\n if (geo != null) {\n JSONObject g = new JSONObject();\n g.put(\"lat\", geo.getLat());\n g.put(\"lon\", geo.getLon());\n\n d.put(\"geo\", g);\n }\n\n payload.put(\"device\", d);\n }\n }\n\n JSONObject getInstallOpenPayload(String stdid, String referrer, boolean deviceId) throws JSONException {\n JSONObject payload = newJSONObject();\n if(stdid != null) {\n payload.put(\"stdid\", stdid);\n }\n payload.put(\"timestamp\", getCurrentTimestamp());\n payload.put(\"referrer\", referrer);\n addDevice(payload, deviceId);\n addApp(payload);\n addClient(payload);\n return payload;\n }\n\n JSONObject getItemPayload(Item item) throws JSONException {\n JSONObject itemJSON = new JSONObject();\n JSONUtils.put(itemJSON, \"type\", item.getType());\n JSONUtils.put(itemJSON, \"url\", item.getUrl());\n JSONUtils.put(itemJSON, \"title\", item.getTitle());\n JSONUtils.put(itemJSON, \"image\", item.getImageUrl());\n JSONUtils.put(itemJSON, \"description\", item.getDescription());\n JSONUtils.put(itemJSON, \"video\", item.getVideoUrl());\n return itemJSON;\n }\n\n // Mockable\n JSONObject newJSONObject() {\n return new JSONObject();\n }\n\n Map<String, String> getAuthHeader(String apiKey, String apiSecret) {\n Map<String, String> headers = new HashMap<String, String>();\n headers.put(AUTH_HEADER_KEY, apiKey);\n headers.put(AUTH_HEADER_SECRET, apiSecret);\n return headers;\n }\n\n @SuppressWarnings(\"unused\")\n final void setHttpClientFactory(HttpClientFactory httpClientFactory) {\n this.httpClientFactory = httpClientFactory;\n }\n\n @SuppressWarnings(\"unused\")\n public void setUseShortlinkCache(boolean useShortlinkCache) {\n this.useShortlinkCache = useShortlinkCache;\n }\n}", "public class Event {\n\n private String type;\n private Map<String, String> meta;\n\n public String getType() {\n return type;\n }\n\n public void setType(String type) {\n this.type = type;\n }\n\n public Map<String, String> getMeta() {\n return meta;\n }\n\n public void setMeta(Map<String, String> meta) {\n this.meta = meta;\n }\n\n public synchronized void addMeta(String key, String value) {\n if(meta == null) {\n meta = new LinkedHashMap<String, String>();\n }\n meta.put(key, value);\n }\n\n @Override\n public String toString() {\n return \"Event{\" +\n \"type='\" + type + '\\'' +\n \", meta=\" + meta +\n '}';\n }\n}", "public class Item {\n\n String type = \"website\";\n String url;\n String title;\n String imageUrl;\n String description;\n String videoUrl;\n Set<String> tags;\n\n String shortlink;\n\n /**\n * The \"og:type\" corresponding to the content being shared.\n * @return og:type\n */\n public String getType() {\n return type;\n }\n\n /**\n * Optional.\n * Corresponds to the og:type meta element. Default is 'website'\n * @param type The type of the content being shared (og:type)\n * @see <a href=\"http://ogp.me/#types\" target=\"_blank\">http://ogp.me/#types</a>\n */\n public void setType(String type) {\n this.type = type;\n }\n\n public String getUrl() {\n return url;\n }\n\n /**\n * Optional. (MUST specify one of url or title!)\n * The url of the content being shared. If the content does not have a url, you must at least provide a title.\n * @param url The url of the content being shared.\n */\n public void setUrl(String url) {\n this.url = url;\n }\n\n public String getTitle() {\n return title;\n }\n\n /**\n * Optional. (MUST specify one of url or title!)\n * The title of the content being shared. If the content does not have a url, you must at least provide a title.\n * @param title The title of the content being shared.\n */\n public void setTitle(String title) {\n this.title = title;\n }\n\n public String getImageUrl() {\n return imageUrl;\n }\n\n /**\n * Optional. Corresponds to og:image\n * @param imageUrl An image url corresponding to the content being shared.\n */\n public void setImageUrl(String imageUrl) {\n this.imageUrl = imageUrl;\n }\n\n public String getDescription() {\n return description;\n }\n\n /**\n * Optional. Corresponds to og:description\n * @param description The description of the content being shared.\n */\n public void setDescription(String description) {\n this.description = description;\n }\n\n public String getVideoUrl() {\n return videoUrl;\n }\n\n /**\n * Optional. Corresponds to og:video\n * @param videoUrl A video url corresponding to the content being shared.\n */\n public void setVideoUrl(String videoUrl) {\n this.videoUrl = videoUrl;\n }\n\n /**\n * @return The custom tags associated with the item\n */\n public Set<String> getTags() {\n return tags;\n }\n\n /**\n * Optional.\n * @param tags Any custom tags associated with the item\n */\n public void setTags(Set<String> tags) {\n this.tags = tags;\n }\n\n public String getShortlink() {\n return shortlink;\n }\n\n void setShortlink(String shortlink) {\n this.shortlink = shortlink;\n }\n\n public synchronized void addTag(String tag) {\n if(tags == null) {\n tags = new LinkedHashSet<String>();\n }\n tags.add(tag);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n Item item = (Item) o;\n\n if (title != null ? !title.equals(item.title) : item.title != null) return false;\n if (url != null ? !url.equals(item.url) : item.url != null) return false;\n\n return true;\n }\n\n @Override\n public int hashCode() {\n int result = url != null ? url.hashCode() : 0;\n result = 31 * result + (title != null ? title.hashCode() : 0);\n return result;\n }\n\n @Override\n public String toString() {\n if(url != null) {\n return url;\n }\n else if(title != null) {\n return title;\n }\n return super.toString();\n }\n}", "public class Loopy {\n\n public static String VERSION = \"1.0\";\n\n static final String INSTALL_ACTION = \"STInstallAction\";\n\n static Loopy instance = new Loopy(new ApiClient());\n\n // TODO: Should be part of loopy instance.\n private static BroadcastReceiver installReceiver;\n\n private ApiClient apiClient;\n private Device device;\n private App app;\n private Geo geo;\n private int instances = 0;\n private boolean receiverRegistered = false;\n private CountDownLatch startLatch;\n\n ShareClickListener shareClickListener = new ShareClickListener();\n ShareConfig config = new ShareConfig();\n\n Loopy(ApiClient apiClient) {\n this.apiClient = apiClient;\n }\n\n static Loopy getInstance() {\n return instance;\n }\n\n /**\n * Should be called within the Activity lifecycle onCreate() method.\n *\n * @param context The current context.\n */\n public static void onCreate(Context context, String apiKey, String apiSecret) {\n\n if(Logger.isDebugEnabled()) {\n Logger.d(\"onCreate called for \" + apiKey);\n }\n\n AppDataCache.getInstance().onCreate(context);\n instance.create(context, apiKey, apiSecret);\n }\n\n /**\n * Should be called within the Activity lifecycle onDestroy() method.\n *\n * @param context The current context.\n */\n public static void onDestroy(Context context) {\n if(Logger.isDebugEnabled()) {\n Logger.d(\"onDestroy called\");\n }\n\n AppDataCache.getInstance().onDestroy(context);\n instance.destroy();\n }\n\n /**\n * Should be called within the Activity lifecycle onStart() method.\n *\n * @param context The current context.\n */\n public static void onStart(Context context) {\n if(Logger.isDebugEnabled()) {\n Logger.d(\"onStart called\");\n }\n instance.start(context);\n }\n\n /**\n * Optional variation of onStart that takes a callback\n * @param context The current context.\n * @param callback A callback that will be notified when the start process has completed.\n */\n public static void onStart(Context context, StartCallback callback) {\n if(Logger.isDebugEnabled()) {\n Logger.d(\"onStart called\");\n }\n instance.start(context, callback);\n }\n\n /**\n * Should be called within the Activity lifecycle onStop() method.\n *\n * @param context The current context.\n */\n public static void onStop(Context context) {\n if(Logger.isDebugEnabled()) {\n Logger.d(\"onStop called\");\n }\n instance.stop(context);\n }\n\n /**\n * Called by the BroadcastReciever when a referred installation occurs.\n * This will be called from a separate process.\n *\n * @param context The current context.\n * @param intent The receiver intent.\n */\n public static void onInstall(final Context context, Intent intent) {\n // Send an in-app broadcast to trigger the install on the main process thread.\n Intent installIntent = new Intent();\n installIntent.setAction(INSTALL_ACTION);\n installIntent.putExtras(intent);\n context.sendBroadcast(installIntent);\n }\n\n /**\n * Displays the default share dialog and presents the apps that are able to consume the content type of the share intent provided.\n *\n * @param context The current context.\n * @param dialogTitle The title of the dialog.\n * @param url The url to be shared.\n * @param shareIntent The original share intent\n */\n public static void showShareDialog(\n Context context,\n String dialogTitle,\n String url,\n Intent shareIntent,\n ShareDialogListener listener) {\n Item item = new Item();\n item.setUrl(url);\n showShareDialog(context, dialogTitle, item, shareIntent, listener);\n }\n\n /**\n * Displays the default share dialog and presents the apps that are able to consume the content type of the share intent provided.\n *\n * @param context The current context.\n * @param dialogTitle The title of the dialog.\n * @param item The item to be shared.\n * @param shareIntent The original share intent\n */\n public static void showShareDialog(final Context context,\n final String dialogTitle,\n final Item item,\n final Intent shareIntent,\n final ShareDialogListener listener) {\n Loopy.shorten(item, new ShareCallback() {\n @Override\n public void onResult(Item item, Throwable error) {\n if (listener != null) {\n listener.onLinkGenerated(item, shareIntent, error);\n }\n\n if (error == null || !StringUtils.isEmpty(item.getUrl())) {\n showDialog(context, dialogTitle, shareIntent, listener);\n }\n }\n });\n }\n\n /**\n * Displays the default share dialog and presents the apps that are able to consume the content type\n * of the share intent provided.\n * <br/>\n * NOTE: This method assumes the shortlink property of the share Item has been set.\n * @param context The current context.\n * @param title The title of the dialog.\n * @param item The Item to be shared.\n * @param shareIntent The original share intent\n */\n static void showDialog(\n Context context,\n String title,\n Item item,\n Intent shareIntent,\n ShareDialogListener listener) {\n instance.doShareDialog(context, title, item, shareIntent, listener);\n }\n\n /**\n * Adds tracking to the given url.\n *\n * @param url The URL to shorten.\n * @param callback A callback to handle the result.\n */\n @SuppressWarnings(\"unused\")\n public static void shorten(String url, final ShareCallback callback) {\n final Item item = new Item();\n item.setUrl(url);\n shorten(item, callback);\n }\n\n /**\n * Reports a share AND generates a shortlink\n * @param item The item to be shared.\n * @param channel The channel through which the share occurred.\n * @param callback A callback to handle the result.\n */\n public static void shareAndLink(Item item, String channel, final ShareCallback callback) {\n if (callback != null) {\n callback.setItem(item);\n }\n instance.sharelink(item, channel, callback);\n }\n\n /**\n * Adds tracking to the given item.\n *\n * @param item The item to track.\n * @param callback A callback to handle the result.\n */\n public static void shorten(final Item item, final ShareCallback callback) {\n if (callback != null) {\n callback.setItem(item);\n }\n instance.shortlink(item, callback);\n }\n\n static void reportShareFromIntent(Context context, Item item, Intent intent) {\n instance.shareFromIntent(context, item, intent);\n }\n\n @SuppressWarnings(\"unused\")\n public static void reportShare(Item item, String channel) {\n instance.share(item, channel, null);\n }\n\n @SuppressWarnings(\"unused\")\n public static void reportShare(Item item, String channel, ApiCallback callback) {\n instance.share(item, channel, callback);\n }\n\n /**\n * Sets the api key/secret combination\n *\n * @param apiKey Your api key.\n * @param apiSecret Your api secret.\n */\n @SuppressWarnings(\"unused\")\n public static void setApiKey(String apiKey, String apiSecret) {\n instance.config.setApiKey(apiKey);\n instance.config.setApiSecret(apiSecret);\n }\n\n void sharelink(Item item, String channel, ApiCallback callback) {\n getApiClient().shareLink(\n config.getApiKey(),\n config.getApiSecret(),\n item,\n channel,\n callback\n );\n }\n\n // Mockable\n void shortlink(Item item, ApiCallback callback) {\n getApiClient().shortlink(\n config.getApiKey(),\n config.getApiSecret(),\n item, callback);\n }\n\n // Mockable\n void share(Item item, String channel, ApiCallback callback) {\n if (item.getShortlink() != null) {\n getApiClient().share(\n config.getApiKey(),\n config.getApiSecret(),\n item.getShortlink(),\n channel,\n callback);\n }\n }\n\n void shareFromIntent(Context context, Item item, Intent intent) {\n String app = AppDataCache.getInstance().getAppLabel(intent.getComponent().getPackageName(), intent.getComponent().getClassName());\n\n if (app == null) {\n PackageManager pm = context.getPackageManager();\n try {\n if(pm != null) {\n ActivityInfo activityInfo = pm.getActivityInfo(intent.getComponent(), 0);\n if(activityInfo != null) {\n CharSequence label = activityInfo.loadLabel(pm);\n if(label != null) {\n app = label.toString();\n }\n }\n }\n } catch (Exception e) {\n Logger.e(e);\n }\n }\n\n if (app != null) {\n share(item, app, null);\n }\n }\n\n void doShareDialog(\n final Context context,\n final String title,\n final Item item,\n final Intent shareIntent,\n final ShareDialogListener dialogListener) {\n\n final LayoutInflater inflater = getInflater(context);\n\n new AsyncTask<Void, Void, Void>() {\n\n ListView view;\n ShareDialogAdapter adapter;\n\n @Override\n protected Void doInBackground(Void... params) {\n String type = shareIntent.getType();\n\n if (type == null) {\n type = \"text/plain\";\n }\n\n Collection<ResolveInfo> appsForContentType = getAppUtils().getAppsForContentType(context, type);\n\n adapter = newShareDialogAdapter(context, getAppList(appsForContentType));\n\n adapter.setOnShareClickListener(shareClickListener);\n adapter.setShareItem(item);\n adapter.setShareIntent(shareIntent);\n adapter.setConfig(config);\n\n view = (ListView) inflater.inflate(R.layout.st_share_dialog_list, null);\n\n if(view != null) {\n view.setAdapter(adapter);\n }\n\n return null;\n }\n\n @Override\n protected void onPostExecute(Void aVoid) {\n if (view != null) {\n AlertDialog.Builder builder = newAlertDialogBuilder(new ContextThemeWrapper(context, R.style.STDialogTheme));\n builder.setTitle(title);\n builder.setView(view);\n AlertDialog alertDialog = builder.create();\n\n if (dialogListener != null) {\n alertDialog.setOnCancelListener(dialogListener);\n alertDialog.setOnShowListener(dialogListener);\n adapter.setShareDialogListener(dialogListener);\n }\n\n adapter.setDialog(alertDialog);\n\n alertDialog.show();\n }\n }\n }.execute();\n }\n\n List<ShareDialogRow> getAppList(Collection<ResolveInfo> appsForContentType) {\n\n List<ShareDialogRow> appdata = new LinkedList<ShareDialogRow>();\n\n int i = 0;\n ShareDialogRow row = null;\n\n if (appsForContentType != null) {\n for (ResolveInfo resolveInfo : appsForContentType) {\n if (i % 2 == 0) { // even\n row = new ShareDialogRow();\n appdata.add(row);\n row.left = resolveInfo;\n } else if (row != null) {\n row.right = resolveInfo;\n }\n i++;\n }\n }\n\n return appdata;\n }\n\n @SuppressWarnings(\"unused\")\n public static final class Channel {\n public static final String FACEBOOK = \"facebook\";\n public static final String TWITTER = \"twitter\";\n public static final String GOOGLEPLUS = \"googleplus\";\n public static final String PINTEREST = \"pinterest\";\n public static final String EMAIL = \"email\";\n public static final String SMS = \"sms\";\n }\n\n // mockable\n AppUtils getAppUtils() { return AppUtils.getInstance(); }\n\n // mockable\n ShareDialogAdapter newShareDialogAdapter(Context context, List<ShareDialogRow> appList) {\n return new ShareDialogAdapter(context, appList);\n }\n\n // mockable\n AlertDialog.Builder newAlertDialogBuilder(Context context) { return new AlertDialog.Builder(context); }\n\n // mockable\n LayoutInflater getInflater(Context context) { return LayoutInflater.from(context); }\n\n // Internal use only\n static void setInstance(Loopy loopy) {\n instance = loopy;\n }\n\n protected App getApp() {\n return app;\n }\n\n protected Device getDevice() {\n return device;\n }\n\n protected Geo getGeo() {\n return geo;\n }\n\n // Mockable\n protected Session getSession() {\n return Session.getInstance();\n }\n\n public ApiClient getApiClient() {\n return apiClient;\n }\n\n @SuppressWarnings(\"unused\")\n protected void setApiClient(ApiClient apiClient) {\n this.apiClient = apiClient;\n }\n\n protected void create(Context context, String apiKey, String apiSecret) {\n if (instances == 0) {\n this.device = new Device().onCreate(context);\n this.app = new App().onCreate(context);\n this.config.setApiKey(apiKey);\n this.config.setApiSecret(apiSecret);\n if (Geo.hasPermission(context)) {\n this.geo = new Geo();\n }\n }\n instances++;\n }\n\n protected void start(Context context) {\n start(context, null);\n }\n\n protected void start(final Context context, final StartCallback cb) {\n\n startLatch = new CountDownLatch(1);\n\n if (geo != null) {\n geo.onStart(context);\n }\n\n final Session session = getSession();\n\n session.start(context);\n\n unregisterReceiver(context);\n registerReceiver(context);\n\n // Check for install or open\n new AsyncTask<Void, Void, Void>() {\n @Override\n protected Void doInBackground(Void... params) {\n\n try {\n session.waitForStart();\n\n apiClient.start(session);\n\n if (session.getState() != null) {\n\n if (session.getState().hasSTDID()) {\n\n long currentTime = System.currentTimeMillis();\n long sessionTimeoutMS = session.getConfig().getSessionTimeoutSeconds() * 1000;\n long lastOpenTime = session.getState().getLastOpenTime();\n\n if (currentTime - lastOpenTime >= sessionTimeoutMS) {\n try {\n apiClient.openDirect(\n config.getApiKey(),\n config.getApiSecret(),\n session.getState().getSTDID(),\n null);\n\n session.getState().setLastOpenTime(currentTime);\n session.getState().save(context);\n } catch (Exception e) {\n Logger.e(e);\n }\n }\n } else {\n try {\n final String stdid = generateUUID();\n\n // disable loopy installation due to discontinued Mashery account\n // should be uncommented if new endpoint is used for installations tracking\n // apiClient.installDirect(\n // config.getApiKey(),\n // config.getApiSecret(),\n // stdid,\n // null);\n\n session.getState().setStdid(stdid);\n session.getState().save(context);\n } catch (Exception e) {\n Logger.e(e);\n }\n }\n } else {\n Logger.w(\"No session state during start. This should not happen\");\n }\n } finally {\n startLatch.countDown();\n }\n return null;\n }\n\n @Override\n protected void onPostExecute(Void aVoid) {\n if(cb != null) {\n cb.onComplete();\n }\n }\n }.execute();\n }\n\n // Mockable\n String generateUUID() {\n return UUID.randomUUID().toString();\n }\n\n protected void registerReceiver(Context context) {\n if (!receiverRegistered) {\n\n if(installReceiver == null) {\n installReceiver = new BroadcastReceiver() {\n @Override\n public void onReceive(Context context, Intent intent) {\n instance.trackInstall(context, intent);\n }\n };\n }\n\n IntentFilter intentFilter = new IntentFilter();\n intentFilter.addAction(INSTALL_ACTION);\n context.registerReceiver(installReceiver, intentFilter);\n receiverRegistered = true;\n }\n }\n\n protected void unregisterReceiver(Context context) {\n if(installReceiver != null) {\n try {\n context.unregisterReceiver(installReceiver);\n } catch (Exception ignore) {}\n receiverRegistered = false;\n }\n }\n\n protected void stop(Context context) {\n if (geo != null) {\n geo.onStop(context);\n }\n\n unregisterReceiver(context);\n\n apiClient.stop();\n\n getSession().stop(context);\n }\n\n protected void destroy() {\n instances--;\n if (instances <= 0) {\n instances = 0;\n }\n }\n\n protected void trackInstall(final Context context, Intent intent) {\n\n Bundle extras = intent.getExtras();\n\n if(extras != null) {\n final String referrerString = extras.getString(\"referrer\");\n\n if(!StringUtils.isEmpty(referrerString)) {\n if (Logger.isDebugEnabled()) {\n Logger.d(\"Received install referrer [\" +\n referrerString +\n \"]\");\n }\n\n apiClient.referrer(\n config.getApiKey(),\n config.getApiSecret(), referrerString, new ApiCallback() {\n @Override\n public void onSuccess(JSONObject result) {\n // Just log\n if (Logger.isDebugEnabled()) {\n Logger.d(\"Install referrer recorded\");\n }\n }\n\n @Override\n public void onError(Throwable e) {\n // We couldn't save the referrer, queue for later\n Logger.e(e);\n\n if (getSession().isStarted()) {\n Session session = getSession().waitForStart();\n\n // TODO: Queue referrer for sending later\n session.getState().setReferrer(referrerString);\n session.getState().save(context, null);\n }\n }\n });\n }\n }\n }\n\n protected boolean waitForStart(long timeout) {\n if (startLatch != null) {\n try {\n return startLatch.await(timeout, TimeUnit.MILLISECONDS);\n } catch (InterruptedException ignore) {}\n }\n return false;\n }\n}", "public class LoopyAccess {\n public static Loopy getLoopy() {\n return Loopy.getInstance();\n }\n\n public static ApiClient getApiClient() {\n return Loopy.getInstance().getApiClient();\n }\n\n public static void setApiClient(ApiClient client) {\n Loopy.getInstance().setApiClient(client);\n }\n\n public static void setHttpClientFactory(HttpClientFactory factory) {\n Loopy.getInstance().getApiClient().setHttpClientFactory(factory);\n }\n\n public static void setLoopy(Loopy loopyPrivate) {\n Loopy.setInstance(loopyPrivate);\n }\n\n public static ApiCallback wrapDelay(final ApiCallback callback, final int delay) {\n\n return new ApiCallback() {\n @Override\n public void onSuccess(JSONObject result) {\n callback.onSuccess(result);\n }\n\n @Override\n public void onError(Throwable e) {\n callback.onError(e);\n }\n\n @Override\n public void onProcess(JSONObject result) {\n callback.onProcess(result);\n }\n\n @Override\n public void onBeforePost(Map<String, String> headers, JSONObject payload) {\n\n if(delay > 0) {\n try {\n JSONObject mock = new JSONObject();\n mock.put(\"hang\", delay);\n payload.put(\"mock\", mock);\n }\n catch (JSONException e) {\n e.printStackTrace();\n }\n }\n\n callback.onBeforePost(headers, payload);\n }\n };\n }\n}", "public class LoopyException extends RuntimeException {\n\n private final int code;\n\n public static final int INVALID_PARAMETER = 600;\n public static final int PARAMETER_MISSING = 601;\n public static final int PARSE_ERROR = 602;\n public static final int CLIENT_TIMEOUT = 608;\n\n\n public static final int LIFECYCLE_ERROR = 1000;\n public static final int TIMEOUT = 1001;\n public static final int INTERNAL_ERROR = 1200;\n\n public LoopyException(int code) {\n super();\n this.code = code;\n }\n\n public LoopyException(String detailMessage, int code) {\n super(detailMessage);\n this.code = code;\n }\n\n public LoopyException(String detailMessage, Throwable throwable, int code) {\n super(detailMessage, throwable);\n this.code = code;\n }\n\n public LoopyException(Throwable throwable, int code) {\n super(throwable);\n this.code = code;\n }\n\n public int getCode() {\n return code;\n }\n\n public static LoopyException wrap(Exception e, int code) {\n if(e instanceof LoopyException) {\n return (LoopyException) e;\n }\n return new LoopyException(e, code);\n }\n}", "public class Holder<T> {\n\n\tprivate T object;\n\n private List<T> objects = new ArrayList<T>();\n\n\tpublic Holder() {}\n\n\tpublic Holder(T object) {\n\t\tsuper();\n\t\tthis.object = object;\n\t}\n\n\tpublic T get() {\n\t\treturn object;\n\t}\n\n\tpublic void set(T object) {\n\t\tthis.object = object;\n\t}\n\n public void add(T object) {\n objects.add(object);\n }\n\n public List<T> getObjects() {\n return objects;\n }\n}", "public final class JsonAssert {\n\n private JsonAssert() {}\n\n public static void assertJsonEquals(String name, JSONArray expected, JSONArray actual) throws Exception {\n if (expected.length() != actual.length()) {\n assertEquals(\"Arrays are not of equal length\", expected.toString(), actual.toString());\n }\n\n for (int i = 0; i < expected.length(); ++i) {\n Object expectedValue = expected.opt(i);\n Object actualValue = actual.opt(i);\n assertValueEquals(name, expectedValue, actualValue);\n }\n }\n\n public static void assertJsonEquals(JSONObject expected, JSONObject actual) throws Exception {\n if (expected.length() != actual.length()) {\n\n StringBuilder builder = new StringBuilder();\n Iterator expectedKeys = expected.keys();\n Iterator actualKeys = actual.keys();\n\n builder.append(\"\\n\\nExpected has: \\n\\n\");\n\n while (expectedKeys.hasNext()) {\n builder.append(expectedKeys.next().toString());\n builder.append(\"\\n\");\n }\n\n builder.append(\"\\nActual has: \\n\\n\");\n\n while (actualKeys.hasNext()) {\n builder.append(actualKeys.next().toString());\n builder.append(\"\\n\");\n }\n\n fail(\"Objects are not of equal size.\" + builder.toString());\n }\n\n // Both are empty so skip\n if (expected.names() == null && actual.names() == null) {\n return;\n }\n\n JSONArray names = expected.names();\n List<String> nameList = new ArrayList<String>(names.length());\n\n for (int i = 0; i < names.length(); i++) {\n nameList.add(names.getString(i));\n }\n\n for (String name : nameList) {\n Object expectedValue = expected.opt(name);\n Object actualValue = actual.opt(name);\n assertValueEquals(name, expectedValue, actualValue);\n }\n }\n\n static void assertValueEquals(String name, Object expectedValue, Object actualValue) throws Exception {\n if (expectedValue != null) {\n assertNotNull(\"Value for field \" + name + \" was null but should not have been\", actualValue);\n\n if (expectedValue instanceof JSONObject) {\n assertJsonEquals((JSONObject) expectedValue, (JSONObject) actualValue);\n }\n else if (expectedValue instanceof JSONArray) {\n assertJsonEquals(name, (JSONArray) expectedValue, (JSONArray) actualValue);\n }\n else {\n if(Number.class.isAssignableFrom(expectedValue.getClass())) {\n assertTrue(\"The actual class of \" + name + \" (\" + actualValue.getClass() + \") is not is not a (\" + Number.class + \")\", Number.class.isAssignableFrom(actualValue.getClass()));\n }\n else {\n assertTrue(\"The actual class of \" + name + \" (\" + actualValue.getClass() + \") is not assignable from (\" + expectedValue.getClass() + \")\", actualValue.getClass().isAssignableFrom(expectedValue.getClass()));\n }\n\n assertEquals((\"Value for \" + name + \" was \" + actualValue + \" (\" + actualValue.getClass() + \") but should have been \" + expectedValue + \" (\" + expectedValue.getClass() + \")\"), expectedValue.toString(), actualValue.toString());\n }\n }\n else {\n assertNull(\"Actual value (\" + actualValue + \") was not expected. Expected value for \" + name + \" is null\", actualValue);\n }\n }\n\n public static void assertHasValueAtLocation(JSONObject obj, String path) {\n String[] segments = path.split(\"/\");\n Stack<String> stack = new Stack<String>();\n List<String> tmp = new ArrayList<String>(Arrays.asList(segments));\n Collections.reverse(tmp);\n stack.addAll(tmp);\n\n while(!stack.isEmpty()) {\n String pop = stack.pop();\n assertTrue(\"Object does not contain key \" + pop, obj.has(pop));\n if(!stack.isEmpty()) {\n try {\n obj = obj.getJSONObject(pop);\n }\n catch (JSONException e) {\n e.printStackTrace();\n fail(e.getMessage());\n }\n }\n }\n }\n}" ]
import android.content.Context; import com.sharethis.loopy.sdk.ApiCallback; import com.sharethis.loopy.sdk.ApiClient; import com.sharethis.loopy.sdk.Event; import com.sharethis.loopy.sdk.Item; import com.sharethis.loopy.sdk.Loopy; import com.sharethis.loopy.sdk.LoopyAccess; import com.sharethis.loopy.sdk.LoopyException; import com.sharethis.loopy.test.util.Holder; import com.sharethis.loopy.test.util.JsonAssert; import org.json.JSONObject; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit;
package com.sharethis.loopy.test; /** * tests against the mock API * * @author Jason Polites */ public class ApiClientIntegrationTest extends LoopyAndroidTestCase { ApiClient apiClient; String apiKey = "foobar_api_key"; String apiSecret = "foobar_api_secret"; String stdid = "foobar_stdid"; @Override public void setUp() throws Exception { super.setUp(); Context context = getLocalContext(); Loopy.onCreate(context, apiKey, apiSecret); Loopy.onStart(context); apiClient = LoopyAccess.getApiClient(); // Create a dummy STID apiClient.getState().setStdid("foobar_stdid"); } @Override public void tearDown() throws Exception { Context context = getLocalContext(); Loopy.onStop(context); Loopy.onDestroy(context); super.tearDown(); } public void testInstall() throws Exception { new ApiTestRunner() { @Override
void doApiCall(ApiClient client, ApiCallback callback) {
0
KodeMunkie/imagetozxspec
src/main/java/uk/co/silentsoftware/core/colourstrategy/GigaScreenPaletteStrategy.java
[ "public class OptionsObject {\n\n\tprivate static final Logger log = LoggerFactory.getLogger(OptionsObject.class);\n\t\n\t/**\n\t * The version of preferences\n\t */\n\t@PreferencesField\n\tprivate int prefsVersion = 1;\n\t\n\t/**\n\t * The number of starts this app has had\n\t */\n\t@PreferencesField\n\tprivate int starts = 0;\n\t\n\t/**\n\t * Path to the VLC binary\n\t */\n\t@PreferencesField\n\tprivate String pathToVideoEngineLibrary = null;\n\n\t/**\n\t * The number of frames to sample from the video per second\n\t */\n\t@PreferencesField\n\tprivate volatile double videoFramesPerSecond = 10;\n\n\t/**\n\t * The number of milliseconds delay for each gif frame\n\t */\n\t@PreferencesField\n\tprivate volatile int gifDisplayTimeMillis = 100;\n\n\t/**\n\t * CPU time is diverted more to processing than rendering or other less important tasks\n\t */\n\t@PreferencesField\n\tprivate volatile boolean turboMode = false;\n\n\t/**\n\t * Prefix identifier for custom basic loaders\n\t */\n\tpublic final static String CUSTOM_LOADER_PREFIX = getCaption(\"loader_custom\") + \" \";\n\n\t/**\n\t * Basic loader for slideshows/video (tap output)\n\t */\n\tprivate final List<BasicLoader> basicLoaders;\n\t{\n\t\tbasicLoaders = new ArrayList<>();\n\t\tbasicLoaders.add(new BasicLoader(getCaption(\"loader_simple\"), \"/simple.tap\"));\n\t\tbasicLoaders.add(new BasicLoader(getCaption(\"loader_buffered\"), \"/buffered.tap\"));\n\t\tbasicLoaders.add(new BasicLoader(getCaption(\"loader_gigascreen\"), \"/gigascreen.tap\"));\n\t\tbasicLoaders.add(new BasicLoader(CUSTOM_LOADER_PREFIX, null));\n\t}\n\n\t/**\n\t * The chosen basic loader\n\t */\n\t@PreferencesField\n\tprivate volatile int basicLoader = 0;\n\n\t/**\n\t * Error diffusion dither strategies available\n\t */\n\tprivate final List<ErrorDiffusionDitherStrategy> errorDithers;\n\t{\n\t\terrorDithers = new ArrayList<>();\n\t\terrorDithers.add(new AtkinsonDitherStrategy());\n\t\terrorDithers.add(new BurkesDitherStrategy());\n\t\terrorDithers.add(new FloydSteinbergDitherStrategy());\n\t\terrorDithers.add(new JarvisJudiceNinkeDitherStrategy());\n\t\terrorDithers.add(new LowErrorAtkinsonDitherStrategy());\n\t\terrorDithers.add(new NoDitherStrategy());\n\t\terrorDithers.add(new SierraFilterLightStrategy());\n\t\terrorDithers.add(new StuckiDitherStrategy());\n\t}\n\n\t/**\n\t * Ordered dither strategies available\n\t */\n\tprivate final List<OrderedDitherStrategy> orderedDithers;\n\t{\n\t\torderedDithers = new ArrayList<>();\n\t\torderedDithers.add(new BayerTwoByOneOrderedDitherStrategy());\n\t\torderedDithers.add(new BayerTwoByTwoOrderedDitherStrategy());\n\t\torderedDithers.add(new OmegaOrderedDitherStrategy()); \n\t\torderedDithers.add(new BayerFourByFourDitherStrategy());\n\t\torderedDithers.add(new BayerEightByEightDitherStrategy());\n\t\torderedDithers.add(new MagicSquareDitherStrategy());\n\t\torderedDithers.add(new NasikMagicSquareDitherStrategy());\n\t}\n\n\t/**\n\t * Any non standard dither strategies (e.g character dither)\n\t */\n\tprivate final List<DitherStrategy> otherDithers;\n\t{\n\t\totherDithers = new ArrayList<>();\n\t\totherDithers.add(new CharacterDitherStrategy());\n\t}\n\t\n\t/**\n\t * The chosen dither strategy\n\t */\n\t@PreferencesField\n\tprivate volatile int selectedDitherStrategy = 0;\n\n\t/**\n\t * The chosen dither strategy type\n\t */\n\t@PreferencesField\n\tprivate volatile String selectedDitherStrategyType = ErrorDiffusionDitherStrategy.class.getName();\n\n\tpublic final static ScalingObject INTERLACED = new ScalingObject(getCaption(\"scaling_interlace\"),\n\t\t\tSpectrumDefaults.SCREEN_WIDTH, SpectrumDefaults.SCREEN_HEIGHT*2);\n\n\t/**\n\t * Scaling modes available\n\t */\n\tprivate final List<ScalingObject> scalings;\n\t{\n\t\tscalings = new ArrayList<>();\n\t\tscalings.add(new ScalingObject(getCaption(\"scaling_default\"), SpectrumDefaults.SCREEN_WIDTH, SpectrumDefaults.SCREEN_HEIGHT));\n\t\tscalings.add(INTERLACED);\n\t\tscalings.add(new ScalingObject(getCaption(\"scaling_none\"), -1, -1));\n\t\tscalings.add(new ScalingObject(getCaption(\"scaling_width_prop\"), SpectrumDefaults.SCREEN_WIDTH, -1));\n\t\tscalings.add(new ScalingObject(getCaption(\"scaling_height_prop\"), -1, SpectrumDefaults.SCREEN_HEIGHT));\n\t}\n\n\t/**\n\t * ZX Spectrum scaling mode\n\t */\n\tpublic final ScalingObject zxScaling = scalings.get(0);\t\n\t\n\t/**\n\t * Currently selected scaling mode\n\t */\n\t@PreferencesField\n\tpublic volatile int scaling = 0;\n\n\tpublic static final GigaScreenPaletteStrategy GIGASCREEN_PALETTE_STRATEGY = new GigaScreenPaletteStrategy();\n\n\t/**\n\t * Pixel colouring strategy - akin to screen modes on the Spectrum\n\t * i.e. 2, 15 or 102 colours.\n\t */\n\tprivate final List<ColourChoiceStrategy> colourModes;\n\t{\n\t\tcolourModes = new ArrayList<>();\n\t\tcolourModes.add(new FullPaletteStrategy());\n\t\tcolourModes.add(GIGASCREEN_PALETTE_STRATEGY);\n\t\tcolourModes.add(new MonochromePaletteStrategy());\n\t}\n\n\t/**\n\t * Currently selected pixel colouring strategy\n\t */\n\t@PreferencesField\n\tprivate volatile int colourMode = 0;\n\n\t/**\n\t * Attribute favouritism choice - when colours need to be changed to a two\n\t * colour attribute block of 8x8 what is favoured?\n\t */\n\tprivate final List<AttributeStrategy> attributeModes;\n\t{\n\t\tattributeModes = new ArrayList<>();\n\t\tattributeModes.add(new FavourHalfBrightAttributeStrategy());\n\t\tattributeModes.add(new FavourBrightAttributeStrategy());\n\t\tattributeModes.add(new FavourMostPopularAttributeStrategy());\n\t\tattributeModes.add(new ForceHalfBrightAttributeStrategy()); \n\t\tattributeModes.add(new ForceBrightAttributeStrategy());\n\t\tattributeModes.add(new ForceReducedHalfBrightAttributeStrategy());\n\t};\n\n\t/**\n\t * Currently selected attribute favouritism mode\n\t */\n\t@PreferencesField\n\tprivate volatile int attributeMode = 0;\n\n\t/**\n\t * Attribute favouritism choice for Gigascreen. This is similar to the regular\n\t * attribute modes but needs to take account for the fact that the extra\n\t * colours are created by using two Spectrum screens (e.g. black+white full bright = grey)\n\t */\n\tprivate final List<GigaScreenAttributeStrategy> gigaScreenAttributeModes;\n\t{\n\t\tgigaScreenAttributeModes = new ArrayList<>();\n\t\tgigaScreenAttributeModes.add(new GigaScreenHalfBrightPaletteStrategy());\n\t\tgigaScreenAttributeModes.add(new GigaScreenBrightPaletteStrategy());\n\t\tgigaScreenAttributeModes.add(new GigaScreenMixedPaletteStrategy());\n\t};\n\n\tprivate final List<ColourDistanceStrategy> colourDistancesModes;\n\t{\n\t\tcolourDistancesModes = new ArrayList<>();\n\t\tcolourDistancesModes.add(new CompuphaseColourDistanceStrategy());\n\t\tcolourDistancesModes.add(new ClassicColourDistanceStrategy());\n\t\tcolourDistancesModes.add(new EuclideanColourDistance());\n\t}\n\n\t/**\n\t * Currently selected gigascreen attribute mode\n\t */\n\t@PreferencesField\n\tprivate volatile int gigaScreenAttributeMode = 0;\n\n\t/**\n\t * The chosen giga screen hsb option \n\t */\n\t@PreferencesField\n\tprivate volatile String gigaScreenPaletteOrder = GigaScreenPaletteOrder.Luminosity.name();\n\n\t/**\n\t * The video converting libraries supported\n\t */\n\tprivate final List<VideoImportEngine> videoImportEngines;\n\t{\n\t\tvideoImportEngines = new ArrayList<>();\n\t\tvideoImportEngines.add(new HumbleVideoImportEngine());\n\t\t\n\t\t// VLCJ doesn't work on MacOS.\n\t\tif (SystemUtils.IS_OS_MAC_OSX) {\n\t\t\tlog.info(\"Disabling VLCJ import engine - not supported on OSX\");\n\t\t} else {\n\t\t\tvideoImportEngines.add(new VLCVideoImportEngine());\n\t\t}\n\t};\n\n\t/**\n\t * Currently selected video converter\n\t */\n\t@PreferencesField\n\tprivate volatile int videoImportEngine = 0;\n\n\t/**\n\t * Display frames per second\n\t */\n\t@PreferencesField\n\tprivate volatile boolean fpsCounter = false;\n\n\t/**\n\t * Display frames per second\n\t */\n\t@PreferencesField\n\tprivate volatile boolean showWipPreview = true;\n\n\t/**\n\t * Export image formats available\n\t */\n\tprivate final String[] imageFormats = new String[] { \"png\", \"jpg\" };\n\n\t/**\n\t * Currently selected image export format\n\t */\n\t@PreferencesField\n\tprivate volatile String imageFormat = imageFormats[0];\n\n\t/**\n\t * Image pre-process contrast setting\n\t */\n\t@PreferencesField\n\tprivate volatile float contrast = 1;\n\n\t/**\n\t * Image pre-process brightness setting\n\t */\n\t@PreferencesField\n\tprivate volatile float brightness = 0;\n\n\t/**\n\t * Image pre-process saturation setting\n\t */\n\t@PreferencesField\n\tprivate volatile float saturation = 0;\n\n\t/**\n\t * Monochrome b/w threshold - determines what value a colour rgb values\n\t * must all be below for it to be considered black\n\t */\n\t@PreferencesField\n\tprivate volatile int blackThreshold = 128;\n\n\t/**\n\t * Flag for allowing regular image export\n\t */\n\t@PreferencesField\n\tprivate volatile boolean exportImage = true;\n\n\t/**\n\t * Flag for allowing Spectrum screen file export\n\t */\n\t@PreferencesField\n\tprivate volatile boolean exportScreen = false;\n\n\t/**\n\t * Flag for allowing Spectrum tape (slideshow) file export\n\t */\n\t@PreferencesField\n\tprivate volatile boolean exportTape = false;\n\n\t/**\n\t * Flag to export an anim gif\n\t */\n\t@PreferencesField\n\tprivate volatile boolean exportAnimGif = false;\n\n\t/**\n\t * Flag to export a text dither as a text file\n\t */\n\t@PreferencesField\n\tprivate volatile boolean exportText = false;\n\n\t/**\n\t * The monochrome mode ink colour (spectrum palette index)\n\t */\n\t@PreferencesField\n\tprivate volatile int monochromeInkIndex = 0;\n\n\t/**\n\t * The monochrome mode paper colour (spectrum palette index)\n\t */\n\t@PreferencesField\n\tprivate volatile int monochromePaperIndex = 7;\n\n\t/**\n\t * Intensity for ordered dithering\n\t */\n\t@PreferencesField\n\tprivate volatile int orderedDitherIntensity = 1;\n\n\t/**\n\t * Serpentine dithering mode (image rows traversed \n\t * in alternate directions)\n\t */\n\t@PreferencesField\n\tprivate volatile boolean serpentine = false;\n\n\t/**\n\t * Constrains the error of the error diffusion to \n\t * 8x8 pixels (a single attribute block). Can lead\n\t * to a grid pattern effect.\n\t */\n\t@PreferencesField\n\tprivate volatile boolean constrainedErrorDiffusion = false;\n\n\t/**\n\t * Algorithm to compare colour likeness\n\t */\n\t@PreferencesField\n\tprivate volatile int colourDistanceStrategy = 0;\n\n\t/**\n\t * Singleton instance of this class\n\t */\n\tprivate final static OptionsObject instance;\n\n\tstatic {\n\t\tOptional<OptionsObject> tempRef = PreferencesService.load();\n\t\tif (tempRef.isPresent()) {\n\t\t\tinstance = tempRef.get();\n\t\t} else {\n\t\t\tinstance = new OptionsObject();\n\t\t}\n\t\t// Start this early as some engines take a number of seconds to load\n\t\tinstance.getVideoImportEngine().initVideoImportEngine(Optional.ofNullable(instance.getPathToVideoEngineLibrary()));\n\t\tlog.info(\"Options initialised\");\n\t}\n\t\n\t/**\n\t * Retrieves the only option object instance\n\t * \n\t * @return the singleton instance of this object\n\t */\n\tpublic static OptionsObject getInstance() {\n\t\tif (instance == null) {\n\t\t\tlog.error(\"Options instance is null!\");\n\t\t}\n\t\treturn instance;\n\t}\n\t\n\tpublic int getStarts() {\n\t\treturn starts;\n\t}\n\n\tpublic void setStarts(int starts) {\n\t\tthis.starts = starts;\n\t}\n\n\tpublic void setTurboMode(boolean turbo) {\n\t\tthis.turboMode = turbo;\n\t}\n\t\n\tpublic boolean getTurboMode() {\n\t\treturn turboMode;\n\t}\t\n\t\n\tpublic ErrorDiffusionDitherStrategy[] getErrorDithers() {\n\t\treturn errorDithers.toArray(new ErrorDiffusionDitherStrategy[0]);\n\t}\n\n\tpublic ScalingObject[] getScalings() {\n\t\treturn scalings.toArray(new ScalingObject[0]);\n\t}\n\n\tpublic ScalingObject getScaling() {\n\t\treturn scalings.get(scaling);\n\t}\n\n\tpublic ScalingObject getZXDefaultScaling() {\n\t\treturn zxScaling;\n\t}\n\n\tpublic void setScaling(ScalingObject scaling) {\n\t\tthis.scaling = scalings.indexOf(scaling);\n\t}\n\n\tpublic float getContrast() {\n\t\treturn contrast;\n\t}\n\n\tpublic void setContrast(float contrast) {\n\t\tthis.contrast = contrast;\n\t}\n\n\tpublic float getBrightness() {\n\t\treturn brightness;\n\t}\n\n\tpublic void setBrightness(float brightness) {\n\t\tthis.brightness = brightness;\n\t}\n\n\tpublic float getSaturation() {\n\t\treturn saturation;\n\t}\n\n\tpublic void setSaturation(float saturation) {\n\t\tthis.saturation = saturation;\n\t}\n\n\tpublic void setFpsCounter(boolean fpsCounter) {\n\t\tthis.fpsCounter = fpsCounter;\n\t}\n\n\tpublic void setShowWipPreview(boolean showWipPreview) {\n\t\tthis.showWipPreview = showWipPreview;\n\t}\n\n\tpublic String getImageFormat() {\n\t\treturn imageFormat;\n\t}\n\n\tpublic void setImageFormat(String imageFormat) {\n\t\tthis.imageFormat = imageFormat;\n\t}\n\n\tpublic String[] getImageFormats() {\n\t\treturn imageFormats;\n\t}\n\n\tpublic boolean getFpsCounter() {\n\t\treturn fpsCounter;\n\t}\n\n\tpublic boolean getShowWipPreview() {\n\t\treturn showWipPreview;\n\t}\n\n\tpublic boolean getExportImage() {\n\t\treturn exportImage;\n\t}\n\n\tpublic void setExportImage(boolean exportImage) {\n\t\tthis.exportImage = exportImage;\n\t}\n\n\tpublic boolean getExportScreen() {\n\t\treturn exportScreen;\n\t}\n\n\tpublic void setExportScreen(boolean exportScreen) {\n\t\tthis.exportScreen = exportScreen;\n\t}\n\n\tpublic boolean getExportAnimGif() {\n\t\treturn exportAnimGif;\n\t}\n\n\tpublic void setExportAnimGif(boolean exportAnimGif) {\n\t\tthis.exportAnimGif = exportAnimGif;\n\t}\n\n\tpublic boolean getExportText() {\n\t\treturn exportText;\n\t}\n\n\tpublic void setExportText(boolean exportText) {\n\t\tthis.exportText = exportText;\n\t}\n\n\tpublic boolean getExportTape() {\n\t\treturn exportTape;\n\t}\n\n\tpublic void setExportTape(boolean exportTape) {\n\t\tthis.exportTape = exportTape;\n\t}\n\n\tpublic ColourChoiceStrategy getColourMode() {\n\t\treturn colourModes.get(colourMode);\n\t}\n\n\tpublic void setColourMode(ColourChoiceStrategy colourMode) {\n\t\tthis.colourMode = colourModes.indexOf(colourMode);\n\t}\n\n\tpublic ColourChoiceStrategy[] getColourModes() {\n\t\treturn colourModes.toArray(new ColourChoiceStrategy[0]);\n\t}\n\n\tpublic int getMonochromeInkIndex() {\n\t\treturn monochromeInkIndex;\n\t}\n\n\tpublic void setMonochromeInkIndex(int monochromeInkIndex) {\n\t\tthis.monochromeInkIndex = monochromeInkIndex;\n\t}\n\n\tpublic int getMonochromePaperIndex() {\n\t\treturn monochromePaperIndex;\n\t}\n\n\tpublic void setMonochromePaperIndex(int monochromePaperIndex) {\n\t\tthis.monochromePaperIndex = monochromePaperIndex;\n\t}\n\n\tpublic int getBlackThreshold() {\n\t\treturn blackThreshold;\n\t}\n\n\tpublic void setBlackThreshold(int blackThreshold) {\n\t\tthis.blackThreshold = blackThreshold;\n\t}\n\n\tpublic OrderedDitherStrategy[] getOrderedDithers() {\n\t\treturn orderedDithers.toArray(new OrderedDitherStrategy[0]);\n\t}\n\n\tpublic DitherStrategy[] getOtherDithers() {\n\t\treturn otherDithers.toArray(new DitherStrategy[0]);\n\t}\n\t\n\tpublic DitherStrategy getSelectedDitherStrategy() {\n\t\tif (ErrorDiffusionDitherStrategy.class.getName().equals(selectedDitherStrategyType)) {\n\t\t\treturn errorDithers.get(selectedDitherStrategy);\n\t\t}\n\t\tif (OrderedDitherStrategy.class.getName().equals(selectedDitherStrategyType)) {\n\t\t\treturn orderedDithers.get(selectedDitherStrategy);\n\t\t}\n\t\tif (CharacterDitherStrategy.class.getName().equals(selectedDitherStrategyType)) {\n\t\t\treturn otherDithers.get(selectedDitherStrategy);\n\t\t}\n\t\tthrow new IllegalStateException(\"Unknown dither strategy \"+selectedDitherStrategy);\n\t}\n\n\tpublic void setSelectedDitherStrategy(DitherStrategy selectedDitherStrategy) {\n\t\tif (errorDithers.contains(selectedDitherStrategy)) {\n\t\t\tthis.selectedDitherStrategy = errorDithers.indexOf(selectedDitherStrategy);\n\t\t\tthis.selectedDitherStrategyType = ErrorDiffusionDitherStrategy.class.getName();\n\t\t}\n\t\tif (orderedDithers.contains(selectedDitherStrategy)) {\n\t\t\tthis.selectedDitherStrategy = orderedDithers.indexOf(selectedDitherStrategy);\n\t\t\tthis.selectedDitherStrategyType = OrderedDitherStrategy.class.getName();\n\t\t}\n\t\tif (otherDithers.contains(selectedDitherStrategy)) {\n\t\t\tthis.selectedDitherStrategy = otherDithers.indexOf(selectedDitherStrategy);\n\t\t\tthis.selectedDitherStrategyType = CharacterDitherStrategy.class.getName();\n\t\t}\n\t}\n\n\tpublic int getOrderedDitherIntensity() {\n\t\treturn orderedDitherIntensity;\n\t}\n\n\tpublic void setOrderedDitherIntensity(int orderedDitherIntensity) {\n\t\tthis.orderedDitherIntensity = orderedDitherIntensity;\n\t}\n\n\tpublic AttributeStrategy getAttributeMode() {\n\t\treturn attributeModes.get(attributeMode);\n\t}\n\n\tpublic void setAttributeMode(AttributeStrategy attributeMode) {\n\t\tthis.attributeMode = attributeModes.indexOf(attributeMode);\n\t}\n\n\tpublic AttributeStrategy[] getAttributeModes() {\n\t\treturn attributeModes.toArray(new AttributeStrategy[0]);\n\t}\n\n\tpublic BasicLoader[] getBasicLoaders() {\n\t\treturn basicLoaders.toArray(new BasicLoader[0]);\n\t}\n\n\tpublic BasicLoader getBasicLoader() {\n\t\treturn basicLoaders.get(basicLoader);\n\t}\n\n\tpublic void setBasicLoader(BasicLoader basicLoader) {\n\t\tthis.basicLoader = basicLoaders.indexOf(basicLoader);\n\t}\n\n\tpublic double getVideoFramesPerSecond() {\n\t\treturn videoFramesPerSecond;\n\t}\n\n\tpublic void setVideoFramesPerSecond(double videoFramesPerSecond) {\n\t\tthis.videoFramesPerSecond = videoFramesPerSecond;\n\t}\n\n\tpublic int getGifDisplayTimeMillis() {\n\t\treturn gifDisplayTimeMillis;\n\t}\n\n\tpublic void setGifDisplayTimeMillis(int gifDisplayTimeMillis) {\n\t\tthis.gifDisplayTimeMillis = gifDisplayTimeMillis;\n\t}\n\n\tpublic boolean getSerpentine() {\n\t\treturn serpentine;\n\t}\n\n\tpublic void setSerpentine(boolean serpentine) {\n\t\tthis.serpentine = serpentine;\n\t}\n\n\tpublic boolean getConstrainedErrorDiffusion() {\n\t\treturn constrainedErrorDiffusion;\n\t}\n\n\tpublic void setConstrainedErrorDiffusion(boolean constrainedErrorDiffusion) {\n\t\tthis.constrainedErrorDiffusion = constrainedErrorDiffusion;\n\t}\n\n\tpublic VideoImportEngine getVideoImportEngine() {\n\t\treturn videoImportEngines.get(videoImportEngine);\n\t}\n\n\tpublic void setVideoImportEngine(VideoImportEngine videoImportEngine) {\n\t\tthis.videoImportEngine = videoImportEngines.indexOf(videoImportEngine);\n\t}\n\n\tpublic VideoImportEngine[] getVideoImportEngines() {\n\t\treturn videoImportEngines.toArray(new VideoImportEngine[0]);\n\t}\n\n\tpublic String getPathToVideoEngineLibrary() {\n\t\treturn pathToVideoEngineLibrary;\n\t}\n\n\tpublic void setPathToVideoEngineLibrary(String path) {\n\t\tthis.pathToVideoEngineLibrary = path;\n\t}\n\n\tpublic GigaScreenAttributeStrategy[] getGigaScreenAttributeStrategies() {\n\t\treturn gigaScreenAttributeModes.toArray(new GigaScreenAttributeStrategy[0]);\n\t}\n\n\tpublic GigaScreenAttributeStrategy getGigaScreenAttributeStrategy() {\n\t\treturn gigaScreenAttributeModes.get(gigaScreenAttributeMode);\n\t}\n\n\tpublic void setGigaScreenAttributeStrategy(GigaScreenAttributeStrategy gigaScreenAttributeStrategy) {\n\t\tthis.gigaScreenAttributeMode = gigaScreenAttributeModes.indexOf(gigaScreenAttributeStrategy);\n\t}\n\n\tpublic GigaScreenPaletteOrder[] getGigaScreenPaletteOrders() {\n\t\treturn GigaScreenPaletteOrder.values();\n\t}\n\n\tpublic GigaScreenPaletteOrder getGigaScreenPaletteOrder() {\n\t\treturn GigaScreenPaletteOrder.valueOf(gigaScreenPaletteOrder);\n\t}\n\n\tpublic void setGigaScreenPaletteOrder(GigaScreenPaletteOrder gigaScreenAttributeOrderingOption) {\n\t\tthis.gigaScreenPaletteOrder = gigaScreenAttributeOrderingOption.name();\n\t}\n\n\tpublic ColourDistanceStrategy getColourDistanceMode() {\n\t\treturn colourDistancesModes.get(colourDistanceStrategy);\n\t}\n\n\tpublic ColourDistanceStrategy[] getColourDistances() {\n\t\treturn colourDistancesModes.toArray(new ColourDistanceStrategy[0]);\n\t}\n\n\tpublic void setColourDistanceStrategy(ColourDistanceStrategy colourDistanceStrategy) {\n\t\tthis.colourDistanceStrategy = colourDistancesModes.indexOf(colourDistanceStrategy);\n\t}\n}", "public class SpectrumDefaults {\n\n\tprivate static final int UNIQUE_COLOURS_THRESHOLD = 3;\n\n\t/**\n\t * The size of Spectrum the colour \"blocks\" (8x8 pixels default)\n\t */\n\tpublic static final int ATTRIBUTE_BLOCK_SIZE = 8;\n\t\n\t/**\n\t * The spectrum screen width in pixels\n\t */\n\tpublic static final int SCREEN_WIDTH = 256;\n\t\n\t/**\n\t * The spectrum screen height in pixels\n\t */\n\tpublic static final int SCREEN_HEIGHT = 192;\n\t\n\t/**\n\t * 1/3 of the spectrum screen height in pixels\n\t */\n\tpublic static final int SCREEN_HEIGHT_THIRD = SCREEN_HEIGHT/3;\n\t\n\t/**\n\t * The number of character colour rows\n\t */\n\tpublic static final int ROWS = SCREEN_HEIGHT/ATTRIBUTE_BLOCK_SIZE;\n\t\n\t/**\n\t * The number of character colour columns\n\t */\n\tpublic static final int COLUMNS = SCREEN_WIDTH/ATTRIBUTE_BLOCK_SIZE;\n\n\t/**\n\t * Colours that are grouped on a single screen to reduce inter-attribute flicker\n\t */\n\tpublic static final List<Integer> GIGASCREEN_GROUPED_COLOURS = new ArrayList<>();\n\tstatic {\n\t\tGIGASCREEN_GROUPED_COLOURS.add(0xFF000000); // black\n\t\tGIGASCREEN_GROUPED_COLOURS.add(0xFF00CDCD); // turquiose h\n\t\tGIGASCREEN_GROUPED_COLOURS.add(0xFF00FFFF); // turquiose\n\t\tGIGASCREEN_GROUPED_COLOURS.add(0xFFCD0000); // red h\n\t\tGIGASCREEN_GROUPED_COLOURS.add(0xFFFF0000); // red\n\t\tGIGASCREEN_GROUPED_COLOURS.add(0xFFCD00CD); // magenta h\n\t\tGIGASCREEN_GROUPED_COLOURS.add(0xFFFF00FF); // magenta\n\t}\n\n\t/**\n\t * Spectrum's full bright colour set\n\t */\n\tpublic static final int[] SPECTRUM_COLOURS_BRIGHT;\n\n\tstatic {\n\t\tSPECTRUM_COLOURS_BRIGHT = new int[] {\n\t\t\t0xFF000000,\n\t\t\t0xFF0000FF, \t\n\t\t\t0xFFFF0000, \t\n\t\t\t0xFFFF00FF,\n\t\t\t0xFF00FF00, \t\n\t\t\t0xFF00FFFF,\n\t\t\t0xFFFFFF00, \n\t\t\t0xFFFFFFFF\n\t\t};\n\t}\n\t/**\n\t * Spectrum's half bright colour set\n\t */\n\tpublic static final int[] SPECTRUM_COLOURS_HALF_BRIGHT;\n\tstatic {\n\t\tSPECTRUM_COLOURS_HALF_BRIGHT = new int[] {\n\t\t0xFF000000,\n\t\t0xFF0000CD,\t\n\t\t0xFFCD0000,\n\t\t0xFFCD00CD,\n\t\t0xFF00CD00, \t\n\t\t0xFF00CDCD,\n\t\t0xFFCDCD00,\n\t\t0xFFCDCDCD\n\t\t};\n\t}\n\t\n\t/**\n\t * Spectrum's primary colours minus magenta and teal (makes for a less gawdy image)\n\t */\n\tpublic static final int[] SPECTRUM_COLOURS_REDUCED_HALF_BRIGHT;\n\tstatic {\n\t\tSPECTRUM_COLOURS_REDUCED_HALF_BRIGHT = new int[] {\n\t\t0xFF000000,\n\t\t0xFF0000CD,\t\n\t\t0xFFCD0000,\n\t\t0xFF00CD00, \t\n\t\t0xFFCDCD00,\n\t\t0xFFCDCDCD\n\t\t};\n\t}\n\t\n\t/**\n\t * All Spectrum colours\n\t */\n\tpublic static final int[] SPECTRUM_COLOURS_ALL;\n\tstatic {\n\t\tSPECTRUM_COLOURS_ALL= new int[] {\n\t\t0xFF000000,\n\t\t0xFF0000CD,\n\t\t0xFF0000FF,\n\t\t0xFFCD0000,\n\t\t0xFFFF0000,\t\n\t\t0xFFCD00CD,\n\t\t0xFFFF00FF,\n\t\t0xFF00CD00, \n\t\t0xFF00FF00,\n\t\t0xFF00CDCD,\n\t\t0xFF00FFFF,\n\t\t0xFFCDCD00,\n\t\t0xFFFFFF00, \n\t\t0xFFCDCDCD,\n\t\t0xFFFFFFFF\n\t\t};\n\t}\n\t\t\n\t/**\n\t * The GigaScreen persistence of vision colours generated by flashing two screens.\n\t */\n\tpublic static final int[] GIGASCREEN_COLOURS_ALL;\n\tstatic {\n\t\tGIGASCREEN_COLOURS_ALL = new int[] {\n\t\t\t\t0xff000000,\n\t\t\t\t0xff006600,\n\t\t\t\t0xff000066,\n\t\t\t\t0xff660000,\n\t\t\t\t0xff7f0000,\n\t\t\t\t0xff00007f,\n\t\t\t\t0xff007f00,\n\t\t\t\t0xff006666,\n\t\t\t\t0xff666600,\n\t\t\t\t0xff660066,\n\t\t\t\t0xff0000cd,\n\t\t\t\t0xff00cd00,\n\t\t\t\t0xffcd0000,\n\t\t\t\t0xff7f0066,\n\t\t\t\t0xff00667f,\n\t\t\t\t0xff007f66,\n\t\t\t\t0xff7f6600,\n\t\t\t\t0xff66007f,\n\t\t\t\t0xff667f00,\n\t\t\t\t0xff0000e6,\n\t\t\t\t0xff00e600,\n\t\t\t\t0xffe60000,\n\t\t\t\t0xff7f007f,\n\t\t\t\t0xff7f7f00,\n\t\t\t\t0xff007f7f,\n\t\t\t\t0xff0000ff,\n\t\t\t\t0xffff0000,\n\t\t\t\t0xff00ff00,\n\t\t\t\t0xff666666,\n\t\t\t\t0xff6600cd,\n\t\t\t\t0xffcd6600,\n\t\t\t\t0xffcd0066,\n\t\t\t\t0xff0066cd,\n\t\t\t\t0xff66cd00,\n\t\t\t\t0xff00cd66,\n\t\t\t\t0xff66667f,\n\t\t\t\t0xff667f66,\n\t\t\t\t0xff7f6666,\n\t\t\t\t0xffe60066,\n\t\t\t\t0xff6600e6,\n\t\t\t\t0xff00e666,\n\t\t\t\t0xff66e600,\n\t\t\t\t0xff0066e6,\n\t\t\t\t0xffe66600,\n\t\t\t\t0xff7f7f66,\n\t\t\t\t0xff667f7f,\n\t\t\t\t0xff7f667f,\n\t\t\t\t0xff007fe6,\n\t\t\t\t0xffe6007f,\n\t\t\t\t0xff00e67f,\n\t\t\t\t0xffe67f00,\n\t\t\t\t0xff7f00e6,\n\t\t\t\t0xff7fe600,\n\t\t\t\t0xff7f7f7f,\n\t\t\t\t0xff007fff,\n\t\t\t\t0xff7fff00,\n\t\t\t\t0xff7f00ff,\n\t\t\t\t0xff00ff7f,\n\t\t\t\t0xffff007f,\n\t\t\t\t0xffff7f00,\n\t\t\t\t0xffcd6666,\n\t\t\t\t0xff6666cd,\n\t\t\t\t0xff66cd66,\n\t\t\t\t0xffcd00cd,\n\t\t\t\t0xff00cdcd,\n\t\t\t\t0xffcdcd00,\n\t\t\t\t0xff66e666,\n\t\t\t\t0xffe66666,\n\t\t\t\t0xff6666e6,\n\t\t\t\t0xffe67f66,\n\t\t\t\t0xff667fe6,\n\t\t\t\t0xff66e67f,\n\t\t\t\t0xff7f66e6,\n\t\t\t\t0xff7fe666,\n\t\t\t\t0xffe6667f,\n\t\t\t\t0xffe600e6,\n\t\t\t\t0xff00e6e6,\n\t\t\t\t0xffe6e600,\n\t\t\t\t0xffe67f7f,\n\t\t\t\t0xff7f7fe6,\n\t\t\t\t0xff7fe67f,\n\t\t\t\t0xff7fff7f,\n\t\t\t\t0xff7f7fff,\n\t\t\t\t0xffff7f7f,\n\t\t\t\t0xff00ffff,\n\t\t\t\t0xffff00ff,\n\t\t\t\t0xffffff00,\n\t\t\t\t0xff66cdcd,\n\t\t\t\t0xffcd66cd,\n\t\t\t\t0xffcdcd66,\n\t\t\t\t0xffe666e6,\n\t\t\t\t0xffe6e666,\n\t\t\t\t0xff66e6e6,\n\t\t\t\t0xff7fe6e6,\n\t\t\t\t0xffe67fe6,\n\t\t\t\t0xffe6e67f,\n\t\t\t\t0xffcdcdcd,\n\t\t\t\t0xffff7fff,\n\t\t\t\t0xff7fffff,\n\t\t\t\t0xffffff7f,\n\t\t\t\t0xffe6e6e6,\n\t\t\t\t0xffffffff\n\t\t};\n\t}\n\t\n\t/**\n\t * The GigaScreen combinations of 4 base Spectrum colours generated by \n\t * calculating half bright screen 1 colours x half bright screen 2 colours \n\t */\n\tpublic static final GigaScreenAttribute[] GIGASCREEN_HALF_BRIGHT_ATTRIBUTES;\n\tstatic {\n\t\tGIGASCREEN_HALF_BRIGHT_ATTRIBUTES = SpectrumDefaults.generateGigascreenAttributes(SPECTRUM_COLOURS_HALF_BRIGHT, SPECTRUM_COLOURS_HALF_BRIGHT);\n\t}\n\t\n\t/**\n\t * The GigaScreen combinations of 4 base Spectrum colours generated by \n\t * calculating half bright screen 1 colours x full bright screen 2 colours \n\t */\n\tpublic static final GigaScreenAttribute[] GIGASCREEN_MIXED_ATTRIBUTES;\n\tstatic {\n\t\tGIGASCREEN_MIXED_ATTRIBUTES = SpectrumDefaults.generateGigascreenAttributes(SPECTRUM_COLOURS_HALF_BRIGHT, SPECTRUM_COLOURS_BRIGHT);\n\t}\n\t\n\t/**\n\t * The GigaScreen combinations of 4 base Spectrum colours generated by \n\t * calculating full bright screen 1 colours x full bright screen 2 colours \n\t */\n\tpublic static final GigaScreenAttribute[] GIGASCREEN_BRIGHT_ATTRIBUTES;\n\tstatic {\t\n\t\tGIGASCREEN_BRIGHT_ATTRIBUTES = SpectrumDefaults.generateGigascreenAttributes(SPECTRUM_COLOURS_BRIGHT, SPECTRUM_COLOURS_BRIGHT);\n\t}\n\t\n\t/**\n\t * Mappings from RGB to ZX Spectrum palette\n\t */\n\tpublic static final Map<Integer, Integer> SPECTRUM_ARGB = new HashMap<>(15);\n\tstatic {\n\t\tSPECTRUM_ARGB.put(0xFF000000, 0);\n\t\tSPECTRUM_ARGB.put(0xFF0000CD, 1); SPECTRUM_ARGB.put(0xFF0000FF, 8);\n\t\tSPECTRUM_ARGB.put(0xFFCD0000, 2); SPECTRUM_ARGB.put(0xFFFF0000, 9);\n\t\tSPECTRUM_ARGB.put(0xFFCD00CD, 3); SPECTRUM_ARGB.put(0xFFFF00FF, 10);\n\t\tSPECTRUM_ARGB.put(0xFF00CD00, 4); SPECTRUM_ARGB.put(0xFF00FF00, 11);\n\t\tSPECTRUM_ARGB.put(0xFF00CDCD, 5); SPECTRUM_ARGB.put(0xFF00FFFF, 12);\n\t\tSPECTRUM_ARGB.put(0xFFCDCD00, 6); SPECTRUM_ARGB.put(0xFFFFFF00, 13);\n\t\tSPECTRUM_ARGB.put(0xFFCDCDCD, 7); SPECTRUM_ARGB.put(0xFFFFFFFF, 14);\n\t}\n\t\n\t/**\n\t * Mappings from RGB to Color (caching common colours for use in UI only)\n\t */\n\tpublic static final Map<Integer, Color> SPECTRUM_COLORS = new HashMap<>(15);\n\tstatic {\n\t\tSPECTRUM_COLORS.put(0xFF000000, new Color(0xFF000000));\n\t\tSPECTRUM_COLORS.put(0xFF0000CD, new Color(0xFF0000CD)); SPECTRUM_COLORS.put(0xFF0000FF, new Color(0xFF0000FF));\n\t\tSPECTRUM_COLORS.put(0xFFCD0000, new Color(0xFFCD0000)); SPECTRUM_COLORS.put(0xFFFF0000, new Color(0xFFFF0000));\n\t\tSPECTRUM_COLORS.put(0xFFCD00CD, new Color(0xFFCD00CD)); SPECTRUM_COLORS.put(0xFFFF00FF, new Color(0xFFFF00FF));\n\t\tSPECTRUM_COLORS.put(0xFF00CD00, new Color(0xFF00CD00)); SPECTRUM_COLORS.put(0xFF00FF00, new Color(0xFF00FF00));\n\t\tSPECTRUM_COLORS.put(0xFF00CDCD, new Color(0xFF00CDCD)); SPECTRUM_COLORS.put(0xFF00FFFF, new Color(0xFF00FFFF));\n\t\tSPECTRUM_COLORS.put(0xFFCDCD00, new Color(0xFFCDCD00)); SPECTRUM_COLORS.put(0xFFFFFF00, new Color(0xFFFFFF00));\n\t\tSPECTRUM_COLORS.put(0xFFCDCDCD, new Color(0xFFCDCDCD)); SPECTRUM_COLORS.put(0xFFFFFFFF, new Color(0xFFFFFFFF));\n\t}\n\t\n\t/**\n\t * Utility method to generate gigascreen 4 colour combinations from two palettes (bright and half bright)\n\t * \n\t * @param palette1 the palette from screen number 1\n\t * @param palette2 the palette from screen number 2\n\t * @return a gigascreen attribute object representing the combination of both palettes and it's real 32 bit palette colour\n\t */\n\tpublic static GigaScreenAttribute[] generateGigascreenAttributes(int[] palette1, int[] palette2) {\n\t\tSet<GigaScreenAttribute> combos = new HashSet<>();\n\t\tfor (int inkScreen1 : palette1) {\n\t\t\tfor (int paperScreen1 : palette1) {\t\n\t\t\t\tfor (int inkScreen2 : palette2) {\n\t\t\t\t\tfor (int paperScreen2 : palette2) {\t\n\t\t\t\t\t\tGigaScreenAttribute gc = new GigaScreenAttribute(inkScreen1, paperScreen1, inkScreen2, paperScreen2);\n\t\t\t\t\t\t\n\t\t\t\t\t\t// Only use those attributes that have 3+ colours otherwise we don't get\n\t\t\t\t\t\t// maximum benefit from this screenmode\n\t\t\t\t\t\t// Nb. used to be 4 colour threshold however colour quantisation/distance/attribute calcuations\n\t\t\t\t\t\t// seem to benefit where very same colours appear multiple times within 8x8 pixels (this is\n\t\t\t\t\t\t// subjective however I think it's important enough to adjust).\n\t\t\t\t\t\tif (gc.getUniqueColourCount() >= UNIQUE_COLOURS_THRESHOLD) {\n\t\t\t\t\t\t\tcombos.add(gc);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn combos.toArray(new GigaScreenAttribute[]{});\n\t}\n}", "public interface GigaScreenAttributeStrategy {\n\n\t/**\n\t * Retrieves the GigaScreenAttribute which represents a Spectrum\n\t * attribute block and the possible 4 colours that can be displayed\n\t * in it in Gigascreen mode. \n\t * e.g both screen brights would be one strategy.\n\t * \n\t * @return the gigascreenattribute's palette\n\t */\n\tGigaScreenAttribute[] getPalette();\n}", "public class GigaScreenAttribute {\n\n\t// The actual Gigascreen 32 bit palette representing up to 4 colours\n\tprivate int[] palette;\n\n\t// The array storing the Gigascreen colours' composite parts (Spectrum\n\t// colour for each screen, separate RGB values)\n\tprivate GigaScreenColour[] gigaScreenColours = new GigaScreenColour[4];\n\tprivate int uniqueColourCount;\n\tprivate String uniqueHash = StringUtils.EMPTY;\n\n\t/**\n\t * Constructor for a GigaScreenAttribute\n\t * \n\t * @param inkScreen1 the rgb colour for the ink on screen 1\n\t * @param paperScreen1 the rgb colour for the paper on screen 1\n\t * @param inkScreen2 the rgb colour for the ink on screen 2\n\t * @param paperScreen2 the rgb colour for the paper on screen 2\n\t */\n\tpublic GigaScreenAttribute(int inkScreen1, int paperScreen1, int inkScreen2, int paperScreen2) {\n\t\tgigaScreenColours[0] = new GigaScreenColour(inkScreen1, inkScreen2);\n\t\tgigaScreenColours[1] = new GigaScreenColour(inkScreen1, paperScreen2);\n\t\tgigaScreenColours[2] = new GigaScreenColour(paperScreen1, inkScreen2);\n\t\tgigaScreenColours[3] = new GigaScreenColour(paperScreen1, paperScreen2);\n\n\t\t// Build an ordered set\n\t\tSet<Integer> uniqueColours = new TreeSet<>();\n\t\tuniqueColours.add(gigaScreenColours[0].gigascreenColour);\n\t\tuniqueColours.add(gigaScreenColours[1].gigascreenColour);\n\t\tuniqueColours.add(gigaScreenColours[2].gigascreenColour);\n\t\tuniqueColours.add(gigaScreenColours[3].gigascreenColour);\n\t\tuniqueColourCount = uniqueColours.size();\n\n\t\tpalette = new int[] { gigaScreenColours[0].gigascreenColour, gigaScreenColours[1].gigascreenColour, gigaScreenColours[2].gigascreenColour,\n\t\t\t\tgigaScreenColours[3].gigascreenColour};\n\n\t\tfor (Integer uniqueColour : uniqueColours) {\n\t\t\t// Builds a string, not an integer\n\t\t\tuniqueHash += uniqueColour;\n\t\t}\n\t}\n\n\tpublic int[] getPalette() {\n\t\treturn palette;\n\t}\n\n\t/**\n\t * Calculate how close a match this attribute set of 4 colours compares to\n\t * the provided attribute block. Lower is better.\n\t * \n\t * @param attributeBlock the sample block to compare against this attribute\n\t * @return the score in range >= 0\n\t */\n\t public double getScoreForAttributeBlock(int[] attributeBlock) {\n\t\tdouble totalDistance = 0;\n\t\tfor (int pixel : attributeBlock) {\n\t\t\tint[] components = ColourHelper.intToRgbComponents(pixel);\n\t\t\tdouble distance = ColourHelper.getClosestColourDistanceForGigascreenColours(components[0], components[1], components[2], gigaScreenColours);\n\t\t\ttotalDistance += distance;\n\t\t}\n\t\treturn totalDistance;\n\t}\n\n\tpublic int getUniqueColourCount() {\n\t\treturn uniqueColourCount;\n\t}\n\n\tpublic GigaScreenColour getGigaScreenColour(int index) {\n\t\treturn gigaScreenColours[index];\n\t}\n\n\t/**\n\t * Representation of an attribute block across two screens i.e. a gigascreen\n\t * colour and the two base Spectrum colours (one colour per screen).\n\t */\n\tpublic class GigaScreenColour {\n\n\t\tprivate int gigascreenColour;\n\t\tprivate int[] gigascreenColourRGB;\n\t\tprivate int screen1Colour;\n\t\tprivate int screen2Colour;\n\n\t\tGigaScreenColour(int screen1Colour, int screen2Colour) {\n\t\t\tthis.screen1Colour = screen1Colour;\n\t\t\tthis.screen2Colour = screen2Colour;\n\n\t\t\tint[] rgbS1 = ColourHelper.intToRgbComponents(screen1Colour);\n\t\t\tint[] rgbS2 = ColourHelper.intToRgbComponents(screen2Colour);\n\t\t\tgigascreenColour = ColourHelper.componentsToAlphaRgb(\n\t\t\t\t\t(int)(((long)rgbS1[0] + (long)rgbS2[0]) / 2l),\n\t\t\t\t\t(int)(((long)rgbS1[1] + (long)rgbS2[1]) / 2l),\n\t\t\t\t\t(int)(((long)rgbS1[2] + (long)rgbS2[2]) / 2l));\n\t\t\tgigascreenColourRGB = ColourHelper.intToRgbComponents(gigascreenColour);\n\t\t}\n\n\t\tpublic int[] getGigascreenColourRGB() {\n\t\t\treturn gigascreenColourRGB;\n\t\t}\n\n\t\tpublic int getGigascreenColour() {\n\t\t\treturn gigascreenColour;\n\t\t}\n\n\t\tint getScreen1Colour() {\n\t\t\treturn screen1Colour;\n\t\t}\n\n\t\tint getScreen2Colour() {\n\t\t\treturn screen2Colour;\n\t\t}\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + uniqueHash.hashCode();\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tGigaScreenAttribute other = (GigaScreenAttribute) obj;\n\t\treturn uniqueHash.equals(other.uniqueHash);\n\t}\n}", "public final class ColourHelper {\n\n\tprivate static final int MAXIMUM_COMPONENT_VALUE = 255;\n\n\tprivate static final int PREFER_DETAIL_COMPONENT_BOUNDARY = 127;\n\n\tprivate static final int CACHE_TIME_SECONDS = 10;\n\n\tprivate static final Cache<String, GigaScreenAttribute.GigaScreenColour> CACHE = Caffeine.newBuilder().expireAfterAccess(CACHE_TIME_SECONDS, TimeUnit.SECONDS).build();\n\n\tprivate static final Cache<String, int[]> AVERAGE_CACHE = Caffeine.newBuilder().expireAfterAccess(CACHE_TIME_SECONDS, TimeUnit.SECONDS).build();\n\n\n\t/**\n\t * Private constructor since we want static use only\n\t */\n\tprivate ColourHelper(){}\n\n\t/**\n\t * Gets the closest colour in the mostPopularRgbColours for the provided rgb components\n\t *\n\t * @param originalAlphaRgb the original rgb to find the closest colour for\n\t * @return the closest colour\n\t */\n\tpublic static int getClosestColour(int originalAlphaRgb, int[] colourSet) {\n\n\t\t// Break the colours into their RGB components\n\t\tint[] originalRgbComps = ColourHelper.intToRgbComponents(originalAlphaRgb);\n\t\treturn ColourHelper.getClosestColour(originalRgbComps[0], originalRgbComps[1], originalRgbComps[2], colourSet);\n\t}\n\n\t/**\n\t * Gets the closest colour in the colourset for the provided rgb components\n\t *\n\t * @param red the red component\n\t * @param green the green component\n\t * @param blue the blue component\n\t * @param colourSet the colours to search\n\t * @return the closest colour\n\t */\n\tprivate static int getClosestColour(int red, int green, int blue, int[] colourSet) {\n\t\tdouble bestMatch = Double.MAX_VALUE;\n\t\tInteger closest = null;\n\t\tfor (int colour : colourSet) {\n\t\t\tfinal int[] colourSetComps = intToRgbComponents(colour);\n\t\t\tdouble diff = OptionsObject.getInstance().getColourDistanceMode().getColourDistance(red, green, blue, colourSetComps);\n\t\t\tif (diff < bestMatch) {\n\t\t\t\tclosest = colour;\n\t\t\t\tbestMatch = diff;\n\t\t\t}\n\t\t}\n\t\treturn closest;\n\t}\n\n\t/**\n\t * Gets the closest colour distance from the gigascreen colours for the rgb components\n\t *\n\t * @param red the red component\n\t * @param green the green component\n\t * @param blue the blue component\n\t * @param colours the gigascreen colours to search\n\t * @return the difference as a value greater than or equal to 0\n\t */\n\tpublic static double getClosestColourDistanceForGigascreenColours(int red, int green, int blue, GigaScreenColour[] colours) {\n\t\tdouble bestMatch = Double.MAX_VALUE;\n\t\tfor (GigaScreenColour colour : colours) {\n\t\t\tfinal int[] paletteComps = colour.getGigascreenColourRGB();\n\t\t\tdouble diff = OptionsObject.getInstance().getColourDistanceMode().getColourDistance(red, green, blue, paletteComps);\n\t\t\tbestMatch = Math.min(diff, bestMatch);\n\t\t}\n\t\treturn bestMatch;\n\t}\n\n\t/**\n\t * Gets the closest Gigascreen colour from a GigaScreenAttribute\n\t *\n\t * @param rgb the rgb value to find the closest gigascreen colour for\n\t * @param colourSet the attribute containing the colours\n\t * @return the closest matching giga screen colour\n\t */\n\tpublic static GigaScreenAttribute.GigaScreenColour getClosestGigaScreenColour(int rgb, GigaScreenAttribute colourSet) {\n\t\tString key = getClosestKey(rgb, colourSet, OptionsObject.getInstance().getGigaScreenAttributeStrategy());\n\t\tGigaScreenAttribute.GigaScreenColour cachedColour = CACHE.getIfPresent(key);\n\t\tif (cachedColour != null) {\n\t\t\treturn cachedColour;\n\t\t}\n\t\tfinal int[] comps = ColourHelper.intToRgbComponents(rgb);\n\t\tdouble bestMatch = Double.MAX_VALUE;\n\t\tInteger closestMatchPaletteIndex = null;\n\t\tint[] palette = colourSet.getPalette();\n\t\tfor (int paletteIndex = 0; paletteIndex < palette.length; ++paletteIndex) {\n\t\t\tint colour = palette[paletteIndex];\n\t\t\tfinal int[] colourSetComps = ColourHelper.intToRgbComponents(colour);\n\t\t\tdouble diff = OptionsObject.getInstance().getColourDistanceMode().getColourDistance(comps[0], comps[1], comps[2], colourSetComps);\n\t\t\tif (diff < bestMatch) {\n\t\t\t\tclosestMatchPaletteIndex = paletteIndex;\n\t\t\t\tbestMatch = diff;\n\t\t\t}\n\t\t}\n\t\tGigaScreenColour colour = colourSet.getGigaScreenColour(closestMatchPaletteIndex);\n\t\tCACHE.put(key, colour);\n\t\treturn colour;\n\t}\n\n\t/**\n\t * Calculates the luminosity total for a set of rgb values\n\t * based on the NTSC formula Y = 0.299*r + 0.587*g + 0.114*b.\n\t *\n\t * @param rgbVals the rgb value sets\n\t * @return the luminosity sum\n\t */\n\tpublic static float luminositySum(int[] rgbVals) {\n\t\tfloat sum = 0;\n\t\tfor (int rgb : rgbVals) {\n\t\t\tint[] rgbComponents = ColourHelper.intToRgbComponents(rgb);\n\t\t\tsum += luminosity(rgbComponents[0], rgbComponents[1], rgbComponents[2]);\n\t\t}\n\t\treturn sum;\n\t}\n\n\tprivate static float luminosity(int red, int green, int blue) {\n\t\treturn (float)((0.299 * red) + (0.587 * green) + (0.114 * blue));\n\t}\n\n\t/**\n\t * Calculates the average distance between colour components in the given palette\n\t * @param palette to calculate the average distance from\n\t * @return the rgb component average distances\n\t */\n\tpublic static int[] getAverageColourDistance(int[] palette) {\n\t\tString key = getAverageKey(palette);\n\t\tint[] result = AVERAGE_CACHE.getIfPresent(key);\n\t\tif (result != null) {\n\t\t\treturn result;\n\t\t}\n\t\tint rollingAverageRed = 0;\n\t\tint rollingAverageGreen = 0;\n\t\tint rollingAverageBlue = 0;\n\t\tfor (int i=0; i<palette.length; ++i) {\n\t\t\tint[] rgbComponents = ColourHelper.intToRgbComponents(palette[i]);\n\n\t\t\tfor (int j=0; j<palette.length; ++j) {\n\t\t\t\tif (j == i) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tint[] rgbComponents2 = ColourHelper.intToRgbComponents(palette[j]);\n\t\t\t\tint redDiff = Math.abs(rgbComponents2[0]-rgbComponents[0]);\n\t\t\t\tint greenDiff = Math.abs(rgbComponents2[1]-rgbComponents[1]);\n\t\t\t\tint blueDiff = Math.abs(rgbComponents2[2]-rgbComponents[2]);\n\t\t\t\trollingAverageRed += redDiff;\n\t\t\t\trollingAverageGreen += greenDiff;\n\t\t\t\trollingAverageBlue += blueDiff;\n\t\t\t}\n\t\t}\n\t\trollingAverageRed = Math.round((float)rollingAverageRed/(float)(palette.length*palette.length));\n\t\trollingAverageGreen = Math.round((float)rollingAverageGreen/(float)(palette.length*palette.length));\n\t\trollingAverageBlue = Math.round((float)rollingAverageBlue/(float)(palette.length*palette.length));\n\t\tresult = new int[]{rollingAverageRed, rollingAverageGreen, rollingAverageBlue};\n\t\tAVERAGE_CACHE.put(key, result);\n\t\treturn result;\n\t}\n\n\t/**\n\t * Colours an entire image using the given colourstrategy based on the\n\t * original and output images. Colours the Spectrum attribute blocks by\n\t * selecting xMax by yMax parts of the output image (i.e. usually 8x8\n\t * pixels), chooses the most popular two colours. The colour choice strategy\n\t * then decides how to colour individual pixels based on these two colours.\n\t * \n\t * Note it is expected that this method will be called AFTER the pixels have\n\t * been changed to Spectrum colours.\n\t * \n\t * @param image the image to colour\n\t * @param colourChoiceStrategy the colour choice strategy\n\t * @return the modified image\n\t */\n\tpublic static BufferedImage colourAttributes(BufferedImage image, ColourChoiceStrategy colourChoiceStrategy) {\n\n\t\t// Do not use bidimap because inverse map key values will be lost (i.e. many tallies will produce same key)\t\n\t\tMap<Integer, Integer> map = new HashMap<>();\n\t\tList<TallyValue> tallyValues = new LinkedList<>();\n\t\t\n\t\t// Analyse block and choose the two most popular colours in attribute block\n\t\tfor (int y = 0; y + ATTRIBUTE_BLOCK_SIZE <= image.getHeight(); y += ATTRIBUTE_BLOCK_SIZE) {\n\t\t\tfor (int x = 0; x + ATTRIBUTE_BLOCK_SIZE <= image.getWidth() && y + ATTRIBUTE_BLOCK_SIZE <= image.getHeight(); x += ATTRIBUTE_BLOCK_SIZE) {\n\t\t\t\tmap.clear();\n\t\t\t\ttallyValues.clear();\n\t\t\t\tint outRgb[] = image.getRGB(x, y, ATTRIBUTE_BLOCK_SIZE, ATTRIBUTE_BLOCK_SIZE, null, 0, ATTRIBUTE_BLOCK_SIZE);\n\n\t\t\t\tfor (int rgb : outRgb) {\n\t\t\t\t\tfinal int[] comps = intToRgbComponents(rgb);\n\t\t\t\t\tint value = getClosestColour(comps[0], comps[1], comps[2], SpectrumDefaults.SPECTRUM_COLOURS_ALL);\n\t\t\t\t\tint count = 1;\n\t\t\t\t\tif (map.containsKey(value)) {\n\t\t\t\t\t\tcount = map.get(value) + 1;\n\t\t\t\t\t}\n\t\t\t\t\tmap.put(value, count);\n\t\t\t\t}\n\t\t\t\tmap.keySet().stream().forEach(colour -> {\n\t\t\t\t\tInteger tally = map.get(colour);\n\t\t\t\t\ttallyValues.add(new TallyValue(colour, tally));\n\t\t\t\t});\n\t\t\t\ttallyValues.sort(TallyValue.TALLY_COMPARATOR);\n\t\t\t\t\n\t\t\t\tint mostPopularColour = tallyValues.get(0).getColour();\n\t\t\t\tint secondMostPopularColour = tallyValues.size()>1?tallyValues.get(1).getColour():mostPopularColour;\n\t\t\t\t\n\t\t\t\t// Enforce attribute favouritism rules on the two spectrum\n\t\t\t\t// attribute colours (fixes the problem that colours could be from both the bright\n\t\t\t\t// and half bright set).\n\t\t\t\tint[] correctedAlphaColours = OptionsObject.getInstance().getAttributeMode().enforceAttributeRule(mostPopularColour, secondMostPopularColour);\n\t\t\t\t\t\t\t\n\t\t\t\t// Replace all colours in attribute block (which can be any spectrum colours) with the just the popular two\n\t\t\t\tfor (int i = 0; i < outRgb.length; ++i) {\n\t\t\t\t\toutRgb[i] = colourChoiceStrategy.chooseBestPaletteMatch(outRgb[i], correctedAlphaColours);\n\t\t\t\t}\n\t\t\t\timage.setRGB(x, y, ATTRIBUTE_BLOCK_SIZE, ATTRIBUTE_BLOCK_SIZE, outRgb, 0, ATTRIBUTE_BLOCK_SIZE);\n\t\t\t}\n\t\t}\n\t\treturn image;\n\t}\n\n\t/**\n\t * Determines whether the colour is from the Spectrum's bright or half\n\t * bright colour set.\n\t * \n\t * @param rgb the colour to test\n\t * @return whether this colour is in the bright set\n\t */\n\tpublic static boolean isBrightSet(int rgb) {\n\t\tif (rgb == 0xFF000000) {\n\t\t\treturn false;\n\t\t}\n\t\tfor (int i = 0; i < SpectrumDefaults.SPECTRUM_COLOURS_BRIGHT.length; ++i) {\n\t\t\tint def = SpectrumDefaults.SPECTRUM_COLOURS_BRIGHT[i];\n\t\t\tif (def == rgb) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Changes the contrast of an image\n\t * \n\t * @see java.awt.image.RescaleOp\n\t * \n\t * @param img the image to change the contrast of\n\t * @param amount the amount to change it (scale factor)\n\t * @return the modified image\n\t */\n\tpublic static BufferedImage changeContrast(BufferedImage img, float amount) {\n\t\tif (amount == 1) {\n\t\t\treturn img;\n\t\t}\n\t\tRescaleOp rescaleOp = new RescaleOp(amount, 0, null);\n\t\treturn rescaleOp.filter(img, null);\n\t}\n\n\t/**\n\t * Changes brightness by increasing all pixel values by a given amount\n\t * \n\t * @see java.awt.image.RescaleOp\n\t * \n\t * @param img the image to change the brightness of\n\t * @param amount the amount to change it\n\t * @return the modified image\n\t */\n\tpublic static BufferedImage changeBrightness(BufferedImage img, float amount) {\n\t\tif (amount == 0) {\n\t\t\treturn img;\n\t\t}\n\t\tRescaleOp rescaleOp = new RescaleOp(1, amount, null);\n\t\treturn rescaleOp.filter(img, null);\n\t}\n\n\t/**\n\t * Changes image saturation by a given amount\n\t * \n\t * @param img the image to change\n\t * @param amount the amount of saturation (0-1 range)\n\t * @return the modified image\n\t */\n\tpublic static BufferedImage changeSaturation(BufferedImage img, float amount) {\n\t\tif (amount == 0) {\n\t\t\treturn img;\n\t\t}\n\t\tfor (int y = 0; y < img.getHeight(); ++y) {\n\t\t\tfor (int x = 0; x < img.getWidth(); ++x) {\n\t\t\t\timg.setRGB(x, y, changePixelSaturation(img.getRGB(x, y), amount));\n\t\t\t}\n\t\t}\n\t\treturn img;\n\t}\n\n\t/**\n\t * Changes the saturation of an individual pixel by the given amount (0-1\n\t * range)\n\t * \n\t * @param pixel the pixel rgb to saturate\n\t * @param amount the amount to saturate\n\t * @return the modified rgb pixel\n\t */\n\tprivate static int changePixelSaturation(int pixel, float amount) {\n\t\tint[] rgb = intToRgbComponents(pixel);\n\t\tfloat[] hsb = Color.RGBtoHSB(rgb[0], rgb[1], rgb[2], null);\n\t\thsb[1] += amount;\n\t\tfloat saturation = correctRange(hsb[1], 0, 1);\n\t\treturn Color.HSBtoRGB(hsb[0], saturation, hsb[2]);\n\t}\n\n\t/**\n\t * Ensures a value is within a given range. If it exceeds or is below it is\n\t * set to the high value or low value respectively\n\t * \n\t * @param value the value to test\n\t * @param low the low value\n\t * @param high the high value\n\t * @return the ranged valued\n\t */\n\tprivate static int correctRange(int value, int low, int high) {\n\t\tif (value < low) {\n\t\t\treturn low;\n\t\t}\n\t\tif (value > high) {\n\t\t\treturn high;\n\t\t}\n\t\treturn value;\n\t}\n\t\n\t/**\n\t * Ensures a value is within a given range. If it exceeds or is below it is\n\t * set to the high value or low value respectively\n\t * \n\t * @param value the value to test\n\t * @param low the low value\n\t * @param high the high value\n\t * @return the ranged valued\n\t */\n\tpublic static float correctRange(float value, float low, float high) {\n\t\tif (value < low) {\n\t\t\treturn low;\n\t\t}\n\t\tif (value > high) {\n\t\t\treturn high;\n\t\t}\n\t\treturn value;\n\t}\n\n\t/**\n\t * Convert rgb to its components\n\t * \n\t * @param rgb the value to split\n\t * @return the rgb components\n\t */\n\tpublic static int[] intToRgbComponents(int rgb) {\n\t\treturn new int[] { rgb >> 16 & 0xFF, rgb >> 8 & 0xFF, rgb & 0xFF };\n\t}\n\n\t/**\n\t * Convert individual RGB components into a 32 bit ARGB value\n\t * \n\t * @param red the red component\n\t * @param green the green component\n\t * @param blue the blue component\n\t * @return the argb value\n\t */\n\tpublic static int componentsToAlphaRgb(int red, int green, int blue) {\n\t\treturn new Color(correctRange(red), correctRange(green), correctRange(blue)).getRGB();\n\t}\n\n\t/**\n\t * Corrects and individual colour component value's range to 0>channel<255\n\t * \n\t * @param component the component to restrict\n\t * @return the corrected component\n\t */\n\tpublic static int correctRange(int component) {\n\t\treturn ColourHelper.correctRange(component, 0, MAXIMUM_COMPONENT_VALUE);\n\t}\n\n\t/**\n\t * Returns an array of black and white colours representing the ink (black)\n\t * and paper (white) monochrome colours.\n\t * \n\t * Opposite function to getMonochromeFromBlackAndWhite\n\t * \n\t * @param image the monochrome image to scan\n\t * @return an array of black and white rgb values\n\t */\n\tpublic static int[] getBlackAndWhiteFromMonochrome(int[] image) {\n\t\tint[] copy = Arrays.copyOf(image, image.length);\n\t\tfor (int i = 0; i < copy.length; ++i) {\n\t\t\tif (copy[i] == SpectrumDefaults.SPECTRUM_COLOURS_BRIGHT[OptionsObject.getInstance().getMonochromePaperIndex()]) {\n\t\t\t\tcopy[i] = Color.WHITE.getRGB();\n\t\t\t} else {\n\t\t\t\tcopy[i] = Color.BLACK.getRGB();\n\t\t\t}\n\t\t}\n\t\treturn copy;\n\t}\n\n\t/**\n\t * Returns an array of monochrome (chosen ink and paper) colours based on an\n\t * input array of black (ink) and white (paper).\n\t * \n\t * Opposite function to getBlackAndWhiteFromMonochrome\n\t * \n\t * @param data the black and white array to get the monochrome colours for\n\t * @return the equivalent monochrome array\n\t */\n\tpublic static int[] getMonochromeFromBlackAndWhite(final int[] data) {\n\t\tint[] copy = Arrays.copyOf(data, data.length);\n\t\tfor (int i = 0; i < copy.length; ++i) {\n\t\t\tcopy[i] = getMonochromeFromBlackAndWhite(copy[i]);\n\t\t}\n\t\treturn copy;\n\t}\n\n\t/**\n\t * Returns an a monochrome (chosen ink and paper) colour based on an\n\t * input array of black (ink) and white (paper).\n\t * \n\t * @param original the black and white rgb value to get the monochrome colour for\n\t * @return the equivalent monochrome colour\n\t */\n\tpublic static int getMonochromeFromBlackAndWhite(int original) {\n\t\tOptionsObject oo = OptionsObject.getInstance();\n\t\tif (original == Color.WHITE.getRGB()) {\n\t\t\treturn SpectrumDefaults.SPECTRUM_COLOURS_BRIGHT[oo.getMonochromePaperIndex()];\n\t\t}\n\t\treturn SpectrumDefaults.SPECTRUM_COLOURS_BRIGHT[oo.getMonochromeInkIndex()];\n\t}\n\n\tprivate static String getAverageKey(int[] palette) {\n\t\treturn \"pal\"+Arrays.hashCode(palette);\n\t}\n\n\tprivate static String getClosestKey(int rgb, GigaScreenAttribute attribute, GigaScreenAttributeStrategy attributeStrategy) {\n\t\treturn rgb+\"-\"+attribute.hashCode()+\"-\"+attributeStrategy.hashCode();\n\t}\n\n}", "public static String getCaption(String key) {\n\tString translation = null;\n\tif (captions != null) {\n\t\ttry {\n\t\t\ttranslation = captions.getString(key);\n\t\t} catch(MissingResourceException ignore){}\n\t}\n\t// We're missing a key's value, use the key as the value :(\n\tif (translation == null || translation.trim().length()==0) {\n\t\ttranslation=key;\n\t}\n\treturn translation;\n}", "public static final int ATTRIBUTE_BLOCK_SIZE = 8;" ]
import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import uk.co.silentsoftware.config.OptionsObject; import uk.co.silentsoftware.config.SpectrumDefaults; import uk.co.silentsoftware.core.attributestrategy.GigaScreenAttributeStrategy; import uk.co.silentsoftware.core.converters.image.processors.GigaScreenAttribute; import uk.co.silentsoftware.core.helpers.ColourHelper; import java.awt.image.BufferedImage; import java.util.Arrays; import java.util.concurrent.TimeUnit; import static uk.co.silentsoftware.config.LanguageSupport.getCaption; import static uk.co.silentsoftware.config.SpectrumDefaults.ATTRIBUTE_BLOCK_SIZE;
/* Image to ZX Spec * Copyright (C) 2020 Silent Software (Benjamin Brown) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.silentsoftware.core.colourstrategy; /** * GigaScreen palette strategy */ public class GigaScreenPaletteStrategy implements ColourChoiceStrategy { private static final int CACHE_TIME_SECONDS = 10; private static final Cache<String, GigaScreenAttribute[][]> CACHE = Caffeine.newBuilder().expireAfterAccess(CACHE_TIME_SECONDS, TimeUnit.SECONDS).build(); public String toString() { return getCaption("colour_mode_gigascreen"); } /** * Processing of the colours cannot be applied to both Spectrum screens used in Gigascreen at the same time. * If this method is called then the wrong processor implementation is being used. */ @Override public int chooseBestPaletteMatch(int originalRgb, int[] mostPopularRgbColours) { throw new UnsupportedOperationException("GigaScreen palette colouring cannot be applied to dither image processors - this is a placeholder class to allow identification during getClosestColour conversions for the GigaScreenConverter."); } @Override public int chooseBestPaletteMatch(int rgb) { return ColourHelper.getClosestColour(rgb, SpectrumDefaults.GIGASCREEN_COLOURS_ALL); } @Override public int[] getPalette() { return SpectrumDefaults.GIGASCREEN_COLOURS_ALL; } @Override public BufferedImage colourAttributes(BufferedImage output) { // Algorithm replaces each pixel with the colour from the closest matching // 4 colour GigaScreen attribute block. GigaScreenAttribute[] palette = OptionsObject.getInstance().getGigaScreenAttributeStrategy().getPalette(); GigaScreenAttribute[][] quad = getGigaScreenAttributes(output, palette); GigaScreenAttribute currentGigaScreenAttribute = null; for (int y = 0; y < output.getHeight(); ++y) { for (int x = 0; x < output.getWidth(); ++x) {
if (x % ATTRIBUTE_BLOCK_SIZE == 0) {
6
CyclopsMC/ColossalChests
src/main/java/org/cyclops/colossalchests/item/ItemUpgradeTool.java
[ "public class Advancements {\n\n public static final ChestFormedTrigger CHEST_FORMED = AdvancementHelpers\n .registerCriteriaTrigger(new ChestFormedTrigger());\n\n public static void load() {}\n\n}", "public class ChestMaterial extends ForgeRegistryEntry<ChestMaterial> {\n\n public static final List<ChestMaterial> VALUES = Lists.newArrayList();\n public static final Map<String, ChestMaterial> KEYED_VALUES = Maps.newHashMap();\n\n public static final ChestMaterial WOOD = new ChestMaterial(\"wood\", 1);\n public static final ChestMaterial COPPER = new ChestMaterial(\"copper\", 1.666);\n public static final ChestMaterial IRON = new ChestMaterial(\"iron\", 2);\n public static final ChestMaterial SILVER = new ChestMaterial(\"silver\", 2.666);\n public static final ChestMaterial GOLD = new ChestMaterial(\"gold\", 3);\n public static final ChestMaterial DIAMOND = new ChestMaterial(\"diamond\", 4);\n public static final ChestMaterial OBSIDIAN = new ChestMaterial(\"obsidian\", 4);\n\n private final String name;\n private final double inventoryMultiplier;\n private final int index;\n\n private ColossalChest blockCore;\n private Interface blockInterface;\n private ChestWall blockWall;\n private CubeDetector chestDetector = null;\n private ContainerType<ContainerColossalChest> container;\n\n public ChestMaterial(String name, double inventoryMultiplier) {\n this.name = name;\n this.inventoryMultiplier = inventoryMultiplier;\n this.index = ChestMaterial.VALUES.size();\n ChestMaterial.VALUES.add(this);\n ChestMaterial.KEYED_VALUES.put(getName(), this);\n }\n\n public static ChestMaterial valueOf(String materialString) {\n return KEYED_VALUES.get(materialString.toLowerCase());\n }\n\n public String getName() {\n return name;\n }\n\n public double getInventoryMultiplier() {\n return this.inventoryMultiplier;\n }\n\n public String getUnlocalizedName() {\n return \"material.\" + Reference.MOD_ID + \".\" + getName();\n }\n\n public boolean isExplosionResistant() {\n return this == OBSIDIAN;\n }\n\n public int ordinal() {\n return this.index;\n }\n\n public ColossalChest getBlockCore() {\n return blockCore;\n }\n\n public void setBlockCore(ColossalChest blockCore) {\n if (this.blockCore != null) {\n throw new IllegalStateException(\"Tried registering multiple core blocks for \" + this.getName());\n }\n this.blockCore = blockCore;\n }\n\n public Interface getBlockInterface() {\n return blockInterface;\n }\n\n public void setBlockInterface(Interface blockInterface) {\n if (this.blockInterface != null) {\n throw new IllegalStateException(\"Tried registering multiple core blocks for \" + this.getName());\n }\n this.blockInterface = blockInterface;\n }\n\n public ChestWall getBlockWall() {\n return blockWall;\n }\n\n public void setBlockWall(ChestWall blockWall) {\n if (this.blockWall != null) {\n throw new IllegalStateException(\"Tried registering multiple core blocks for \" + this.getName());\n }\n this.blockWall = blockWall;\n }\n\n public void setContainer(ContainerType<ContainerColossalChest> container) {\n if (this.container != null) {\n throw new IllegalStateException(\"Tried registering multiple containers for \" + this.getName());\n }\n this.container = container;\n }\n\n public ContainerType<ContainerColossalChest> getContainer() {\n return container;\n }\n\n public CubeDetector getChestDetector() {\n if (chestDetector == null) {\n chestDetector = new HollowCubeDetector(\n new AllowedBlock[]{\n new AllowedBlock(getBlockWall()),\n new AllowedBlock(getBlockCore()).addCountValidator(new ExactBlockCountValidator(1)),\n new AllowedBlock(getBlockInterface())\n },\n Lists.newArrayList(getBlockCore(), getBlockWall(), getBlockInterface())\n )\n .addSizeValidator(new MinimumSizeValidator(new Vector3i(1, 1, 1)))\n .addSizeValidator(new CubeSizeValidator())\n .addSizeValidator(new MaximumSizeValidator(TileColossalChest.getMaxSize()) {\n @Override\n public Vector3i getMaximumSize() {\n return TileColossalChest.getMaxSize();\n }\n });\n }\n return chestDetector;\n }\n\n}", "public class ChestWall extends Block implements CubeDetector.IDetectionListener, IBlockChestMaterial {\n\n public static final BooleanProperty ENABLED = ColossalChest.ENABLED;\n\n private final ChestMaterial material;\n\n public ChestWall(Block.Properties properties, ChestMaterial material) {\n super(properties);\n this.material = material;\n\n material.setBlockWall(this);\n\n this.setDefaultState(this.stateContainer.getBaseState()\n .with(ENABLED, false));\n }\n\n @Override\n public String getTranslationKey() {\n String baseKey = super.getTranslationKey();\n return baseKey.substring(0, baseKey.lastIndexOf('_'));\n }\n\n @Override\n public ChestMaterial getMaterial() {\n return material;\n }\n\n @Override\n protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) {\n builder.add(ENABLED);\n }\n\n @Override\n public boolean isToolEffective(BlockState state, ToolType tool) {\n return ColossalChest.isToolEffectiveShared(this.material, state, tool);\n }\n\n @Override\n public BlockRenderType getRenderType(BlockState blockState) {\n return blockState.get(ENABLED) ? BlockRenderType.ENTITYBLOCK_ANIMATED : super.getRenderType(blockState);\n }\n\n @Override\n public boolean propagatesSkylightDown(BlockState blockState, IBlockReader blockReader, BlockPos blockPos) {\n return blockState.get(ENABLED);\n }\n\n @Override\n public boolean canCreatureSpawn(BlockState state, IBlockReader world, BlockPos pos,\n EntitySpawnPlacementRegistry.PlacementType type, @Nullable EntityType<?> entityType) {\n return false;\n }\n\n @Override\n public boolean shouldDisplayFluidOverlay(BlockState blockState, IBlockDisplayReader world, BlockPos pos, FluidState fluidState) {\n return true;\n }\n\n @Override\n public void onBlockPlacedBy(World world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) {\n super.onBlockPlacedBy(world, pos, state, placer, stack);\n ColossalChest.triggerDetector(this.material, world, pos, true, placer instanceof PlayerEntity ? (PlayerEntity) placer : null);\n }\n\n @Override\n public void onBlockAdded(BlockState blockStateNew, World world, BlockPos blockPos, BlockState blockStateOld, boolean isMoving) {\n super.onBlockAdded(blockStateNew, world, blockPos, blockStateOld, isMoving);\n if(!world.captureBlockSnapshots && blockStateNew.getBlock() != blockStateOld.getBlock() && !blockStateNew.get(ENABLED)) {\n ColossalChest.triggerDetector(this.material, world, blockPos, true, null);\n }\n }\n\n @Override\n public void onPlayerDestroy(IWorld world, BlockPos blockPos, BlockState blockState) {\n if(blockState.get(ENABLED)) ColossalChest.triggerDetector(material, world, blockPos, false, null);\n super.onPlayerDestroy(world, blockPos, blockState);\n }\n\n @Override\n public void onBlockExploded(BlockState state, World world, BlockPos pos, Explosion explosion) {\n if(world.getBlockState(pos).get(ENABLED)) ColossalChest.triggerDetector(material, world, pos, false, null);\n // IForgeBlock.super.onBlockExploded(state, world, pos, explosion);\n world.setBlockState(pos, Blocks.AIR.getDefaultState(), 3);\n getBlock().onExplosionDestroy(world, pos, explosion);\n }\n\n @Override\n public void onDetect(IWorldReader world, BlockPos location, Vector3i size, boolean valid, BlockPos originCorner) {\n Block block = world.getBlockState(location).getBlock();\n if(block == this) {\n boolean change = !world.getBlockState(location).get(ENABLED);\n ((IWorldWriter) world).setBlockState(location, world.getBlockState(location).with(ENABLED, valid), MinecraftHelpers.BLOCK_NOTIFY_CLIENT);\n if(change) {\n TileColossalChest.detectStructure(world, location, size, valid, originCorner);\n }\n }\n }\n\n @Override\n public ActionResultType onBlockActivated(BlockState blockState, World world, BlockPos blockPos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult) {\n if(blockState.get(ENABLED)) {\n BlockPos tileLocation = ColossalChest.getCoreLocation(material, world, blockPos);\n if(tileLocation != null) {\n return world.getBlockState(tileLocation).getBlock().\n onBlockActivated(blockState, world, tileLocation, player, hand, rayTraceResult);\n }\n } else {\n ColossalChest.addPlayerChatError(material, world, blockPos, player, hand);\n return ActionResultType.FAIL;\n }\n return super.onBlockActivated(blockState, world, blockPos, player, hand, rayTraceResult);\n }\n\n @Override\n public boolean isValidPosition(BlockState blockState, IWorldReader world, BlockPos blockPos) {\n return super.isValidPosition(blockState, world, blockPos) && ColossalChest.canPlace(world, blockPos);\n }\n\n @Override\n public float getExplosionResistance(BlockState state, IBlockReader world, BlockPos pos, Explosion explosion) {\n if (this.material.isExplosionResistant()) {\n return 10000F;\n }\n return 0;\n }\n\n}", "public class ColossalChest extends BlockTileGui implements CubeDetector.IDetectionListener, IBlockChestMaterial {\n\n public static final BooleanProperty ENABLED = BlockStateProperties.ENABLED;\n\n private final ChestMaterial material;\n\n public ColossalChest(Properties properties, ChestMaterial material) {\n super(properties, TileColossalChest::new);\n this.material = material;\n\n material.setBlockCore(this);\n\n this.setDefaultState(this.stateContainer.getBaseState()\n .with(ENABLED, false));\n }\n\n @Override\n public String getTranslationKey() {\n String baseKey = super.getTranslationKey();\n return baseKey.substring(0, baseKey.lastIndexOf('_'));\n }\n\n @Override\n public ChestMaterial getMaterial() {\n return material;\n }\n\n @Override\n protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) {\n builder.add(ENABLED);\n }\n\n public static boolean isToolEffectiveShared(ChestMaterial material, BlockState state, ToolType tool) {\n if(material == ChestMaterial.WOOD) {\n return tool == ToolType.AXE;\n }\n return tool == ToolType.PICKAXE;\n }\n\n public static boolean canPlace(IWorldReader world, BlockPos pos) {\n for(Direction side : Direction.values()) {\n BlockState blockState = world.getBlockState(pos.offset(side));\n Block block = blockState.getBlock();\n if((block instanceof ColossalChest || block instanceof ChestWall || block instanceof Interface)\n && blockState.getProperties().contains(ENABLED) && blockState.get(ENABLED)) {\n return false;\n }\n }\n return true;\n }\n\n @Override\n public boolean isToolEffective(BlockState state, ToolType tool) {\n return isToolEffectiveShared(this.material, state, tool);\n }\n\n @Override\n public BlockRenderType getRenderType(BlockState blockState) {\n return blockState.get(ENABLED) ? BlockRenderType.ENTITYBLOCK_ANIMATED : super.getRenderType(blockState);\n }\n\n @Override\n public boolean propagatesSkylightDown(BlockState blockState, IBlockReader blockReader, BlockPos blockPos) {\n return blockState.get(ENABLED);\n }\n\n @Override\n public boolean canCreatureSpawn(BlockState state, IBlockReader world, BlockPos pos,\n EntitySpawnPlacementRegistry.PlacementType type, @Nullable EntityType<?> entityType) {\n return false;\n }\n\n @Override\n public boolean shouldDisplayFluidOverlay(BlockState blockState, IBlockDisplayReader world, BlockPos pos, FluidState fluidState) {\n return true;\n }\n\n public static DetectionResult triggerDetector(ChestMaterial material, IWorld world, BlockPos blockPos, boolean valid, @Nullable PlayerEntity player) {\n DetectionResult detectionResult = material.getChestDetector().detect(world, blockPos, valid ? null : blockPos, new MaterialValidationAction(), true);\n if (player instanceof ServerPlayerEntity && detectionResult.getError() == null) {\n BlockState blockState = world.getBlockState(blockPos);\n if (blockState.get(ENABLED)) {\n TileColossalChest tile = TileHelpers.getSafeTile(world, blockPos, TileColossalChest.class).orElse(null);\n if (tile == null) {\n BlockPos corePos = getCoreLocation(material, world, blockPos);\n tile = TileHelpers.getSafeTile(world, corePos, TileColossalChest.class).orElse(null);\n }\n\n Advancements.CHEST_FORMED.test((ServerPlayerEntity) player, material, tile.getSizeSingular());\n }\n }\n return detectionResult;\n }\n\n @Override\n public void onBlockPlacedBy(World world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) {\n super.onBlockPlacedBy(world, pos, state, placer, stack);\n if (stack.hasDisplayName()) {\n TileColossalChest tile = TileHelpers.getSafeTile(world, pos, TileColossalChest.class).orElse(null);\n if (tile != null) {\n tile.setCustomName(stack.getDisplayName());\n tile.setSize(Vector3i.NULL_VECTOR);\n }\n }\n triggerDetector(this.material, world, pos, true, placer instanceof PlayerEntity ? (PlayerEntity) placer : null);\n }\n\n @Override\n public void onBlockAdded(BlockState blockStateNew, World world, BlockPos blockPos, BlockState blockStateOld, boolean isMoving) {\n super.onBlockAdded(blockStateNew, world, blockPos, blockStateOld, isMoving);\n if(!world.captureBlockSnapshots && blockStateNew.getBlock() != blockStateOld.getBlock() && !blockStateNew.get(ENABLED)) {\n triggerDetector(this.material, world, blockPos, true, null);\n }\n }\n\n @Override\n public void onDetect(IWorldReader world, BlockPos location, Vector3i size, boolean valid, BlockPos originCorner) {\n Block block = world.getBlockState(location).getBlock();\n if(block == this) {\n ((IWorldWriter) world).setBlockState(location, world.getBlockState(location).with(ENABLED, valid), MinecraftHelpers.BLOCK_NOTIFY_CLIENT);\n TileColossalChest tile = TileHelpers.getSafeTile(world, location, TileColossalChest.class).orElse(null);\n if(tile != null) {\n tile.setMaterial(this.material);\n tile.setSize(valid ? size : Vector3i.NULL_VECTOR);\n tile.setCenter(new Vector3d(\n originCorner.getX() + ((double) size.getX()) / 2,\n originCorner.getY() + ((double) size.getY()) / 2,\n originCorner.getZ() + ((double) size.getZ()) / 2\n ));\n tile.addInterface(location);\n }\n }\n }\n\n /**\n * Get the core block location.\n * @param material The chest material.\n * @param world The world.\n * @param blockPos The start position to search from.\n * @return The found location.\n */\n public static @Nullable BlockPos getCoreLocation(ChestMaterial material, IWorldReader world, BlockPos blockPos) {\n final Wrapper<BlockPos> tileLocationWrapper = new Wrapper<BlockPos>();\n material.getChestDetector().detect(world, blockPos, null, (location, blockState) -> {\n if (blockState.getBlock() instanceof ColossalChest) {\n tileLocationWrapper.set(location);\n }\n return null;\n }, false);\n return tileLocationWrapper.get();\n }\n\n /**\n * Show the structure forming error in the given player chat window.\n * @param material The chest material.\n * @param world The world.\n * @param blockPos The start position.\n * @param player The player.\n * @param hand The used hand.\n */\n public static void addPlayerChatError(ChestMaterial material, World world, BlockPos blockPos, PlayerEntity player, Hand hand) {\n if(!world.isRemote && player.getHeldItem(hand).isEmpty()) {\n DetectionResult result = material.getChestDetector().detect(world, blockPos, null, new MaterialValidationAction(), false);\n if (result != null && result.getError() != null) {\n addPlayerChatError(player, result.getError());\n } else {\n player.sendMessage(new TranslationTextComponent(\"multiblock.colossalchests.error.unexpected\"), Util.DUMMY_UUID);\n }\n }\n }\n\n public static void addPlayerChatError(PlayerEntity player, ITextComponent error) {\n IFormattableTextComponent chat = new StringTextComponent(\"\");\n ITextComponent prefix = new StringTextComponent(\"[\")\n .append(new TranslationTextComponent(\"multiblock.colossalchests.error.prefix\"))\n .append(new StringTextComponent(\"]: \"))\n .setStyle(Style.EMPTY.\n setColor(Color.fromTextFormatting(TextFormatting.GRAY)).\n setHoverEvent(new HoverEvent(\n HoverEvent.Action.SHOW_TEXT,\n new TranslationTextComponent(\"multiblock.colossalchests.error.prefix.info\")\n ))\n );\n chat.append(prefix);\n chat.append(error);\n player.sendMessage(chat, Util.DUMMY_UUID);\n }\n\n @Override\n public void writeExtraGuiData(PacketBuffer packetBuffer, World world, PlayerEntity player, BlockPos blockPos, Hand hand, BlockRayTraceResult rayTraceResult) {\n TileHelpers.getSafeTile(world, blockPos, TileColossalChest.class).ifPresent(tile -> packetBuffer.writeInt(tile.getInventory().getSizeInventory()));\n }\n\n @Override\n public ActionResultType onBlockActivated(BlockState blockState, World world, BlockPos blockPos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult) {\n if(!(blockState.get(ENABLED))) {\n ColossalChest.addPlayerChatError(material, world, blockPos, player, hand);\n return ActionResultType.FAIL;\n }\n return super.onBlockActivated(blockState, world, blockPos, player, hand, rayTraceResult);\n }\n\n @Override\n public void onPlayerDestroy(IWorld world, BlockPos blockPos, BlockState blockState) {\n if(blockState.get(ENABLED)) ColossalChest.triggerDetector(material, world, blockPos, false, null);\n super.onPlayerDestroy(world, blockPos, blockState);\n }\n\n @Override\n public void onBlockExploded(BlockState state, World world, BlockPos pos, Explosion explosion) {\n if(world.getBlockState(pos).get(ENABLED)) ColossalChest.triggerDetector(material, world, pos, false, null);\n // IForgeBlock.super.onBlockExploded(state, world, pos, explosion);\n world.setBlockState(pos, Blocks.AIR.getDefaultState(), 3);\n getBlock().onExplosionDestroy(world, pos, explosion);\n }\n\n @Override\n public float getExplosionResistance(BlockState state, IBlockReader world, BlockPos pos, Explosion explosion) {\n if (this.material.isExplosionResistant()) {\n return 10000F;\n }\n return 0;\n }\n\n @Override\n public boolean isValidPosition(BlockState blockState, IWorldReader world, BlockPos blockPos) {\n return super.isValidPosition(blockState, world, blockPos) && ColossalChest.canPlace(world, blockPos);\n }\n\n @Override\n public void onReplaced(BlockState oldState, World world, BlockPos blockPos, BlockState newState, boolean isMoving) {\n if (oldState.getBlock().getClass() != newState.getBlock().getClass()) {\n TileHelpers.getSafeTile(world, blockPos, TileColossalChest.class)\n .ifPresent(tile -> {\n // Last inventory overrides inventory when the chest is in a disabled state.\n SimpleInventory lastInventory = tile.getLastValidInventory();\n InventoryHelpers.dropItems(world, lastInventory != null ? lastInventory : tile.getInventory(), blockPos);\n });\n super.onReplaced(oldState, world, blockPos, newState, isMoving);\n }\n }\n\n private static class MaterialValidationAction implements CubeDetector.IValidationAction {\n private final Wrapper<ChestMaterial> requiredMaterial;\n\n public MaterialValidationAction() {\n this.requiredMaterial = new Wrapper<ChestMaterial>(null);\n }\n\n @Override\n public ITextComponent onValidate(BlockPos blockPos, BlockState blockState) {\n ChestMaterial material = null;\n if (blockState.getBlock() instanceof IBlockChestMaterial) {\n material = ((IBlockChestMaterial) blockState.getBlock()).getMaterial();\n }\n if(requiredMaterial.get() == null) {\n requiredMaterial.set(material);\n return null;\n }\n return requiredMaterial.get() == material ? null : new TranslationTextComponent(\n \"multiblock.colossalchests.error.material\", new TranslationTextComponent(material.getUnlocalizedName()),\n LocationHelpers.toCompactString(blockPos),\n new TranslationTextComponent(requiredMaterial.get().getUnlocalizedName()));\n }\n }\n}", "public interface IBlockChestMaterial {\n\n public ChestMaterial getMaterial();\n\n}", "public class Interface extends BlockTile implements CubeDetector.IDetectionListener, IBlockChestMaterial {\n\n public static final BooleanProperty ENABLED = ColossalChest.ENABLED;\n\n private final ChestMaterial material;\n\n public Interface(Block.Properties properties, ChestMaterial material) {\n super(properties, TileInterface::new);\n this.material = material;\n\n material.setBlockInterface(this);\n\n this.setDefaultState(this.stateContainer.getBaseState()\n .with(ENABLED, false));\n }\n\n @Override\n public String getTranslationKey() {\n String baseKey = super.getTranslationKey();\n return baseKey.substring(0, baseKey.lastIndexOf('_'));\n }\n\n @Override\n public ChestMaterial getMaterial() {\n return material;\n }\n\n @Override\n protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) {\n builder.add(ENABLED);\n }\n\n @Override\n public boolean isToolEffective(BlockState state, ToolType tool) {\n return ColossalChest.isToolEffectiveShared(this.material, state, tool);\n }\n\n @Override\n public BlockRenderType getRenderType(BlockState blockState) {\n return blockState.get(ENABLED) ? BlockRenderType.ENTITYBLOCK_ANIMATED : super.getRenderType(blockState);\n }\n\n @Override\n public boolean propagatesSkylightDown(BlockState blockState, IBlockReader blockReader, BlockPos blockPos) {\n return blockState.get(ENABLED);\n }\n\n @Override\n public boolean canCreatureSpawn(BlockState state, IBlockReader world, BlockPos pos,\n EntitySpawnPlacementRegistry.PlacementType type, @Nullable EntityType<?> entityType) {\n return false;\n }\n\n @Override\n public boolean shouldDisplayFluidOverlay(BlockState blockState, IBlockDisplayReader world, BlockPos pos, FluidState fluidState) {\n return true;\n }\n\n @Override\n public void onBlockPlacedBy(World world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) {\n super.onBlockPlacedBy(world, pos, state, placer, stack);\n ColossalChest.triggerDetector(this.material, world, pos, true, placer instanceof PlayerEntity ? (PlayerEntity) placer : null);\n }\n\n @Override\n public void onBlockAdded(BlockState blockStateNew, World world, BlockPos blockPos, BlockState blockStateOld, boolean isMoving) {\n super.onBlockAdded(blockStateNew, world, blockPos, blockStateOld, isMoving);\n if(!world.captureBlockSnapshots && blockStateNew.getBlock() != blockStateOld.getBlock() && !blockStateNew.get(ENABLED)) {\n ColossalChest.triggerDetector(this.material, world, blockPos, true, null);\n }\n }\n\n @Override\n public void onPlayerDestroy(IWorld world, BlockPos blockPos, BlockState blockState) {\n if(blockState.get(ENABLED)) ColossalChest.triggerDetector(material, world, blockPos, false, null);\n super.onPlayerDestroy(world, blockPos, blockState);\n }\n\n @Override\n public void onBlockExploded(BlockState state, World world, BlockPos pos, Explosion explosion) {\n if(world.getBlockState(pos).get(ENABLED)) ColossalChest.triggerDetector(material, world, pos, false, null);\n // IForgeBlock.super.onBlockExploded(state, world, pos, explosion);\n world.setBlockState(pos, Blocks.AIR.getDefaultState(), 3);\n getBlock().onExplosionDestroy(world, pos, explosion);\n }\n\n @Override\n public void onDetect(IWorldReader world, BlockPos location, Vector3i size, boolean valid, BlockPos originCorner) {\n Block block = world.getBlockState(location).getBlock();\n if(block == this) {\n boolean change = !(Boolean) world.getBlockState(location).get(ENABLED);\n ((IWorldWriter) world).setBlockState(location, world.getBlockState(location).with(ENABLED, valid), MinecraftHelpers.BLOCK_NOTIFY_CLIENT);\n if(change) {\n BlockPos tileLocation = ColossalChest.getCoreLocation(material, world, location);\n TileInterface tile = TileHelpers.getSafeTile(world, location, TileInterface.class).orElse(null);\n if(tile != null && tileLocation != null) {\n tile.setCorePosition(tileLocation);\n TileColossalChest core = TileHelpers.getSafeTile(world, tileLocation, TileColossalChest.class).orElse(null);\n if (core != null) {\n core.addInterface(location);\n }\n }\n }\n }\n }\n\n @Override\n public ActionResultType onBlockActivated(BlockState blockState, World world, BlockPos blockPos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult) {\n if(blockState.get(ENABLED)) {\n BlockPos tileLocation = ColossalChest.getCoreLocation(material, world, blockPos);\n if(tileLocation != null) {\n return world.getBlockState(tileLocation).getBlock().\n onBlockActivated(blockState, world, tileLocation, player, hand, rayTraceResult);\n }\n } else {\n ColossalChest.addPlayerChatError(material, world, blockPos, player, hand);\n return ActionResultType.FAIL;\n }\n return super.onBlockActivated(blockState, world, blockPos, player, hand, rayTraceResult);\n }\n\n @Override\n public boolean isValidPosition(BlockState blockState, IWorldReader world, BlockPos blockPos) {\n return super.isValidPosition(blockState, world, blockPos) && ColossalChest.canPlace(world, blockPos);\n }\n\n @Override\n public float getExplosionResistance(BlockState state, IBlockReader world, BlockPos pos, Explosion explosion) {\n if (this.material.isExplosionResistant()) {\n return 10000F;\n }\n return 0;\n }\n\n}", "@OnlyIn(value = Dist.CLIENT, _interface = IChestLid.class)\npublic class TileColossalChest extends CyclopsTileEntity implements CyclopsTileEntity.ITickingTile, INamedContainerProvider, IChestLid {\n\n private static final int TICK_MODULUS = 200;\n\n @Delegate\n private final ITickingTile tickingTileComponent = new TickingTileComponent(this);\n\n private SimpleInventory lastValidInventory = null;\n private SimpleInventory inventory = null;\n private LazyOptional<IItemHandler> capabilityItemHandler = LazyOptional.empty();\n\n @NBTPersist\n private Vector3i size = LocationHelpers.copyLocation(Vector3i.NULL_VECTOR);\n @NBTPersist\n private Vector3d renderOffset = new Vector3d(0, 0, 0);\n private ITextComponent customName = null;\n @NBTPersist\n private int materialId = 0;\n @NBTPersist\n private int rotation = 0;\n @NBTPersist(useDefaultValue = false)\n private List<Vector3i> interfaceLocations = Lists.newArrayList();\n\n /**\n * The previous angle of the lid.\n */\n public float prevLidAngle;\n /**\n * The current angle of the lid.\n */\n public float lidAngle;\n private int playersUsing;\n private boolean recreateNullInventory = true;\n\n private EnumFacingMap<int[]> facingSlots = EnumFacingMap.newMap();\n\n public TileColossalChest() {\n super(RegistryEntries.TILE_ENTITY_COLOSSAL_CHEST);\n }\n\n /**\n * @return the size\n */\n public Vector3i getSize() {\n return size;\n }\n\n /**\n * Set the size.\n * This will also handle the change in inventory size.\n * @param size the size to set\n */\n public void setSize(Vector3i size) {\n this.size = size;\n facingSlots.clear();\n if(isStructureComplete()) {\n setInventory(constructInventory());\n this.inventory.addDirtyMarkListener(this);\n\n // Move all items from the last valid inventory into the new one\n // If the new inventory would be smaller than the old one, the remaining\n // items will be ejected into the world for slot index larger than the new size.\n if(this.lastValidInventory != null) {\n int slot = 0;\n while(slot < Math.min(this.lastValidInventory.getSizeInventory(), this.inventory.getSizeInventory())) {\n ItemStack contents = this.lastValidInventory.getStackInSlot(slot);\n if (!contents.isEmpty()) {\n this.inventory.setInventorySlotContents(slot, contents);\n this.lastValidInventory.setInventorySlotContents(slot, ItemStack.EMPTY);\n }\n slot++;\n }\n if(slot < this.lastValidInventory.getSizeInventory()) {\n InventoryHelpers.dropItems(getWorld(), this.lastValidInventory, getPos());\n }\n this.lastValidInventory = null;\n }\n } else {\n interfaceLocations.clear();\n if(this.inventory != null) {\n if(GeneralConfig.ejectItemsOnDestroy) {\n InventoryHelpers.dropItems(getWorld(), this.inventory, getPos());\n this.lastValidInventory = null;\n } else {\n this.lastValidInventory = this.inventory;\n }\n }\n setInventory(new LargeInventory(0, 0));\n }\n sendUpdate();\n }\n\n public void setMaterial(ChestMaterial material) {\n this.materialId = material.ordinal();\n }\n\n public ChestMaterial getMaterial() {\n return ChestMaterial.VALUES.get(this.materialId);\n }\n\n public SimpleInventory getLastValidInventory() {\n return lastValidInventory;\n }\n\n public void setLastValidInventory(SimpleInventory lastValidInventory) {\n this.lastValidInventory = lastValidInventory;\n }\n\n public int getSizeSingular() {\n return getSize().getX() + 1;\n }\n\n protected boolean isClientSide() {\n return getWorld() != null && getWorld().isRemote;\n }\n\n protected LargeInventory constructInventory() {\n if (!isClientSide() && GeneralConfig.creativeChests) {\n return constructInventoryDebug();\n }\n return !isClientSide() ? new IndexedInventory(calculateInventorySize(), 64) {\n @Override\n public void openInventory(PlayerEntity entityPlayer) {\n if (!entityPlayer.isSpectator()) {\n super.openInventory(entityPlayer);\n triggerPlayerUsageChange(1);\n }\n }\n\n @Override\n public void closeInventory(PlayerEntity entityPlayer) {\n if (!entityPlayer.isSpectator()) {\n super.closeInventory(entityPlayer);\n triggerPlayerUsageChange(-1);\n }\n }\n } : new LargeInventory(calculateInventorySize(), 64);\n }\n\n protected LargeInventory constructInventoryDebug() {\n LargeInventory inv = !isClientSide() ? new IndexedInventory(calculateInventorySize(), 64)\n : new LargeInventory(calculateInventorySize(), 64);\n Random random = new Random();\n for (int i = 0; i < inv.getSizeInventory(); i++) {\n inv.setInventorySlotContents(i, new ItemStack(Iterables.get(ForgeRegistries.ITEMS.getValues(),\n random.nextInt(ForgeRegistries.ITEMS.getValues().size()))));\n }\n return inv;\n }\n\n @Override\n public CompoundNBT getUpdateTag() {\n // Don't send the inventory to the client.\n // The client will receive the data once the gui is opened.\n SimpleInventory oldInventory = this.inventory;\n SimpleInventory oldLastInventory = this.lastValidInventory;\n this.inventory = null;\n this.lastValidInventory = null;\n this.recreateNullInventory = false;\n CompoundNBT tag = super.getUpdateTag();\n this.inventory = oldInventory;\n this.lastValidInventory = oldLastInventory;\n this.recreateNullInventory = true;\n return tag;\n }\n\n @Override\n public void read(CompoundNBT tag) {\n SimpleInventory oldInventory = this.inventory;\n SimpleInventory oldLastInventory = this.lastValidInventory;\n\n if (getWorld() != null && getWorld().isRemote) {\n // Don't read the inventory on the client.\n // The client will receive the data once the gui is opened.\n this.inventory = null;\n this.lastValidInventory = null;\n this.recreateNullInventory = false;\n }\n super.read(tag);\n if (getWorld() != null && getWorld().isRemote) {\n this.inventory = oldInventory;\n this.lastValidInventory = oldLastInventory;\n this.recreateNullInventory = true;\n } else {\n getInventory().read(tag.getCompound(\"inventory\"));\n if (tag.contains(\"lastValidInventory\", Constants.NBT.TAG_COMPOUND)) {\n this.lastValidInventory = new LargeInventory(tag.getInt(\"lastValidInventorySize\"), this.inventory.getInventoryStackLimit());\n this.lastValidInventory.read(tag.getCompound(\"lastValidInventory\"));\n }\n }\n\n if (tag.contains(\"CustomName\", Constants.NBT.TAG_STRING)) {\n this.customName = ITextComponent.Serializer.getComponentFromJson(tag.getString(\"CustomName\"));\n }\n }\n\n @Override\n public CompoundNBT write(CompoundNBT tag) {\n if (this.customName != null) {\n tag.putString(\"CustomName\", ITextComponent.Serializer.toJson(this.customName));\n }\n if (this.inventory != null) {\n CompoundNBT subTag = new CompoundNBT();\n this.inventory.write(subTag);\n tag.put(\"inventory\", subTag);\n }\n if (this.lastValidInventory != null) {\n CompoundNBT subTag = new CompoundNBT();\n this.lastValidInventory.write(subTag);\n tag.put(\"lastValidInventory\", subTag);\n tag.putInt(\"lastValidInventorySize\", this.lastValidInventory.getSizeInventory());\n }\n return super.write(tag);\n }\n\n @Override\n public SUpdateTileEntityPacket getUpdatePacket() {\n return new SUpdateTileEntityPacket(getPos(), 1, getUpdateTag());\n }\n\n protected int calculateInventorySize() {\n int size = getSizeSingular();\n if (size == 1) {\n return 0;\n }\n return (int) Math.ceil((Math.pow(size, 3) * 27) * getMaterial().getInventoryMultiplier() / 9) * 9;\n }\n\n @Override\n public void updateTileEntity() {\n super.updateTileEntity();\n\n // Resynchronize clients with the server state, the last condition makes sure\n // not all chests are synced at the same time.\n if(world != null\n && !this.world.isRemote\n && this.playersUsing != 0\n && WorldHelpers.efficientTick(world, TICK_MODULUS, getPos().hashCode())) {\n this.playersUsing = 0;\n float range = 5.0F;\n @SuppressWarnings(\"unchecked\")\n List<PlayerEntity> entities = this.world.getEntitiesWithinAABB(\n PlayerEntity.class,\n new AxisAlignedBB(\n getPos().add(new Vector3i(-range, -range, -range)),\n getPos().add(new Vector3i(1 + range, 1 + range, 1 + range))\n )\n );\n\n for(PlayerEntity player : entities) {\n if (player.openContainer instanceof ContainerColossalChest) {\n ++this.playersUsing;\n }\n }\n\n world.addBlockEvent(getPos(), getBlockState().getBlock(), 1, playersUsing);\n }\n\n prevLidAngle = lidAngle;\n float increaseAngle = 0.15F / Math.min(5, getSizeSingular());\n if (playersUsing > 0 && lidAngle == 0.0F) {\n world.playSound(\n (double) getPos().getX() + 0.5D,\n (double) getPos().getY() + 0.5D,\n (double) getPos().getZ() + 0.5D,\n SoundEvents.BLOCK_CHEST_OPEN,\n SoundCategory.BLOCKS,\n (float) (0.5F + (0.5F * Math.log(getSizeSingular()))),\n world.rand.nextFloat() * 0.1F + 0.45F + increaseAngle,\n true\n );\n }\n if (playersUsing == 0 && lidAngle > 0.0F || playersUsing > 0 && lidAngle < 1.0F) {\n float preIncreaseAngle = lidAngle;\n if (playersUsing > 0) {\n lidAngle += increaseAngle;\n } else {\n lidAngle -= increaseAngle;\n }\n if (lidAngle > 1.0F) {\n lidAngle = 1.0F;\n }\n float closedAngle = 0.5F;\n if (lidAngle < closedAngle && preIncreaseAngle >= closedAngle) {\n world.playSound(\n (double) getPos().getX() + 0.5D,\n (double) getPos().getY() + 0.5D,\n (double) getPos().getZ() + 0.5D,\n SoundEvents.BLOCK_CHEST_CLOSE,\n SoundCategory.BLOCKS,\n (float) (0.5F + (0.5F * Math.log(getSizeSingular()))),\n world.rand.nextFloat() * 0.05F + 0.45F + increaseAngle,\n true\n );\n }\n if (lidAngle < 0.0F) {\n lidAngle = 0.0F;\n }\n }\n }\n\n @Override\n public boolean receiveClientEvent(int i, int j) {\n if (i == 1) {\n playersUsing = j;\n }\n return true;\n }\n\n private void triggerPlayerUsageChange(int change) {\n if (world != null) {\n playersUsing += change;\n world.addBlockEvent(getPos(), getBlockState().getBlock(), 1, playersUsing);\n }\n }\n\n public void setInventory(SimpleInventory inventory) {\n this.capabilityItemHandler.invalidate();\n this.inventory = inventory;\n if (this.inventory.getSizeInventory() > 0) {\n IItemHandler itemHandler = new InvWrapper(this.inventory);\n this.capabilityItemHandler = LazyOptional.of(() -> itemHandler);\n } else {\n this.capabilityItemHandler = LazyOptional.empty();\n }\n }\n\n protected void ensureInventoryInitialized() {\n if (getWorld() != null && getWorld().isRemote && (inventory == null || inventory.getSizeInventory() != calculateInventorySize())) {\n setInventory(constructInventory());\n }\n }\n\n public INBTInventory getInventory() {\n if(lastValidInventory != null) {\n return new IndexedInventory();\n }\n ensureInventoryInitialized();\n if(inventory == null && this.recreateNullInventory) {\n setInventory(constructInventory());\n }\n return inventory;\n }\n\n @Override\n public <T> LazyOptional<T> getCapability(Capability<T> capability, Direction facing) {\n ensureInventoryInitialized();\n if (this.capabilityItemHandler.isPresent() && capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) {\n return this.capabilityItemHandler.cast();\n }\n return super.getCapability(capability, facing);\n }\n\n @Override\n public boolean canInteractWith(PlayerEntity entityPlayer) {\n return getSizeSingular() > 1 && super.canInteractWith(entityPlayer);\n }\n\n @Override\n @OnlyIn(Dist.CLIENT)\n public AxisAlignedBB getRenderBoundingBox() {\n int size = getSizeSingular();\n return new AxisAlignedBB(getPos().subtract(new Vector3i(size, size, size)), getPos().add(size, size * 2, size));\n }\n\n public void setCenter(Vector3d center) {\n Direction rotation;\n double dx = Math.abs(center.x - getPos().getX());\n double dz = Math.abs(center.z - getPos().getZ());\n boolean equal = (center.x - getPos().getX()) == (center.z - getPos().getZ());\n if(dx > dz || (!equal && getSizeSingular() == 2)) {\n rotation = DirectionHelpers.getEnumFacingFromXSign((int) Math.round(center.x - getPos().getX()));\n } else {\n rotation = DirectionHelpers.getEnumFacingFromZSing((int) Math.round(center.z - getPos().getZ()));\n }\n this.setRotation(rotation);\n this.renderOffset = new Vector3d(getPos().getX() - center.x, getPos().getY() - center.y, getPos().getZ() - center.z);\n }\n\n public void setRotation(Direction rotation) {\n this.rotation = rotation.ordinal();\n }\n\n @Override\n public Direction getRotation() {\n return Direction.byIndex(this.rotation);\n }\n\n public Vector3d getRenderOffset() {\n return this.renderOffset;\n }\n\n public void setRenderOffset(Vector3d renderOffset) {\n this.renderOffset = renderOffset;\n }\n\n /**\n * Callback for when a structure has been detected for a spirit furnace block.\n * @param world The world.\n * @param location The location of one block of the structure.\n * @param size The size of the structure.\n * @param valid If the structure is being validated(/created), otherwise invalidated.\n * @param originCorner The origin corner\n */\n public static void detectStructure(IWorldReader world, BlockPos location, Vector3i size, boolean valid, BlockPos originCorner) {\n\n }\n\n /**\n * @return If the structure is valid.\n */\n public boolean isStructureComplete() {\n return !getSize().equals(Vector3i.NULL_VECTOR);\n }\n\n public static Vector3i getMaxSize() {\n int size = ColossalChestConfig.maxSize - 1;\n return new Vector3i(size, size, size);\n }\n\n public boolean hasCustomName() {\n return customName != null;\n }\n\n public void setCustomName(ITextComponent name) {\n this.customName = name;\n }\n\n public void addInterface(Vector3i blockPos) {\n interfaceLocations.add(blockPos);\n }\n\n public List<Vector3i> getInterfaceLocations() {\n return Collections.unmodifiableList(interfaceLocations);\n }\n\n @Override\n public ITextComponent getDisplayName() {\n return hasCustomName() ? customName : new TranslationTextComponent(\"general.colossalchests.colossalchest\",\n new TranslationTextComponent(getMaterial().getUnlocalizedName()), getSizeSingular());\n }\n\n @Nullable\n @Override\n public Container createMenu(int id, PlayerInventory playerInventory, PlayerEntity playerEntity) {\n return new ContainerColossalChest(id, playerInventory, this.getInventory());\n }\n\n @Override\n @OnlyIn(Dist.CLIENT)\n public float getLidAngle(float partialTicks) {\n return ColossalChestConfig.chestAnimation ? MathHelper.lerp(partialTicks, this.prevLidAngle, this.lidAngle) : 0F;\n }\n}", "public class TileInterface extends CyclopsTileEntity {\n\n @Delegate\n private final ITickingTile tickingTileComponent = new TickingTileComponent(this);\n\n @NBTPersist\n @Getter\n private Vector3i corePosition = null;\n private WeakReference<TileColossalChest> coreReference = new WeakReference<TileColossalChest>(null);\n\n public TileInterface() {\n super(RegistryEntries.TILE_ENTITY_INTERFACE);\n }\n\n @Override\n public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> capability, Direction facing) {\n TileColossalChest core = getCore();\n if (core != null) {\n LazyOptional<T> t = core.getCapability(capability, facing);\n if (t.isPresent()) {\n return t;\n }\n }\n return super.getCapability(capability, facing);\n }\n\n public void setCorePosition(Vector3i corePosition) {\n this.corePosition = corePosition;\n coreReference = new WeakReference<TileColossalChest>(null);\n }\n\n protected TileColossalChest getCore() {\n if(corePosition == null) {\n return null;\n }\n if (coreReference.get() == null) {\n coreReference = new WeakReference<TileColossalChest>(\n TileHelpers.getSafeTile(getWorld(), new BlockPos(corePosition), TileColossalChest.class).orElse(null));\n }\n return coreReference.get();\n }\n\n}" ]
import com.google.common.collect.Lists; import lombok.Data; import lombok.EqualsAndHashCode; import net.minecraft.block.BlockState; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemUseContext; import net.minecraft.util.ActionResultType; import net.minecraft.util.Direction; import net.minecraft.util.Hand; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.vector.Vector3d; import net.minecraft.util.math.vector.Vector3i; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TranslationTextComponent; import net.minecraft.world.World; import org.apache.commons.lang3.tuple.Pair; import org.cyclops.colossalchests.Advancements; import org.cyclops.colossalchests.block.ChestMaterial; import org.cyclops.colossalchests.block.ChestWall; import org.cyclops.colossalchests.block.ColossalChest; import org.cyclops.colossalchests.block.IBlockChestMaterial; import org.cyclops.colossalchests.block.Interface; import org.cyclops.colossalchests.tileentity.TileColossalChest; import org.cyclops.colossalchests.tileentity.TileInterface; import org.cyclops.cyclopscore.block.multi.DetectionResult; import org.cyclops.cyclopscore.datastructure.Wrapper; import org.cyclops.cyclopscore.helper.BlockHelpers; import org.cyclops.cyclopscore.helper.InventoryHelpers; import org.cyclops.cyclopscore.helper.MinecraftHelpers; import org.cyclops.cyclopscore.helper.TileHelpers; import org.cyclops.cyclopscore.inventory.PlayerInventoryIterator; import org.cyclops.cyclopscore.inventory.SimpleInventory; import java.util.List;
package org.cyclops.colossalchests.item; /** * An item to upgrade chests to the next tier. * @author rubensworks */ @EqualsAndHashCode(callSuper = false) @Data public class ItemUpgradeTool extends Item { private final boolean upgrade; public ItemUpgradeTool(Properties properties, boolean upgrade) { super(properties); this.upgrade = upgrade; } @Override public ActionResultType onItemUseFirst(ItemStack itemStack, ItemUseContext context) { BlockState blockState = context.getWorld().getBlockState(context.getPos());
if (blockState.getBlock() instanceof IBlockChestMaterial
4
ArtificialPB/DevelopmentKit
src/com/artificial/cachereader/fs/RT4CacheSystem.java
[ "public enum GameType {\n RT6(\"runescape\"),\n RT4(\"oldschool\");\n\n private final String folderName;\n\n GameType(final String folderName) {\n this.folderName = folderName;\n }\n\n public String getFolderName() {\n return folderName;\n }\n}", "public class ItemDefinitionLoader extends ProtocolWrapperLoader<ItemDefinition> {\n public ItemDefinitionLoader(final RT4CacheSystem cacheSystem) {\n super(cacheSystem, cacheSystem.getCacheSource().getCacheType(2).getArchive(10));\n }\n\n @Override\n public ItemDefinition load(final int id) {\n final FileData data = getValidFile(id);\n ItemDefinition ret = new ItemDefinition(this, id);\n ret.decode(data.getDataAsStream());\n fixItem(ret);\n return ret;\n }\n\n private void fixItem(final ItemDefinition item) {\n if (item.noteTemplateId != -1) {\n fixNotedItem(item);\n }\n //we set shift action here in case the actions don't get loaded before the shift index is\n if (item.shiftActionIndex != -2 && item.shiftActionIndex < item.actions.length) {\n item.shiftAction = item.actions[item.shiftActionIndex];\n }\n }\n\n private void fixNotedItem(final ItemDefinition item) {\n final ItemDefinition note = this.load(item.noteId);\n item.value = note.value;\n item.name = note.name;\n item.stackable = true;\n item.members = note.members;\n item.noted = true;\n }\n\n}", "public class NpcDefinitionLoader extends ProtocolWrapperLoader<NpcDefinition> {\n public NpcDefinitionLoader(final RT4CacheSystem cacheSystem) {\n super(cacheSystem, cacheSystem.getCacheSource().getCacheType(2).getArchive(9));\n }\n\n @Override\n public NpcDefinition load(final int id) {\n FileData data = getValidFile(id);\n NpcDefinition ret = new NpcDefinition(this, id);\n ret.decode(data.getDataAsStream());\n return ret;\n }\n}", "public class ObjectDefinitionLoader extends ProtocolWrapperLoader<ObjectDefinition> {\n public ObjectDefinitionLoader(final RT4CacheSystem cacheSystem) {\n super(cacheSystem, cacheSystem.getCacheSource().getCacheType(2).getArchive(6));\n }\n\n @Override\n public ObjectDefinition load(final int id) {\n FileData data = getValidFile(id);\n ObjectDefinition ret = new ObjectDefinition(this, id);\n ret.decode(data.getDataAsStream());\n return ret;\n }\n}", "public class ScriptLoader extends ProtocolWrapperLoader<Script> {\n public ScriptLoader(final RT4CacheSystem cacheSystem) {\n super(cacheSystem, cacheSystem.getCacheSource().getCacheType(2).getArchive(14));\n }\n\n @Override\n public Script load(final int id) {\n final FileData data = getValidFile(id);\n final Script definition = new Script(this, id);\n definition.decode(data.getDataAsStream());\n return definition;\n }\n\n}", "public class WidgetLoader extends WrapperLoader<Widget> {\n private final CacheType cache;\n\n public WidgetLoader(RT4CacheSystem cacheSystem) {\n super(cacheSystem);\n cache = cacheSystem.getCacheSource().getCacheType(3);\n }\n\n @Override\n public Widget load(final int widgetId) {\n final Archive archive = getValidArchive(widgetId);\n final ArchiveMeta meta = cache.getTable().getEntries().get(archive.getId());\n final Widget ret = new Widget(this, widgetId);\n ret.components = new Component[meta.getChildren().size()];\n int index = 0;\n for (final Map.Entry<Integer, FileMeta> b : meta.getChildren().entrySet()) {\n final int fileId = b.getValue().getId();\n final FileData data = archive.getFile(fileId);\n final int componentId = (widgetId << 16) + fileId;\n final Component comp = new Component(this, componentId);\n comp.decode(data.getDataAsStream());\n ret.components[comp.index = index++] = comp;\n }\n return ret;\n }\n\n @Override\n public boolean canLoad(int id) {\n return getWidgetArchive(id) != null;\n }\n\n private Archive getValidArchive(final int widgetId) {\n Archive ret = getWidgetArchive(widgetId);\n if (ret == null)\n throw new IllegalArgumentException(\"Bad id\");\n return ret;\n }\n\n private Archive getWidgetArchive(final int widgetId) {\n return cache.getArchive(widgetId);\n }\n\n public List<Widget> loadAll() {\n final List<Widget> ret = new LinkedList<>();\n for (final Map.Entry<Integer, ArchiveMeta> entry : cache.getTable().getEntries().entrySet()) {\n ret.add(load(entry.getKey()));\n }\n return ret;\n }\n}" ]
import com.artificial.cachereader.GameType; import com.artificial.cachereader.wrappers.rt4.loaders.ItemDefinitionLoader; import com.artificial.cachereader.wrappers.rt4.loaders.NpcDefinitionLoader; import com.artificial.cachereader.wrappers.rt4.loaders.ObjectDefinitionLoader; import com.artificial.cachereader.wrappers.rt4.loaders.ScriptLoader; import com.artificial.cachereader.wrappers.rt4.loaders.WidgetLoader;
package com.artificial.cachereader.fs; public class RT4CacheSystem extends CacheSystem<RT4CacheSystem> { public final ItemDefinitionLoader itemLoader; public final ObjectDefinitionLoader objectLoader; public final NpcDefinitionLoader npcLoader;
public final ScriptLoader scriptLoader;
4
olivierlemasle/java-certificate-authority
ca-api/src/main/java/io/github/olivierlemasle/caweb/cli/CreateCertificate.java
[ "public static CsrBuilder createCsr() {\n return new CsrBuilderImpl();\n}", "public static DnBuilder dn() {\n return new DnBuilderImpl();\n}", "public static RootCertificate loadRootCertificate(final String keystorePath,\n final char[] password, final String alias) {\n return RootCertificateLoader.loadRootCertificate(keystorePath, password, alias);\n}", "public interface Certificate {\n\n public X509Certificate getX509Certificate();\n\n public String print();\n\n public void save(File file);\n\n public void save(String fileName);\n\n public CertificateWithPrivateKey attachPrivateKey(PrivateKey privateKey);\n\n}", "public interface CertificateWithPrivateKey extends Certificate {\n\n public KeyStore addToKeystore(KeyStore keyStore, String alias);\n\n public KeyStore saveInPkcs12Keystore(String alias);\n\n public void exportPkcs12(final String keystorePath, final char[] keystorePassword,\n final String alias);\n\n public void exportPkcs12(final File keystoreFile, final char[] keystorePassword,\n final String alias);\n\n public PrivateKey getPrivateKey();\n\n public String printKey();\n\n public void saveKey(File file);\n\n public void saveKey(String fileName);\n}", "public interface CsrWithPrivateKey extends CSR {\n\n public PrivateKey getPrivateKey();\n}", "public interface DistinguishedName {\n\n public X500Name getX500Name();\n\n public X500Principal getX500Principal();\n\n public byte[] getEncoded();\n\n public String getName();\n}", "public interface RootCertificate extends CertificateWithPrivateKey {\n\n public Signer signCsr(final CSR request);\n\n}" ]
import static io.github.olivierlemasle.ca.CA.createCsr; import static io.github.olivierlemasle.ca.CA.dn; import static io.github.olivierlemasle.ca.CA.loadRootCertificate; import io.dropwizard.cli.Command; import io.dropwizard.setup.Bootstrap; import io.github.olivierlemasle.ca.Certificate; import io.github.olivierlemasle.ca.CertificateWithPrivateKey; import io.github.olivierlemasle.ca.CsrWithPrivateKey; import io.github.olivierlemasle.ca.DistinguishedName; import io.github.olivierlemasle.ca.RootCertificate; import net.sourceforge.argparse4j.inf.Namespace; import net.sourceforge.argparse4j.inf.Subparser;
package io.github.olivierlemasle.caweb.cli; public class CreateCertificate extends Command { public CreateCertificate() { super("createcert", "Creates a signed certificate."); } @Override public void configure(final Subparser parser) { parser.addArgument("-s", "--subject") .dest("subject") .type(String.class) .required(true) .help("The subject CN"); parser.addArgument("-r", "--signer") .dest("signer") .type(String.class) .required(true) .help("The CN of the root certificate."); parser.addArgument("-i", "--in") .dest("in") .type(String.class) .required(true) .help("The name of the root certificate keystore"); parser.addArgument("-p", "--password") .dest("password") .type(String.class) .required(true) .help("The password of the keystore"); parser.addArgument("-c", "--cert") .dest("cert") .type(String.class) .required(true) .help("The certificate file to be created"); parser.addArgument("-k", "--key") .dest("key") .type(String.class) .required(true) .help("The key file to be created"); } @Override public void run(final Bootstrap<?> bootstrap, final Namespace namespace) throws Exception { final String subject = namespace.getString("subject"); final String signer = namespace.getString("signer"); final String in = namespace.getString("in"); final String password = namespace.getString("password"); final String cert = namespace.getString("cert"); final String key = namespace.getString("key"); final RootCertificate root = loadRootCertificate(in, password.toCharArray(), signer);
final DistinguishedName dn = dn().setCn(subject).build();
1
ivannov/predcomposer
src/test/java/com/nosoftskills/predcomposer/browser/fixtures/TestDataInserter.java
[ "@Stateless\npublic class CompetitionsService implements Serializable {\n\n public static final String DEFAULT_COMPETITION_NAME = \"Champions League 2016-2017\";\n\n private static final long serialVersionUID = 7432416155835050214L;\n\n @PersistenceContext\n EntityManager entityManager;\n\n private static Competition activeCompetition;\n\n public Competition findCompetitionById(Long competitionId) {\n return entityManager.find(Competition.class, competitionId);\n }\n\n\n public Competition findActiveCompetition() {\n if (activeCompetition == null) {\n TypedQuery<Competition> competitionQuery = entityManager.createQuery(\"SELECT c FROM Competition c WHERE c.name = :defaultCompetition\", Competition.class);\n competitionQuery.setParameter(\"defaultCompetition\", DEFAULT_COMPETITION_NAME);\n activeCompetition = competitionQuery.getSingleResult();\n }\n return activeCompetition;\n }\n\n public Competition storeCompetition(Competition competition) {\n if (competition.getId() == null) {\n entityManager.persist(competition);\n return competition;\n } else {\n return entityManager.merge(competition);\n }\n }\n\n public Set<Game> getGamesForCompetition(Competition selectedCompetition) {\n Competition mergedCompetition = entityManager.merge(selectedCompetition);\n return mergedCompetition.getGames();\n }\n}", "@Entity\n@XmlRootElement\n@NamedQueries({\n @NamedQuery(name = \"findCompetitionByName\", query = \"SELECT c FROM Competition c WHERE c.name = :competitionName\"),\n})\npublic class Competition implements Serializable {\n\n private static final long serialVersionUID = 7251381689096178933L;\n\n @Id\n\t@GeneratedValue(strategy = GenerationType.AUTO)\n\tprivate Long id;\n\n\t@Version\n\tprivate int version;\n\n\t@Column(nullable = false)\n\tprivate String name;\n\n\tprivate String description;\n\n\t@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)\n\tprivate Set<Game> games = new HashSet<>();\n\n public Competition() {\n }\n\n public Competition(String name) {\n this(name, \"\");\n }\n\n public Competition(String name, String description) {\n this.name = name;\n this.description = description;\n }\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n @XmlTransient\n public int getVersion() {\n return version;\n }\n\n public void setVersion(int version) {\n this.version = version;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n @XmlTransient\n public Set<Game> getGames() {\n return games;\n }\n\n public void setGames(Set<Game> games) {\n this.games = games;\n }\n\n @Override\n public String toString() {\n return \"Competition{\" +\n \"id=\" + id +\n \", name='\" + name + '\\'' +\n \", description='\" + description + '\\'' +\n '}';\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (!(o instanceof Competition))\n return false;\n Competition that = (Competition) o;\n return Objects.equals(name, that.name) &&\n Objects.equals(description, that.description);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(name, description);\n }\n}", "@Entity\n@XmlRootElement\n@NamedQueries({\n @NamedQuery(name = \"getRecentGames\", query = \"SELECT g from Game g WHERE g.gameTime <= :kickoffTime AND g.locked = FALSE\")\n})\npublic class Game implements Serializable, Comparable<Game> {\n\n private static final long serialVersionUID = -7167764360968863333L;\n\n private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern(\n \"dd MMM, HH:mm\");\n\n @Id\n\t@GeneratedValue(strategy = GenerationType.AUTO)\n\tprivate Long id;\n\n\t@Version\n\tprivate int version;\n\n\t@Column(nullable = false)\n\tprivate String homeTeam;\n\n\t@Column(nullable = false)\n\tprivate String awayTeam;\n\n\t@Column\n\tprivate String result;\n\n\t@Column(nullable = false)\n\tprivate LocalDateTime gameTime;\n\n\t@OneToMany(mappedBy = \"forGame\", cascade = CascadeType.ALL, orphanRemoval = true)\n\tprivate Set<Prediction> predictions = new HashSet<>();\n\n\tprivate boolean locked = false;\n\n public Game() {\n }\n\n public Game(String homeTeam, String awayTeam, LocalDateTime gameTime) {\n this(homeTeam, awayTeam, null, gameTime, false);\n }\n\n public Game(String homeTeam, String awayTeam, String result, LocalDateTime gameTime, boolean locked) {\n this.homeTeam = homeTeam;\n this.awayTeam = awayTeam;\n this.result = result;\n this.gameTime = gameTime;\n this.locked = locked;\n }\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n @XmlTransient\n public int getVersion() {\n return version;\n }\n\n public void setVersion(int version) {\n this.version = version;\n }\n\n public String getHomeTeam() {\n return homeTeam;\n }\n\n public void setHomeTeam(String homeTeam) {\n this.homeTeam = homeTeam;\n }\n\n public String getAwayTeam() {\n return awayTeam;\n }\n\n public void setAwayTeam(String awayTeam) {\n this.awayTeam = awayTeam;\n }\n\n public String getResult() {\n return result;\n }\n\n public void setResult(String result) {\n this.result = result;\n }\n\n public LocalDateTime getGameTime() {\n return gameTime;\n }\n\n public String getGameTimeFormatted() {\n return gameTime.format(DATE_TIME_FORMATTER);\n }\n\n public void setGameTime(LocalDateTime gameTime) {\n this.gameTime = gameTime;\n }\n\n @XmlTransient\n public Set<Prediction> getPredictions() {\n return predictions;\n }\n\n public void setPredictions(\n Set<Prediction> predictions) {\n this.predictions = predictions;\n }\n\n public boolean isLocked() {\n return locked;\n }\n\n public void setLocked(boolean locked) {\n this.locked = locked;\n }\n\n @Override\n public String toString() {\n return \"Game{\" +\n \"id=\" + id +\n \", homeTeam='\" + homeTeam + '\\'' +\n \", awayTeam='\" + awayTeam + '\\'' +\n \", result='\" + result + '\\'' +\n \", gameTime=\" + gameTime +\n \", locked=\" + locked +\n '}';\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (!(o instanceof Game))\n return false;\n Game game = (Game) o;\n return Objects.equals(homeTeam, game.homeTeam) &&\n Objects.equals(awayTeam, game.awayTeam) &&\n Objects.equals(gameTime, game.gameTime);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(homeTeam, awayTeam, gameTime);\n }\n\n @Override\n public int compareTo(Game game) {\n return this.getGameTime().compareTo(game.getGameTime());\n }\n}", "@Entity\n@XmlRootElement\n@Table(name = \"Users\")\n@NamedQueries({\n @NamedQuery(name = \"findUserByNameAndPassword\", query = \"SELECT u FROM User u WHERE u.userName = :userName AND u.password = :password\"),\n @NamedQuery(name = \"getAllUsers\", query = \"SELECT u FROM User u\")\n})\npublic class User implements Serializable {\n\n\tprivate static final long serialVersionUID = -3718072367022295097L;\n\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.AUTO)\n\tprivate Long id;\n\n\t@Version\n\tprivate int version;\n\n\t@Column(nullable = false)\n\tprivate String userName;\n\n\t@Column(nullable = false)\n\tprivate String password;\n\n\t@Column(nullable = false)\n\tprivate String email;\n\n\tprivate String firstName;\n\n\tprivate String lastName;\n\n\t@Column(nullable = false)\n\tprivate Boolean isAdmin = false;\n\n\t@Lob\n\tprivate byte[] avatar;\n\n\t@OneToMany(mappedBy = \"byUser\", cascade = CascadeType.ALL, orphanRemoval = true)\n\tprivate Set<Prediction> predictions = new HashSet<>();\n\n\tpublic User() {\n\t}\n\n\tpublic User(String userName, String password, String email) {\n\t\tthis(userName, password, email, null, null, false);\n\t}\n\n\tpublic User(String userName, String password, String email,\n\t\t\tString firstName, String lastName, boolean isAdmin) {\n\t\tthis(userName, password, email, firstName, lastName, isAdmin, null);\n\t}\n\n\tpublic User(String userName, String password, String email,\n\t\t\tString firstName, String lastName, boolean admin, byte[] avatar) {\n\t\tthis.userName = userName;\n\t\tthis.password = password;\n\t\tthis.email = email;\n\t\tthis.firstName = firstName;\n\t\tthis.lastName = lastName;\n\t\tthis.isAdmin = admin;\n\t\tthis.avatar = avatar;\n\t}\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n @XmlTransient\n\tpublic int getVersion() {\n\t\treturn version;\n\t}\n\n\tpublic void setVersion(int version) {\n\t\tthis.version = version;\n\t}\n\n\tpublic String getUserName() {\n\t\treturn userName;\n\t}\n\n\tpublic void setUserName(String userName) {\n\t\tthis.userName = userName;\n\t}\n\n @XmlTransient\n\tpublic String getPassword() {\n\t\treturn password;\n\t}\n\n\tpublic void setPassword(String password) {\n\t\tthis.password = password;\n\t}\n\n\tpublic String getEmail() {\n\t\treturn email;\n\t}\n\n\tpublic void setEmail(String email) {\n\t\tthis.email = email;\n\t}\n\n\tpublic String getFirstName() {\n\t\treturn firstName;\n\t}\n\n\tpublic void setFirstName(String firstName) {\n\t\tthis.firstName = firstName;\n\t}\n\n\tpublic String getLastName() {\n\t\treturn lastName;\n\t}\n\n\tpublic void setLastName(String lastName) {\n\t\tthis.lastName = lastName;\n\t}\n\n\tpublic Boolean getIsAdmin() {\n\t\treturn isAdmin;\n\t}\n\n\tpublic void setIsAdmin(Boolean admin) {\n\t\tthis.isAdmin = admin;\n\t}\n\n @XmlTransient\n public Set<Prediction> getPredictions() {\n return this.predictions;\n }\n\n public void setPredictions(final Set<Prediction> predictions) {\n this.predictions = predictions;\n }\n\n\tpublic byte[] getAvatar() {\n\t\treturn avatar;\n\t}\n\n\tpublic void setAvatar(byte[] avatar) {\n\t\tthis.avatar = avatar;\n\t}\n\n @Override\n public String toString() {\n return \"User{\" +\n \"id=\" + id +\n \", userName='\" + userName + '\\'' +\n \", password='\" + password + '\\'' +\n \", email='\" + email + '\\'' +\n \", firstName='\" + firstName + '\\'' +\n \", lastName='\" + lastName + '\\'' +\n '}';\n }\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (this == o)\n\t\t\treturn true;\n\t\tif (!(o instanceof User))\n\t\t\treturn false;\n\t\tUser user = (User) o;\n\t\treturn Objects.equals(userName, user.userName)\n\t\t\t\t&& Objects.equals(password, user.password)\n\t\t\t\t&& Objects.equals(email, user.email)\n\t\t\t\t&& Objects.equals(isAdmin, user.isAdmin);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(userName, password, email, isAdmin);\n\t}\n}", "public static String hashPassword(String originalPassword) {\n try {\n MessageDigest md = MessageDigest.getInstance(\"SHA\");\n return new String(md.digest(originalPassword.getBytes()));\n } catch (NoSuchAlgorithmException e) {\n return originalPassword;\n }\n}" ]
import static com.nosoftskills.predcomposer.user.PasswordHashUtil.hashPassword; import com.nosoftskills.predcomposer.competition.CompetitionsService; import com.nosoftskills.predcomposer.model.Competition; import com.nosoftskills.predcomposer.model.Game; import com.nosoftskills.predcomposer.model.User; import javax.annotation.PostConstruct; import javax.ejb.Singleton; import javax.ejb.Startup; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.Arrays;
/* * Copyright 2016 Microprofile.io * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nosoftskills.predcomposer.browser.fixtures; @Singleton @Startup public class TestDataInserter { @PersistenceContext private EntityManager entityManager; @PostConstruct public void insertTestData() { User user1 = new User("ivan", hashPassword("ivan"), "ivan@example.com", "Ivan", "Ivanov", true); User user2 = new User("koko", hashPassword("koko"), "koko@example.com", "Koko", "Stefanov", false); LocalDate tomorrow = LocalDate.now().plusDays(1); LocalDateTime gameTime = LocalDateTime.of(tomorrow, LocalTime.of(21, 45));
Competition competition = new Competition(CompetitionsService.DEFAULT_COMPETITION_NAME);
1
KlubJagiellonski/pola-android
app/src/test/java/pl/pola_app/ui/activity/MainPresenterTest.java
[ "public class TestApplication extends Application {\n}", "public class EventLogger {\n\n private Context c;\n\n public EventLogger(Context context) {\n c = context;\n }\n\n public void logSearch(String result, String deviceId, String source) {\n if (!BuildConfig.USE_FIREBASE) {\n return;\n }\n\n Bundle bundle = new Bundle();\n bundle.putString(\"code\", result);\n bundle.putString(\"device_id\", deviceId);\n bundle.putString(\"source\", source);\n FirebaseAnalytics.getInstance(c).logEvent(\"scan_code\", bundle);\n }\n\n public void logCustom(String eventName, Bundle bundle) {\n if (!BuildConfig.USE_FIREBASE) {\n return;\n }\n\n FirebaseAnalytics.getInstance(c).logEvent(eventName, bundle);\n }\n\n public void logContentView(String contentName, String contentType, String contentId, String code, String deviceId) {\n if (!BuildConfig.USE_FIREBASE) {\n return;\n }\n\n Bundle bundle = new Bundle();\n bundle.putString(\"company\", contentName);\n bundle.putString(\"device_id\", deviceId);\n bundle.putString(\"product_id\", contentId);\n bundle.putString(\"code\", code);\n FirebaseAnalytics.getInstance(c).logEvent(contentType, bundle);\n }\n\n public void logException(Throwable throwable) {\n if (!BuildConfig.USE_FIREBASE) {\n return;\n }\n\n try {\n FirebaseCrashlytics.getInstance().recordException(throwable);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n public void logLevelStart(String levelName, String productId, String deviceId) {\n if(!BuildConfig.USE_FIREBASE) {\n return;\n }\n\n Bundle bundle = new Bundle();\n bundle.putString(\"device_id\", deviceId);\n bundle.putString(\"code\", productId);\n FirebaseAnalytics.getInstance(c).logEvent(levelName+\"_started\", bundle);\n }\n\n public void logLevelEnd(String levelName, String productId, String deviceId) {\n if(!BuildConfig.USE_FIREBASE) {\n return;\n }\n\n Bundle bundle = new Bundle();\n bundle.putString(\"device_id\", deviceId);\n bundle.putString(\"code\", productId);\n FirebaseAnalytics.getInstance(c).logEvent(levelName+\"_finished\", bundle);\n }\n\n public void logMenuItemOpened(String itemName, String deviceId) {\n if(!BuildConfig.USE_FIREBASE) {\n return;\n }\n\n Bundle bundle = new Bundle();\n bundle.putString(\"item\", itemName);\n bundle.putString(\"device_id\", deviceId);\n FirebaseAnalytics.getInstance(c).logEvent(\"menu_item_opened\", bundle);\n }\n\n public void logSupportPolaButtonClick(String deviceId) {\n if(!BuildConfig.USE_FIREBASE) {\n return;\n }\n\n Bundle bundle = new Bundle();\n bundle.putString(\"device_id\", deviceId);\n FirebaseAnalytics.getInstance(c).logEvent(\"donate_opened\", bundle);\n }\n}", "public class SessionId {\n private static final String PREF_SESSION_GUID = \"session_guid\";\n private static final Object lock = new Object();\n private final String sessionId;\n\n public static SessionId create(Context context) {\n return new SessionId(context);\n }\n\n private SessionId(Context context) {\n sessionId = init(context);\n }\n\n public String get() {\n return sessionId;\n }\n\n private static SharedPreferences getDefaultSharedPreferences(Context context) {\n return PreferenceManager.getDefaultSharedPreferences(context);\n }\n\n private static String init(Context context) {\n synchronized (lock) {\n SharedPreferences pref = getDefaultSharedPreferences(context);\n String sessionGuid = pref.getString(PREF_SESSION_GUID, null);\n\n if (sessionGuid == null) {\n sessionGuid = UUID.randomUUID().toString();\n final SharedPreferences.Editor editor = pref.edit();\n editor.putString(PREF_SESSION_GUID, sessionGuid);\n editor.apply();\n }\n return sessionGuid;\n }\n }\n}", "@Parcel\npublic class SearchResult {\n public Integer product_id;\n public String code;\n public String name;\n public String card_type;\n public String altText;\n public ArrayList<Company> companies;\n\n public ReportV4 report; \n\n public String friend_text;\n\n public Donate donate;\n\n public boolean askForSupport() {\n return donate != null;\n }\n\n\n}", "public class SearchUtil {\n\n public static SearchResult createSearchResult(int id) {\n SearchResult searchResult = new SearchResult();\n\n searchResult.product_id = id;\n searchResult.code = \"code\" + id;\n searchResult.card_type = \"card_type\" + id;\n searchResult.altText = \"altText\" + id;\n\n ReportV4 report = new ReportV4();\n searchResult.report = report;\n searchResult.report.text = \"report_text\" + id;\n searchResult.report.button_text = \"report_button_text\" + id;\n searchResult.report.button_type = \"report_button_type\" + id;\n\n ArrayList<Company> companies = new ArrayList<Company>();\n Company company = new Company();\n companies.add(company);\n searchResult.companies = companies;\n searchResult.companies.get(0).description = \"description\" + id;\n searchResult.name = searchResult.name != null ? searchResult.name + id : searchResult.companies.get(0).name + id;\n searchResult.companies.get(0).plScore = 1 + id;\n searchResult.companies.get(0).plCapital = 2 + id;\n searchResult.companies.get(0).plWorkers = 3 + id;\n searchResult.companies.get(0).plRnD = 4 + id;\n searchResult.companies.get(0).plRegistered = 5 + id;\n searchResult.companies.get(0).plNotGlobEnt = 6 + id;\n\n return searchResult;\n }\n}", "public class ProductList {\n @NonNull private final List<SearchResult> searchResults;\n @Nullable private OnProductListChanged onProductListChanged;\n\n public static ProductList create(@Nullable Bundle bundle) {\n final List<SearchResult> searchResults;\n if (bundle != null) {\n searchResults = Parcels.unwrap(bundle.getParcelable(SearchResult.class.getName()));\n } else {\n searchResults = new ArrayList<>();\n }\n\n return new ProductList(searchResults);\n }\n\n private ProductList(@NonNull final List<SearchResult> searchResults) {\n this.searchResults = searchResults;\n }\n\n public void setOnProductListChanged(@Nullable OnProductListChanged onProductListChanged) {\n this.onProductListChanged = onProductListChanged;\n }\n\n\n public void writeToBundle(@NonNull final Bundle bundle) {\n bundle.putParcelable(SearchResult.class.getName(), Parcels.wrap(searchResults));\n }\n\n public void addProduct(SearchResult searchResult) {\n if (searchResults.size() > 0 && searchResults.get(0) == null) {\n searchResults.set(0, searchResult);\n } else {\n searchResults.add(0, searchResult);\n }\n notifyOnChanged();\n }\n\n public void createProductPlaceholder() {\n searchResults.add(0, null);\n notifyOnChanged();\n }\n\n public void removeProductPlaceholder() {\n if (searchResults.size() > 0 && searchResults.get(0) == null) {\n searchResults.remove(0);\n notifyOnChanged();\n }\n }\n\n public boolean itemExists(String code) {\n for (SearchResult p : searchResults) {\n if (p != null) {\n if (p.code.equals(code)) {\n searchResults.remove(p);\n searchResults.add(0, p);\n notifyOnChanged();\n return true;\n }\n }\n }\n\n return false;\n }\n\n public int size() {\n return searchResults.size();\n }\n\n public SearchResult get(int position) {\n return searchResults.get(position);\n }\n\n private void notifyOnChanged() {\n if (onProductListChanged != null) {\n onProductListChanged.onChanged();\n }\n }\n\n}" ]
import android.os.Bundle; import android.util.Log; import com.squareup.otto.Bus; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import pl.pola_app.TestApplication; import pl.pola_app.helpers.EventLogger; import pl.pola_app.helpers.SessionId; import pl.pola_app.helpers.SettingsPreference; import pl.pola_app.model.SearchResult; import pl.pola_app.network.Api; import pl.pola_app.testutil.SearchUtil; import pl.pola_app.ui.adapter.ProductList; import retrofit2.Call; import retrofit2.Response; import static org.junit.Assert.fail; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when;
package pl.pola_app.ui.activity; @Config(application = TestApplication.class) @RunWith(RobolectricTestRunner.class) public class MainPresenterTest { @Mock private MainViewBinder viewBinder; @Mock private ProductList productList; @Mock private Api api; @Mock private Bus eventBus; @Mock private EventLogger logger; @Mock
private SessionId sessionId;
2
johndavidbustard/RoughWorld
src/utils/shapes/skinned/Animate.java
[ "public class GeneralMatrixDouble implements Serializable\r\n{\r\n\tprivate static final long serialVersionUID = 1L;\r\n\r\n\tpublic static final double EPSILON=5.9e-8f;\r\n\tpublic int width; //columns\r\n\tpublic int height; //rows\r\n\tpublic double[] value; //array of values\r\n\r\n\tpublic static void main(String[] list) throws Exception \r\n {\r\n\t\tGeneralMatrixDouble pose = new GeneralMatrixDouble(3,3);\r\n\t\tGeneralMatrixDouble vpose = new GeneralMatrixDouble(3,3);\r\n\t\tGeneralMatrixDouble euler = new GeneralMatrixDouble(3,1);\r\n\t\t\r\n\t\tGeneralMatrixDouble tests = new GeneralMatrixDouble(3);\r\n\r\n\t\tdouble v = Math.PI;\r\n\t\ttests.push_back_row(0.0,0.0,0.0);\r\n\t\ttests.push_back_row(v,0.0,0.0);\r\n\t\ttests.push_back_row(0.0,v,0.0);\r\n\t\ttests.push_back_row(v,v,0.0);\r\n\t\ttests.push_back_row(0.0,0.0,v);\r\n\t\ttests.push_back_row(v,0.0,v);\r\n\t\ttests.push_back_row(0.0,v,v);\r\n\t\ttests.push_back_row(v,v,v);\r\n\r\n\t\tfor(int i=0;i<tests.height;i++)\r\n\t\t{\r\n\t\t\tpose.set3DTransformRotationYXZ(tests.value[i*3+0], tests.value[i*3+1], tests.value[i*3+2]);\r\n\t\t\tGeneralMatrixDouble.getEulerYXZ(pose, euler);\r\n\t\t\tdouble errx = euler.value[0]-tests.value[i*3+0];\r\n\t\t\tdouble erry = euler.value[1]-tests.value[i*3+1];\r\n\t\t\tdouble errz = euler.value[2]-tests.value[i*3+2];\r\n\t\t\tSystem.out.println(\"err \"+i+\" x:\"+errx+\" y:\"+erry+\" z:\"+errz);\r\n\t\t\tvpose.set3DTransformRotationYXZ(euler.value[0], euler.value[1], euler.value[2]);\r\n\t\t\t\r\n\t\t}\r\n }\r\n\t\r\n\tpublic void printTransform2()\r\n\t{\r\n\t\tSystem.out.println(\"Xx:\"+value[0+0]+ \"\\tXy:\"+value[1+0]);\r\n\t\tSystem.out.println(\"Yx:\"+value[0+2]+ \"\\tYy:\"+value[1+2]);\r\n\t}\r\n\tpublic void printTransform()\r\n\t{\r\n\t\tSystem.out.println(\"Xx:\"+value[0+0]+ \"\\tXy:\"+value[1+0]+ \"\\tXz:\"+value[2+0]);\r\n\t\tSystem.out.println(\"Yx:\"+value[0+4]+ \"\\tYy:\"+value[1+4]+ \"\\tYz:\"+value[2+4]);\r\n\t\tSystem.out.println(\"Zx:\"+value[0+8]+ \"\\tZy:\"+value[1+8]+ \"\\tZz:\"+value[2+8]);\r\n\t\tSystem.out.println(\"Tx:\"+value[0+12]+\"\\tTy:\"+value[1+12]+\"\\tTz:\"+value[2+12]);\r\n\t}\r\n\tpublic void printProjection()\r\n\t{\r\n\t\tSystem.out.println(\"Xx:\"+value[0+0]+ \"\\tXy:\"+value[1+0]+ \"\\tXz:\"+value[2+0]);\r\n\t\tSystem.out.println(\"Yx:\"+value[0+4]+ \"\\tYy:\"+value[1+4]+ \"\\tYz:\"+value[2+4]);\r\n\t\tSystem.out.println(\"Zx:\"+value[0+8]+ \"\\tZy:\"+value[1+8]+ \"\\tZz:\"+value[2+8]);\r\n\t\tSystem.out.println(\"Tx:\"+value[0+12]+\"\\tTy:\"+value[1+12]+\"\\tTz:\"+value[2+12]);\r\n\t\tSystem.out.println(\"Hx:\"+value[3+0]+ \"\\tHy:\"+value[3+4]+ \"\\tHz:\"+value[3+8]+\"\\tHt:\"+value[3+12]);\r\n\t}\r\n\t\r\n\tpublic static double calculateMachineEpsilonDouble() \r\n\t{\r\n double machEps = 1.0f;\r\n \r\n do {\r\n machEps /= 2.0f;\r\n }\r\n while ((double)(1.0 + (machEps/2.0)) != 1.0);\r\n \r\n return machEps;\r\n }\r\n\t\r\n\tpublic GeneralMatrixDouble(double[] v)\r\n\t{\r\n\t\tthis.width = 1;\r\n\t\tthis.height = v.length;\r\n\t\tvalue = v;\r\n\t}\r\n\tpublic GeneralMatrixDouble(double a)\r\n\t{\r\n\t\tthis.width = 1;\r\n\t\tthis.height = 1;\r\n\t\tvalue = new double[1];\r\n\t\tvalue[0] = a;\r\n\t}\r\n\tpublic GeneralMatrixDouble(double a,double b)\r\n\t{\r\n\t\tthis.width = 1;\r\n\t\tthis.height = 2;\r\n\t\tvalue = new double[2];\r\n\t\tvalue[0] = a;\r\n\t\tvalue[1] = b;\r\n\t}\r\n\tpublic GeneralMatrixDouble(GeneralMatrixDouble a)\r\n\t{\r\n\t\tthis.width = a.width;\r\n\t\tthis.height = a.height;\r\n\t\tvalue = new double[a.width*a.height];\r\n\t\tset(a);\r\n\t}\r\n\tpublic GeneralMatrixDouble(GeneralMatrixFloat a)\r\n\t{\r\n\t\tthis.width = a.width;\r\n\t\tthis.height = a.height;\r\n\t\tvalue = new double[a.width*a.height];\r\n\t\tset(a);\r\n\t}\r\n\tpublic GeneralMatrixDouble(int width,int height)\r\n\t{\r\n\t\tthis.width = width;\r\n\t\tthis.height = height;\r\n\t\tvalue = new double[width*height];\r\n\t}\r\n\tpublic GeneralMatrixDouble(int width,int height,double[] v)\r\n\t{\r\n\t\tthis.width = width;\r\n\t\tthis.height = height;\r\n\t\tvalue = v;\r\n\t}\r\n\tpublic GeneralMatrixDouble()\r\n\t{\r\n\t\twidth = 0;\r\n\t\theight = 0;\r\n\t}\r\n\r\n\t public boolean isequal(GeneralMatrixDouble m)\r\n\t {\r\n\t\t if(width!=m.width)\r\n\t\t\t return false;\r\n\t\t if(height!=m.height)\r\n\t\t\t return false;\r\n\t\t for (int i = 0; i < width*height; i++) \r\n\t\t {\r\n\t\t\t if(value[i]!=m.value[i])\r\n\t\t\t\t return false;\r\n\t\t }\t\t \r\n\t\t return true;\r\n\t }\r\n\r\n\t \r\n\tpublic void clear(double v)\r\n\t{\r\n\t\t for (int i = 0; i < width*height; i++)\r\n\t\t {\r\n\t\t\t value[i] = v;\r\n\t\t }\r\n\t}\r\n\r\n\tpublic final double get(int i,int j)\r\n\t{\r\n\t\treturn value[j*width+i];\r\n\t}\r\n\r\n\tpublic void reshape(int nw,int nh)\r\n\t{\r\n\t\tensureCapacity(nw*nh);\r\n\t\tif(nw<width)\r\n\t\t{\r\n\t\t\tfor(int j=0;j<nh;j++)\r\n\t\t\t{\r\n\t\t\t\tfor(int i=0;i<nw;i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tvalue[i+j*nw] = value[i+j*width];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tfor(int j=(nh-1);j>=0;j--)\r\n\t\t\t{\r\n\t\t\t\tfor(int i=(nw-1);i>=0;i--)\r\n\t\t\t\t{\r\n\t\t\t\t\tvalue[i+j*nw] = value[i+j*width];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\twidth = nw;\r\n\t\theight = nh;\r\n\t}\r\n\t\r\n\tpublic void reshapeleft(int nw,int nh)\r\n\t{\r\n\t\tensureCapacity(nw*nh);\r\n\t\tif(nw<width)\r\n\t\t{\r\n\t\t\tfor(int j=0;j<nh;j++)\r\n\t\t\t{\r\n\t\t\t\tfor(int i=0;i<nw;i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tvalue[i+j*nw] = value[i+(width-nw)+j*width];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tfor(int j=(nh-1);j>=0;j--)\r\n\t\t\t{\r\n\t\t\t\tfor(int i=(nw-1);i>=0;i--)\r\n\t\t\t\t{\r\n\t\t\t\t\tvalue[i+(nw-width)+j*nw] = value[i+j*width];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\twidth = nw;\r\n\t\theight = nh;\r\n\t}\r\n\r\n\tpublic double getMirror(int x, int y)\r\n {\r\n if (x >= width)\r\n x = width - (x - width + 2);\r\n\r\n if (y >= height)\r\n y = height - (y - height + 2);\r\n\r\n if (x < 0)\r\n {\r\n int tmp = 0;\r\n int dir = 1;\r\n\r\n while (x < 0)\r\n {\r\n tmp += dir;\r\n if (tmp == width - 1 || tmp == 0)\r\n dir *= -1;\r\n x++;\r\n }\r\n x = tmp;\r\n }\r\n\r\n if (y < 0)\r\n {\r\n int tmp = 0;\r\n int dir = 1;\r\n\r\n while (y < 0)\r\n {\r\n tmp += dir;\r\n if (tmp == height - 1 || tmp == 0)\r\n dir *= -1;\r\n y++;\r\n }\r\n y = tmp;\r\n }\r\n\r\n return value[x+y*width];\r\n }\r\n\r\n\tpublic void set(int i,int j,double v)\r\n\t{\r\n\t\tvalue[j*width+i] = v;\r\n\t}\r\n\r\n\tpublic void add(int i,int j,double v)\r\n\t{\r\n\t\tvalue[j*width+i] += v;\r\n\t}\r\n\r\n\tpublic void set(float[] a)\r\n\t{\r\n\t\t for (int i = 0; i < width*height; i++)\r\n\t\t {\r\n\t\t\t value[i] = a[i];\r\n\t\t }\r\n\t}\r\n\tpublic void set(GeneralMatrixFloat a)\r\n\t{\r\n\t\tensureCapacityNoCopy(a.width*a.height);\r\n\t\twidth = a.width;\r\n\t\theight = a.height;\r\n\t\t for (int i = 0; i < width*height; i++)\r\n\t\t {\r\n\t\t\t value[i] = a.value[i];\r\n\t\t }\r\n\t}\r\n\tpublic void set(GeneralMatrixDouble a)\r\n\t{\r\n\t\tensureCapacityNoCopy(a.width*a.height);\r\n\t\twidth = a.width;\r\n\t\theight = a.height;\r\n\t\t for (int i = 0; i < width*height; i++)\r\n\t\t {\r\n\t\t\t value[i] = a.value[i];\r\n\t\t }\r\n\t}\r\n\tpublic void set(double[] a)\r\n\t{\r\n\t\t for (int i = 0; i < width*height; i++)\r\n\t\t {\r\n\t\t\t value[i] = (double)a[i];\r\n\t\t }\r\n\t}\r\n\tpublic void set(double[][] a)\r\n\t{\r\n\t\t for (int j = 0; j < height; j++)\r\n\t\t {\r\n\t\t\t for (int i = 0; i < width; i++)\r\n\t\t\t {\r\n\t\t\t\t value[i+j*width] = (double)a[j][i];\r\n\t\t\t }\r\n\t\t }\r\n\t}\r\n\r\n\tpublic void setDiagonal(double v)\r\n\t{\r\n\t\t for (int i = 0; i < width; i++)\r\n\t\t {\r\n\t\t\t value[i+i*width] = v;\r\n\t\t }\r\n\t}\r\n\r\n\tpublic static double determinant(GeneralMatrixDouble m)\r\n\t{\r\n\t\tint n = m.width; \r\n\t\tif(n==1)\r\n\t\t\treturn m.value[0];\r\n\t\telse\r\n\t\tif(n==2)\r\n\t\t{\r\n\t\t\treturn m.value[0*2+0] * m.value[1*2+1] - m.value[1*2+0] * m.value[0*2+1];\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tfloat det = 0.0f;\r\n\t\t\tfor (int j1=0;j1<n;j1++) \r\n\t\t\t{\r\n\t\t if(m.value[0*n+j1]==0.0f)\r\n\t\t \t continue;\r\n\r\n\t\t GeneralMatrixDouble subm = new GeneralMatrixDouble(n-1,n-1);\r\n\r\n\t\t for (int i=1;i<n;i++) \r\n\t\t {\r\n\t\t int j2 = 0;\r\n\t\t for (int j=0;j<n;j++) \r\n\t\t {\r\n\t\t if (j == j1)\r\n\t\t continue;\r\n\t\t subm.value[(i-1)*(n-1)+j2] = m.value[i*n+j];\r\n\t\t j2++;\r\n\t\t }\r\n\t\t }\r\n\t\t int ind = 1+j1+1;\r\n\t\t \r\n\t\t if((ind%2)==0)\r\n\t\t \t det += m.value[0*n+j1] * determinant(subm);\r\n\t\t else\r\n\t\t \t det -= m.value[0*n+j1] * determinant(subm);\r\n\t\t\t}\r\n\t\t\treturn det;\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic void set3DTransformPosition(double x,double y,double z)\r\n\t{\r\n\t\tvalue[4*3+0] = x;\r\n\t\tvalue[4*3+1] = y;\r\n\t\tvalue[4*3+2] = z;\r\n\t}\r\n\tpublic void set3DTransformZRotation(double z)\r\n\t{\r\n\t\tdouble sin=(double)Math.sin(z);\r\n\t\tdouble cos=(double)Math.cos(z);\r\n\t\tvalue[width*0+0] = cos;\r\n\t\tvalue[width*0+1] = -sin;\r\n\t\tvalue[width*1+0] = sin;\r\n\t\tvalue[width*1+1] = cos;\r\n\t\tvalue[width*2+2] = 1.0f;\r\n\t}\r\n\tpublic void set3DTransformYRotation(double y)\r\n\t{\r\n\t\tdouble sin=(double)Math.sin(y);\r\n\t\tdouble cos=(double)Math.cos(y);\r\n\t\tvalue[width*0+0] = cos;\r\n\t\tvalue[width*0+2] = sin;\r\n\t\tvalue[width*2+0] = -sin;\r\n\t\tvalue[width*2+2] = cos;\r\n\t\tvalue[width*1+1] = 1.0f;\r\n\t}\r\n\tpublic void set3DTransformXRotation(double x)\r\n\t{\r\n\t\tdouble sin=(double)Math.sin(x);\r\n\t\tdouble cos=(double)Math.cos(x);\r\n\t\tvalue[width*1+1] = cos;\r\n\t\tvalue[width*1+2] = -sin;\r\n\t\tvalue[width*2+1] = sin;\r\n\t\tvalue[width*2+2] = cos;\r\n\t\tvalue[width*0+0] = 0.0f;\r\n\t}\r\n\r\n\tpublic void set3DTransformRotationYFirst(double x,double y,double z)\r\n\t{\r\n\t\t//Normal result\r\n\t\tdouble sx=(double)Math.sin(x);\r\n\t\tdouble cx=(double)Math.cos(x);\r\n\t\tdouble sy=(double)Math.sin(y);\r\n\t\tdouble cy=(double)Math.cos(y);\r\n\t\tdouble sz=(double)Math.sin(z);\r\n\t\tdouble cz=(double)Math.cos(z);\r\n\t\t\r\n\t\t//times this\r\n\t\t//0, 1, 0\r\n\t\t//-1, 0, 0\r\n\t\t//0, 0, 1\r\n\r\n//\t\tvalue[4*0+0] = cz*cy;\r\n//\t\tvalue[4*0+1] = (sy*sx*cz-cx*sz);\r\n//\t\tvalue[4*0+2] = (sy*cx*cz+sz*sx);\r\n//\r\n//\t\tvalue[4*1+0] = sz*cy;\r\n//\t\tvalue[4*1+1] = (sy*sx*sz+cx*cz);\r\n//\t\tvalue[4*1+2] = (sy*cx*sz-cz*sx);\r\n//\r\n//\t\tvalue[4*2+0] = -sy;\r\n//\t\tvalue[4*2+1] = cy*sx;\r\n//\t\tvalue[4*2+2] = cy*cx;\r\n\r\n\t\t\r\n\t\t//by this \r\n//\t\tvalue[4*0+0] = sz*cy;\r\n//\t\tvalue[4*0+1] = (sy*sx*sz+cx*cz);\r\n//\t\tvalue[4*0+2] = (sy*cx*sz-cz*sx);\r\n//\r\n//\t\tvalue[4*1+0] = -cz*cy;\r\n//\t\tvalue[4*1+1] = -(sy*sx*cz-cx*sz);\r\n//\t\tvalue[4*1+2] = -(sy*cx*cz+sz*sx);\r\n//\r\n//\t\tvalue[4*2+0] = -sy;\r\n//\t\tvalue[4*2+1] = cy*sx;\r\n//\t\tvalue[4*2+2] = cy*cx;\r\n\t\t\r\n\t\t//times this\r\n\t\t//0, -1, 0\r\n\t\t//1, 0, 0\r\n\t\t//0, 0, 1\r\n\r\n\t\t//First rotate by -90 z \t\t\r\n\t\t//x axis becomes y\r\n\t\t//y becomes -x\r\n\t\t\r\n//\t\tfor (int k=0; k<3; k++) \r\n//\t\t{\r\n//\t\tfor (int j=0; j<3; j++) \r\n//\t\t{\r\n//\t\t\trbmat.value[k*3+j] = \r\n//\t\t\t\tbmat.value[k*3+0] * procrustesTransform.value[0*4+j] +\r\n//\t\t\t\tbmat.value[k*3+1] * procrustesTransform.value[1*4+j] +\r\n//\t\t\t\tbmat.value[k*3+2] * procrustesTransform.value[2*4+j];\r\n//\t\t}\r\n//\t\t}\r\n\t\t\r\n\t\tif(width==4)\r\n\t\t{\r\n\t\t\tvalue[4*0+0] = (sy*sx*sz+cx*cz);\r\n\t\t\tvalue[4*0+1] = -sz*cy;\r\n\t\t\tvalue[4*0+2] = (sy*cx*sz-cz*sx);\r\n\t\r\n\t\t\tvalue[4*1+0] = -(sy*sx*cz-cx*sz);\r\n\t\t\tvalue[4*1+1] = cz*cy;\r\n\t\t\tvalue[4*1+2] = -(sy*cx*cz+sz*sx);\r\n\t\r\n\t\t\tvalue[4*2+0] = cy*sx;\r\n\t\t\tvalue[4*2+1] = sy;\r\n\t\t\tvalue[4*2+2] = cy*cx;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tvalue[3*0+0] = (sy*sx*sz+cx*cz);\r\n\t\t\tvalue[3*0+1] = -sz*cy;\r\n\t\t\tvalue[3*0+2] = (sy*cx*sz-cz*sx);\r\n\r\n\t\t\tvalue[3*1+0] = -(sy*sx*cz-cx*sz);\r\n\t\t\tvalue[3*1+1] = cz*cy;\r\n\t\t\tvalue[3*1+2] = -(sy*cx*cz+sz*sx);\r\n\r\n\t\t\tvalue[3*2+0] = cy*sx;\r\n\t\t\tvalue[3*2+1] = sy;\r\n\t\t\tvalue[3*2+2] = cy*cx;\r\n\t\t}\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\t//then rotate back +90 z\r\n\t\t//x axis becomes -y\r\n\t\t//y becomes x\r\n\t}\r\n\r\n\tpublic void set3DTransformRotation(double x,double y,double z)\r\n\t{\r\n\t\tdouble sx=(double)Math.sin(x);\r\n\t\tdouble cx=(double)Math.cos(x);\r\n\t\tdouble sy=(double)Math.sin(y);\r\n\t\tdouble cy=(double)Math.cos(y);\r\n\t\tdouble sz=(double)Math.sin(z);\r\n\t\tdouble cz=(double)Math.cos(z);\r\n\r\n\t if(width==4)\r\n\t\t{\r\n\t\t\tvalue[4*0+0] = cz*cy;\r\n\t\t\tvalue[4*0+1] = (sy*sx*cz-cx*sz);\r\n\t\t\tvalue[4*0+2] = (sy*cx*cz+sz*sx);\r\n\t\r\n\t\t\tvalue[4*1+0] = sz*cy;\r\n\t\t\tvalue[4*1+1] = (sy*sx*sz+cx*cz);\r\n\t\t\tvalue[4*1+2] = (sy*cx*sz-cz*sx);\r\n\t\r\n\t\t\tvalue[4*2+0] = -sy;\r\n\t\t\tvalue[4*2+1] = cy*sx;\r\n\t\t\tvalue[4*2+2] = cy*cx;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tvalue[3*0+0] = cz*cy;\r\n\t\t\tvalue[3*0+1] = (sy*sx*cz-cx*sz);\r\n\t\t\tvalue[3*0+2] = (sy*cx*cz+sz*sx);\r\n\t\r\n\t\t\tvalue[3*1+0] = sz*cy;\r\n\t\t\tvalue[3*1+1] = (sy*sx*sz+cx*cz);\r\n\t\t\tvalue[3*1+2] = (sy*cx*sz-cz*sx);\r\n\t\r\n\t\t\tvalue[3*2+0] = -sy;\r\n\t\t\tvalue[3*2+1] = cy*sx;\r\n\t\t\tvalue[3*2+2] = cy*cx;\r\n\t\t}\r\n\t}\r\n//\t [ (cy*cz)+(sy*sx*sz) , (cy*(-(sz)))+(sy*sx*cz) ,sy*cx]\r\n//\t [ ]\r\n//\t [ cx*sz , cx*cz ,-(sx)]\r\n//\t [ ]\r\n//\t [((-(sy))*cz)+(cy*sx*sz),((-(sy))*(-(sz)))+(cy*sx*cz),cy*cx]\r\n\tpublic void set3DTransformRotationYXZ(double x,double y,double z)\r\n\t{\r\n\t\tdouble sx=(double)Math.sin(x);\r\n\t\tdouble cx=(double)Math.cos(x);\r\n\t\tdouble sy=(double)Math.sin(y);\r\n\t\tdouble cy=(double)Math.cos(y);\r\n\t\tdouble sz=(double)Math.sin(z);\r\n\t\tdouble cz=(double)Math.cos(z);\r\n\r\n\t\tif(width==4)\r\n\t\t{\r\n\t\t\tvalue[4*0+0] = (cy*cz)+(sy*sx*sz);\r\n\t\t\tvalue[4*0+1] = (cy*(-(sz)))+(sy*sx*cz);\r\n\t\t\tvalue[4*0+2] = sy*cx;\r\n\t\r\n\t\t\tvalue[4*1+0] = cx*sz;\r\n\t\t\tvalue[4*1+1] = cx*cz;\r\n\t\t\tvalue[4*1+2] = -(sx);\r\n\t\r\n\t\t\tvalue[4*2+0] = ((-(sy))*cz)+(cy*sx*sz);\r\n\t\t\tvalue[4*2+1] = ((-(sy))*(-(sz)))+(cy*sx*cz);\r\n\t\t\tvalue[4*2+2] = cy*cx;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tvalue[3*0+0] = (cy*cz)+(sy*sx*sz);\r\n\t\t\tvalue[3*0+1] = (cy*(-(sz)))+(sy*sx*cz);\r\n\t\t\tvalue[3*0+2] = sy*cx;\r\n\t\r\n\t\t\tvalue[3*1+0] = cx*sz;\r\n\t\t\tvalue[3*1+1] = cx*cz;\r\n\t\t\tvalue[3*1+2] = -(sx);\r\n\t\r\n\t\t\tvalue[3*2+0] = ((-(sy))*cz)+(cy*sx*sz);\r\n\t\t\tvalue[3*2+1] = ((-(sy))*(-(sz)))+(cy*sx*cz);\r\n\t\t\tvalue[3*2+2] = cy*cx;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic static final void getEulerYXZ(GeneralMatrixFloat m, GeneralMatrixFloat euler) \r\n\t{\r\n\t\tfinal int i=0;\r\n\t\tfinal int j=1;\r\n\t\tfinal int k=2;\r\n\r\n\t\tfinal int w=m.width;\r\n\t\t\r\n\t\tdouble cx = Math.sqrt(m.value[j*w+i]*m.value[j*w+i] + m.value[j*w+j]*m.value[j*w+j]);\r\n\t\tif (cx > 16*EPSILON) {\r\n\t\t euler.value[0] = (float)Math.atan2(-m.value[j*w+k], cx);\r\n\t\t euler.value[1] = (float)Math.atan2(m.value[i*w+k], m.value[k*w+k]);\r\n\t\t euler.value[2] = (float)Math.atan2(m.value[j*w+i], m.value[j*w+j]);\r\n\t\t} else {\r\n\t\t\teuler.value[0] = (float)Math.atan2(-m.value[j*w+k], cx);\r\n\t\t euler.value[1] = 0;\r\n\t\t euler.value[2] = (float)Math.atan2(m.value[i*w+i], m.value[i*w+j]);\r\n\t\t}\r\n\t}\r\n\tpublic static final void getEulerYXZ(GeneralMatrixDouble m, GeneralMatrixDouble euler) \r\n\t{\r\n\t\tfinal int i=0;\r\n\t\tfinal int j=1;\r\n\t\tfinal int k=2;\r\n\r\n\t\tfinal int w=m.width;\r\n\t\t\r\n\t\tdouble cx = Math.sqrt(m.value[j*w+i]*m.value[j*w+i] + m.value[j*w+j]*m.value[j*w+j]);\r\n\t\tif (cx > 16*EPSILON) {\r\n\t\t euler.value[0] = (double)Math.atan2(-m.value[j*w+k], cx);\r\n\t\t euler.value[1] = (double)Math.atan2(m.value[i*w+k], m.value[k*w+k]);\r\n\t\t euler.value[2] = (double)Math.atan2(m.value[j*w+i], m.value[j*w+j]);\r\n\t\t} else {\r\n\t\t\teuler.value[0] = (double)Math.atan2(-m.value[j*w+k], cx);\r\n\t\t euler.value[1] = 0;\r\n\t\t euler.value[2] = (double)Math.atan2(m.value[i*w+i], m.value[i*w+j]);\r\n\t\t}\r\n\t}\r\n\r\n\tpublic static final void getEuler(GeneralMatrixFloat m, GeneralMatrixDouble euler) \r\n\t{\r\n\t\tfinal int i=0;\r\n\t\tfinal int j=1;\r\n\t\tfinal int k=2;\r\n\r\n\t\tfinal int w=m.width;\r\n\r\n\t\tdouble cy = Math.sqrt(m.value[i*w+i]*m.value[i*w+i] + m.value[j*w+i]*m.value[j*w+i]);\r\n\t\tif (cy > 16*EPSILON) {\r\n\t\t euler.value[0] = (double)Math.atan2(m.value[k*w+j], m.value[k*w+k]);\r\n\t\t euler.value[1] = (double)Math.atan2(-m.value[k*w+i], cy);\r\n\t\t euler.value[2] = (double)Math.atan2(m.value[j*w+i], m.value[i*w+i]);\r\n\t\t} else {\r\n\t\t euler.value[0] = (double)Math.atan2(-m.value[i*w+k], m.value[j*w+j]);\r\n\t\t euler.value[1] = (double)Math.atan2(-m.value[k*w+i], cy);\r\n\t\t euler.value[2] = 0;\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static final void getEuler(GeneralMatrixDouble m, GeneralMatrixDouble euler) \r\n\t{\r\n\t\tfinal int i=0;\r\n\t\tfinal int j=1;\r\n\t\tfinal int k=2;\r\n\r\n\t\tfinal int w=m.width;\r\n\r\n\t\tdouble cy = Math.sqrt(m.value[i*w+i]*m.value[i*w+i] + m.value[j*w+i]*m.value[j*w+i]);\r\n\t\tif (cy > 16*EPSILON) {\r\n\t\t euler.value[0] = (double)Math.atan2(m.value[k*w+j], m.value[k*w+k]);\r\n\t\t euler.value[1] = (double)Math.atan2(-m.value[k*w+i], cy);\r\n\t\t euler.value[2] = (double)Math.atan2(m.value[j*w+i], m.value[i*w+i]);\r\n\t\t} else {\r\n\t\t euler.value[0] = (double)Math.atan2(-m.value[i*w+k], m.value[j*w+j]);\r\n\t\t euler.value[1] = (double)Math.atan2(-m.value[k*w+i], cy);\r\n\t\t euler.value[2] = 0;\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static final void getEuler(GeneralMatrixDouble m, GeneralMatrixFloat euler) \r\n\t{\r\n\t\tfinal int i=0;\r\n\t\tfinal int j=1;\r\n\t\tfinal int k=2;\r\n\r\n\t\tfinal int w=m.width;\r\n\r\n\t\tdouble cy = Math.sqrt(m.value[i*w+i]*m.value[i*w+i] + m.value[j*w+i]*m.value[j*w+i]);\r\n\t\tif (cy > 16*EPSILON) {\r\n\t\t euler.value[0] = (float)Math.atan2(m.value[k*w+j], m.value[k*w+k]);\r\n\t\t euler.value[1] = (float)Math.atan2(-m.value[k*w+i], cy);\r\n\t\t euler.value[2] = (float)Math.atan2(m.value[j*w+i], m.value[i*w+i]);\r\n\t\t} else {\r\n\t\t euler.value[0] = (float)Math.atan2(-m.value[i*w+k], m.value[j*w+j]);\r\n\t\t euler.value[1] = (float)Math.atan2(-m.value[k*w+i], cy);\r\n\t\t euler.value[2] = 0;\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic void calcBasisFromY(double x,double y,double z,\r\n\t\t\tdouble Xx,double Xy,double Xz)\r\n\t{\r\n\t\tvalue[width*1+0] = x;\r\n\t\tvalue[width*1+1] = y;\r\n\t\tvalue[width*1+2] = z;\r\n\t\tdouble total = x*x;\r\n\t\ttotal += y*y;\r\n\t\ttotal += z*z;\r\n\t\tif(total<=EPSILON)\r\n\t\t{\r\n\t\t\tvalue[width*1+0] = 1.0f;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\ttotal = Math.sqrt(total);\r\n\t\t}\r\n\t\tvalue[width*1+0] /= total;\r\n\t\tvalue[width*1+1] /= total;\r\n\t\tvalue[width*1+2] /= total;\r\n\t\t\r\n\t\ttotal = Xx*Xx;\r\n\t\ttotal += Xy*Xy;\r\n\t\ttotal += Xz*Xz;\r\n\t\tif(total<=EPSILON)\r\n\t\t{\r\n\t\t\tvalue[width*0+0] = 1.0f;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\ttotal = Math.sqrt(total);\r\n\t\t\tvalue[width*0+0] = Xx/total;\r\n\t\t\tvalue[width*0+1] = Xy/total;\r\n\t\t\tvalue[width*0+2] = Xz/total;\r\n\t\t}\r\n\r\n\t\t\r\n\t\tvalue[width*2+0] = -y*value[width*0+2]+value[width*0+1]*z;\r\n\t\tvalue[width*2+1] = -z*value[width*0+0]+value[width*0+2]*x;\r\n\t\tvalue[width*2+2] = -x*value[width*0+1]+value[width*0+0]*y;\r\n\r\n\t\t//Normalise\r\n\t\ttotal = value[width*2+0]*value[width*2+0];\r\n\t\ttotal += value[width*2+1]*value[width*2+1];\r\n\t\ttotal += value[width*2+2]*value[width*2+2];\r\n\t\tif(total<=EPSILON)\r\n\t\t{\r\n\t\t\tvalue[width*2+0] = 1.0f;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\ttotal = Math.sqrt(total);\r\n\t\t\tvalue[width*2+0] /= total;\r\n\t\t\tvalue[width*2+1] /= total;\r\n\t\t\tvalue[width*2+2] /= total;\r\n\t\t}\r\n\t\t\r\n\t\tvalue[width*0+0] = y*value[width*2+2]-value[width*2+1]*z;\r\n\t\tvalue[width*0+1] = z*value[width*2+0]-value[width*2+2]*x;\r\n\t\tvalue[width*0+2] = x*value[width*2+1]-value[width*2+0]*y;\r\n\r\n\t\ttotal = value[width*0+0]*value[width*0+0];\r\n\t\ttotal += value[width*0+1]*value[width*0+1];\r\n\t\ttotal += value[width*0+2]*value[width*0+2];\r\n\t\tif(total<=EPSILON)\r\n\t\t{\r\n\t\t\tvalue[width*0+0] = 1.0f;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\ttotal = Math.sqrt(total);\r\n\t\t\tvalue[width*0+0] /= total;\r\n\t\t\tvalue[width*0+1] /= total;\r\n\t\t\tvalue[width*0+2] /= total;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic void calcBasisFromY(double x,double y,double z,\r\n\t\t\tdouble Xx,double Xy,double Xz,\r\n\t\t\tint width,int off)\r\n\t{\r\n\t\tvalue[width*1+0+off] = x;\r\n\t\tvalue[width*1+1+off] = y;\r\n\t\tvalue[width*1+2+off] = z;\r\n\t\tdouble total = x*x;\r\n\t\ttotal += y*y;\r\n\t\ttotal += z*z;\r\n\t\tif(total<=EPSILON)\r\n\t\t{\r\n\t\t\tvalue[width*1+0+off] = 1.0f;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\ttotal = Math.sqrt(total);\r\n\t\t}\r\n\t\tvalue[width*1+0+off] /= total;\r\n\t\tvalue[width*1+1+off] /= total;\r\n\t\tvalue[width*1+2+off] /= total;\r\n\t\t\r\n\t\ttotal = Xx*Xx;\r\n\t\ttotal += Xy*Xy;\r\n\t\ttotal += Xz*Xz;\r\n\t\tif(total<=EPSILON)\r\n\t\t{\r\n\t\t\tvalue[width*0+0+off] = 1.0f;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\ttotal = Math.sqrt(total);\r\n\t\t\tvalue[width*0+0+off] = Xx/total;\r\n\t\t\tvalue[width*0+1+off] = Xy/total;\r\n\t\t\tvalue[width*0+2+off] = Xz/total;\r\n\t\t}\r\n\r\n\t\t\r\n\t\tvalue[width*2+0+off] = -y*value[width*0+2+off]+value[width*0+1+off]*z;\r\n\t\tvalue[width*2+1+off] = -z*value[width*0+0+off]+value[width*0+2+off]*x;\r\n\t\tvalue[width*2+2+off] = -x*value[width*0+1+off]+value[width*0+0+off]*y;\r\n\r\n\t\t//Normalise\r\n\t\ttotal = value[width*2+0+off]*value[width*2+0+off];\r\n\t\ttotal += value[width*2+1+off]*value[width*2+1+off];\r\n\t\ttotal += value[width*2+2+off]*value[width*2+2+off];\r\n\t\tif(total<=EPSILON)\r\n\t\t{\r\n\t\t\tvalue[width*2+0+off] = 1.0f;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\ttotal = Math.sqrt(total);\r\n\t\t\tvalue[width*2+0+off] /= total;\r\n\t\t\tvalue[width*2+1+off] /= total;\r\n\t\t\tvalue[width*2+2+off] /= total;\r\n\t\t}\r\n\t\t\r\n\t\tvalue[width*0+0+off] = y*value[width*2+2+off]-value[width*2+1+off]*z;\r\n\t\tvalue[width*0+1+off] = z*value[width*2+0+off]-value[width*2+2+off]*x;\r\n\t\tvalue[width*0+2+off] = x*value[width*2+1+off]-value[width*2+0+off]*y;\r\n\r\n\t\ttotal = value[width*0+0+off]*value[width*0+0+off];\r\n\t\ttotal += value[width*0+1+off]*value[width*0+1+off];\r\n\t\ttotal += value[width*0+2+off]*value[width*0+2+off];\r\n\t\tif(total<=EPSILON)\r\n\t\t{\r\n\t\t\tvalue[width*0+0+off] = 1.0f;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\ttotal = Math.sqrt(total);\r\n\t\t\tvalue[width*0+0+off] /= total;\r\n\t\t\tvalue[width*0+1+off] /= total;\r\n\t\t\tvalue[width*0+2+off] /= total;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic void setSubset(GeneralMatrixDouble subset,int xs,int ys)\r\n\t{\r\n\t\tint maxy = ys+subset.height;\r\n\t\tint maxx = xs+subset.width;\r\n\t\tfor(int y=ys;y<maxy;y++)\r\n\t\t{\r\n\t\t\tfor(int x=xs;x<maxx;x++)\r\n\t\t\t{\r\n\t\t\t\tvalue[x+y*width] = subset.value[(x-xs)+(y-ys)*subset.width];\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tpublic void clearSubset(int xs,int ys,int sw,int sh,double v)\r\n\t{\r\n\t\tint maxy = ys+sh;\r\n\t\tint maxx = xs+sw;\r\n\t\tfor(int y=ys;y<maxy;y++)\r\n\t\t{\r\n\t\t\tfor(int x=xs;x<maxx;x++)\r\n\t\t\t{\r\n\t\t\t\tvalue[x+y*width] = v;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t//For setting a vec or mat from an array of vecs/mats\r\n\tpublic void setFromSubset(GeneralMatrixDouble full,int ys)\r\n\t{\r\n\t\tint i=0;\r\n\t\tint fi = ys*width;\r\n\t\tfor(int y=0;y<height;y++)\r\n\t\t{\r\n\t\t\tfor(int x=0;x<width;x++)\r\n\t\t\t{\r\n\t\t\t\tvalue[i] = full.value[fi];\r\n\t\t\t\ti++;\r\n\t\t\t\tfi++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tpublic void setFromSubset(GeneralMatrixFloat full,int ys)\r\n\t{\r\n\t\tint i=0;\r\n\t\tint fi = ys*width;\r\n\t\tfor(int y=0;y<height;y++)\r\n\t\t{\r\n\t\t\tfor(int x=0;x<width;x++)\r\n\t\t\t{\r\n\t\t\t\tvalue[i] = full.value[fi];\r\n\t\t\t\ti++;\r\n\t\t\t\tfi++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n public void setRow(int r,GeneralMatrixDouble row)\r\n {\r\n \tSystem.arraycopy(row.value, 0, value, width*(r), width);\r\n }\r\n\t\r\n\tpublic static double norm(GeneralMatrixDouble a)\r\n\t{\r\n\t\tdouble total = 0.0f;\r\n\t\tfor (int i = 0; i < a.width*a.height; i++)\r\n\t\t{\r\n\t\t\ttotal += a.value[i]*a.value[i];\r\n\t\t}\r\n\t\ttotal = (double)Math.sqrt(total);\r\n\t\treturn total;\r\n\t}\r\n\r\n\tpublic void normalise()\r\n\t{\r\n\t\tdouble total = 0.0f;\r\n\t\tfor (int i = 0; i < width*height; i++)\r\n\t\t{\r\n\t\t\ttotal += value[i]*value[i];\r\n\t\t}\r\n\t\tif(total<=EPSILON)\r\n\t\t{\r\n\t\t\tvalue[0] = 1.0f;\r\n\t\t\treturn;\r\n\t\t}\r\n\t\ttotal = (double)Math.sqrt(total);\r\n\t\tfor (int i = 0; i < width*height; i++)\r\n\t\t{\r\n\t\t\tvalue[i] /= total;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic void rowNormalise(int row)\r\n\t{\r\n\t\tdouble total = 0.0f;\r\n\t\tfor (int i = 0; i < width; i++)\r\n\t\t{\r\n\t\t\ttotal += value[i+row*width]*value[i+row*width];\r\n\t\t}\r\n\t\tif(total<=EPSILON)\r\n\t\t{\r\n\t\t\tvalue[0+row*width] = 1.0f;\r\n\t\t\treturn;\r\n\t\t}\r\n\t\ttotal = (double)Math.sqrt(total);\r\n\t\tfor (int i = 0; i < width; i++)\r\n\t\t{\r\n\t\t\tvalue[i+row*width] /= total;\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic void reverse()\r\n\t{\r\n\t\t for (int i = 0; i < width*height; i++)\r\n\t\t {\r\n\t\t\t value[i] = -value[i];\r\n\t\t }\r\n\t}\r\n\r\n\tpublic void scale(double s)\r\n\t{\r\n\t\t for (int i = 0; i < width*height; i++)\r\n\t\t {\r\n\t\t\t value[i] = value[i]*s;\r\n\t\t }\r\n\t}\r\n\r\n\tpublic void setIdentity()\r\n\t{\r\n\t\tint i=0;\r\n\t\tfor(int y=0;y<height;y++)\r\n\t\t{\r\n\t\t\tfor(int x=0;x<width;x++)\r\n\t\t\t{\r\n\t\t\t\tif(x==y)\r\n\t\t\t\t\tvalue[i] = 1.0f;\r\n\t\t\t\telse\r\n\t\t\t\t\tvalue[i] = 0.0f;\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t//Must be square\r\n\tpublic static final boolean invert(GeneralMatrixDouble a,GeneralMatrixDouble ia)\r\n\t{\r\n\t\tGeneralMatrixDouble temp = new GeneralMatrixDouble(a.width,a.height);\r\n\t\ttemp.set(a);\r\n\r\n\t\tia.setIdentity();\r\n\t\tint i,j,k,swap;\r\n\t\tdouble t;\r\n\t\tfor(i=0;i<a.width;i++)\r\n\t\t{\r\n\t\t\tswap = i;\r\n\t\t\tfor (j = i + 1; j < a.height; j++) {\r\n\t\t\t if (Math.abs(a.get(i, j)) > Math.abs(a.get(i, j)))\r\n\t\t\t {\r\n\t\t\t \tswap = j;\r\n\t\t\t }\r\n\t\t\t}\r\n\r\n\t\t\tif (swap != i)\r\n\t\t\t{\r\n\t\t\t /*\r\n\t\t\t ** Swap rows.\r\n\t\t\t */\r\n\t\t\t for (k = 0; k < a.width; k++)\r\n\t\t\t {\r\n\t\t\t\t\tt = temp.get(k,i);\r\n\t\t\t\t\ttemp.set(k,i,temp.get(k, swap));\r\n\t\t\t\t\ttemp.set(k, swap,t);\r\n\r\n\t\t\t\t\tt = ia.get(k,i);\r\n\t\t\t\t\tia.set(k,i,ia.get(k, swap));\r\n\t\t\t\t\tia.set(k, swap,t);\r\n\t\t\t }\r\n\t\t\t}\r\n\r\n\t\t\tt = temp.get(i,i);\r\n\t\t\tif (t == 0.0f)\r\n\t\t\t{\r\n\t\t\t /*\r\n\t\t\t ** No non-zero pivot. The matrix is singular, which shouldn't\r\n\t\t\t ** happen. This means the user gave us a bad matrix.\r\n\t\t\t */\r\n\t\t\t return false;\r\n\t\t\t}\r\n\r\n\t\t\tfor (k = 0; k < a.width; k++)\r\n\t\t\t{\r\n\t\t\t\ttemp.set(k,i,temp.get(k,i) / t);\r\n\t\t\t\tia.set(k,i,ia.get(k,i) / t);\r\n\t\t\t}\r\n\t\t\tfor (j = 0; j < a.width; j++)\r\n\t\t\t{\r\n\t\t\t if (j != i)\r\n\t\t\t {\r\n\t\t\t \tt = temp.get(i,j);\r\n\t\t\t \tfor (k = 0; k < a.width; k++)\r\n\t\t\t \t{\r\n\t\t\t \t\ttemp.set(k,j, temp.get(k,j) - temp.get(k,i)*t);\r\n\t\t\t \t\tia.set(k,j, ia.get(k,j) - ia.get(k,i)*t);\r\n\t\t\t \t}\r\n\t\t\t }\r\n\t\t\t}\r\n\t }\r\n\t return true;\r\n\t}\r\n\r\n\tpublic static final void invertTransform(GeneralMatrixDouble cameraTransformMatrix,GeneralMatrixDouble modelMatrix)\r\n\t{\r\n\t\t//GeneralMatrixFloat.invert(cameraTransformMatrix,modelMatrix);\r\n\t\t//*\r\n\t\tmodelMatrix.value[0*4+0] = cameraTransformMatrix.value[0*4+0];\r\n\t\tmodelMatrix.value[1*4+0] = cameraTransformMatrix.value[0*4+1];\r\n\t\tmodelMatrix.value[2*4+0] = cameraTransformMatrix.value[0*4+2];\r\n\r\n\t\tmodelMatrix.value[0*4+1] = cameraTransformMatrix.value[1*4+0];\r\n\t\tmodelMatrix.value[1*4+1] = cameraTransformMatrix.value[1*4+1];\r\n\t\tmodelMatrix.value[2*4+1] = cameraTransformMatrix.value[1*4+2];\r\n\r\n\t\tmodelMatrix.value[0*4+2] = cameraTransformMatrix.value[2*4+0];\r\n\t\tmodelMatrix.value[1*4+2] = cameraTransformMatrix.value[2*4+1];\r\n\t\tmodelMatrix.value[2*4+2] = cameraTransformMatrix.value[2*4+2];\r\n\r\n\t\tdouble x = -cameraTransformMatrix.value[3*4+0];\r\n\t\tdouble y = -cameraTransformMatrix.value[3*4+1];\r\n\t\tdouble z = -cameraTransformMatrix.value[3*4+2];\r\n\t\t\r\n\t\t//needs to be rotated like the rest of the points in space\r\n\t\tdouble tx = modelMatrix.value[0*4+0]*x+modelMatrix.value[1*4+0]*y+modelMatrix.value[2*4+0]*z;\r\n\t\tdouble ty = modelMatrix.value[0*4+1]*x+modelMatrix.value[1*4+1]*y+modelMatrix.value[2*4+1]*z;\r\n\t\tdouble tz = modelMatrix.value[0*4+2]*x+modelMatrix.value[1*4+2]*y+modelMatrix.value[2*4+2]*z;\r\n\t\tmodelMatrix.value[3*4+0] = tx;\r\n\t\tmodelMatrix.value[3*4+1] = ty;\r\n\t\tmodelMatrix.value[3*4+2] = tz;\t\t\r\n\t\t//*/\r\n\t}\r\n\r\n\t\r\n\tpublic static final void crossProduct3(GeneralMatrixDouble a,GeneralMatrixDouble b,GeneralMatrixDouble c)\r\n\t{\r\n\t\tc.value[0] = a.value[1]*b.value[2]-b.value[1]*a.value[2];\r\n\t\tc.value[1] = a.value[2]*b.value[0]-b.value[2]*a.value[0];\r\n\t\tc.value[2] = a.value[0]*b.value[1]-b.value[0]*a.value[1];\r\n\t}\r\n\r\n\tpublic static final void mult(GeneralMatrixDouble a,GeneralMatrixDouble b,GeneralMatrixDouble c)\r\n\t{\r\n\t\tint n = a.height;\r\n\t\tint p = a.width;\r\n\t\tint r = b.width;\r\n\r\n\t\tif(p!=b.height)\r\n\t\t{\r\n\t\t\tSystem.out.println(\"Mult error, matricies sizes dont match\");\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t double vdot;\r\n\t int i,j,k,m;\r\n\r\n\r\n int r5 = r*5;\r\n\t int rowI = 0;\r\n\t int crowI = 0;\r\n\t for (i = 0; i < n; i++) {\r\n\r\n\t for (j = 0; j < r; j++) {\r\n\r\n\t vdot = 0.0f;\r\n\r\n\t m = p%5;\r\n\r\n\t int rowK = 0;\r\n\t for (k = 0; k < m; k++) {\r\n\r\n\t vdot += a.value[rowI+k]*b.value[rowK+j];\r\n\t rowK += r;\r\n\t }\r\n\r\n\t for (k = m; k < p; k += 5) {\r\n\r\n\t vdot += a.value[rowI+k]*b.value[rowK+j] +\r\n\t a.value[rowI+k+1]*b.value[rowK+r+j] +\r\n\t a.value[rowI+k+2]*b.value[rowK+r*2+j] +\r\n\t a.value[rowI+k+3]*b.value[rowK+r*3+j] +\r\n\t a.value[rowI+k+4]*b.value[rowK+r*4+j];\r\n\r\n\t rowK += r5;\r\n\t }\r\n\r\n\t c.value[crowI+j] = vdot;\r\n\r\n\t }\r\n\t rowI += p;\r\n\t crowI += r;\r\n\t }\r\n\r\n\t}\r\n\r\n\tpublic static final void mult(GeneralMatrixDouble a,double[] x,double[] b)\r\n\t{\r\n\t\tint n = a.height;\r\n\t\tint p = a.width;\r\n\t\tint r = 1;\r\n\r\n\t\tif(p!=x.length)\r\n\t\t{\r\n\t\t\tSystem.out.println(\"Mult error, matricies sizes dont match\");\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t double vdot;\r\n\t int i,j,k,m;\r\n\r\n\r\n int r5 = r*5;\r\n\t int rowI = 0;\r\n\t int crowI = 0;\r\n\t for (i = 0; i < n; i++) {\r\n\r\n\t for (j = 0; j < r; j++) {\r\n\r\n\t vdot = 0.0f;\r\n\r\n\t m = p%5;\r\n\r\n\t int rowK = 0;\r\n\t for (k = 0; k < m; k++) {\r\n\r\n\t vdot += a.value[rowI+k]*x[rowK+j];\r\n\t rowK += r;\r\n\t }\r\n\r\n\t for (k = m; k < p; k += 5) {\r\n\r\n\t vdot += a.value[rowI+k]*x[rowK+j] +\r\n\t a.value[rowI+k+1]*x[rowK+r+j] +\r\n\t a.value[rowI+k+2]*x[rowK+r*2+j] +\r\n\t a.value[rowI+k+3]*x[rowK+r*3+j] +\r\n\t a.value[rowI+k+4]*x[rowK+r*4+j];\r\n\r\n\t rowK += r5;\r\n\t }\r\n\r\n\t b[crowI+j] = vdot;\r\n\r\n\t }\r\n\t rowI += p;\r\n\t crowI += r;\r\n\t }\r\n\r\n\t}\r\n\r\n\tpublic static final void rowmult(GeneralMatrixDouble a,GeneralMatrixDouble b,GeneralMatrixDouble c)\r\n\t{\r\n\t\tdouble vdot;\r\n\t\t for (int i = 0; i < a.height; i++)\r\n\t\t {\r\n\t\t\t //Apply the matrix to this vector\r\n\r\n\t\t\t for (int j = 0; j < a.width; j++)\r\n\t\t\t {\r\n\t\t\t\t vdot = 0.0f;\r\n\t\t\t\t for (int k = 0; k < b.height; k++)\r\n\t\t\t\t {\r\n\t\t\t vdot += a.value[i*a.width+k]*b.value[k*b.width+j];\r\n\t\t\t\t }\r\n\t\t\t\t c.value[i*a.width+j] = vdot;\r\n\t\t\t }\r\n\t\t }\r\n\t}\r\n\r\n\tpublic static final void rowtransform(GeneralMatrixDouble a,GeneralMatrixDouble b,GeneralMatrixDouble c)\r\n\t{\r\n\t\t// wxh\r\n\t\t//a is 3xn (h value of 1.0 is implied)\r\n\t\t//B is 3x4 (or at least the other values are unused)\r\n\t\tdouble vdot;\r\n\t\t for (int i = 0; i < a.height; i++)\r\n\t\t {\r\n\t\t\t //Apply the matrix to this vector\r\n\r\n\t\t\t for (int j = 0; j < a.width; j++)\r\n\t\t\t {\r\n\t\t\t\t vdot = 0.0f;\r\n\t\t\t\t for (int k = 0; k < a.width; k++)\r\n\t\t\t\t {\r\n\t\t\t vdot += a.value[i*a.width+k]*b.value[k*b.width+j];\r\n\t\t\t\t }\r\n\t\t\t\t //Add what would be the homogenious value to translate correctly\r\n\t\t\t\t vdot += b.value[a.width*b.width+j];\r\n\t\t\t\t c.value[i*a.width+j] = vdot;\r\n\t\t\t }\r\n\t\t }\r\n\t}\r\n\r\n\tpublic static final void rowproject(GeneralMatrixDouble a,GeneralMatrixDouble b,GeneralMatrixDouble c)\r\n\t{\r\n\t\t// wxh\r\n\t\t//a is 3xn (h value of 1.0 is implied)\r\n\t\t//B is 4x4 (or at least the other values are unused)\r\n\t\tdouble vdot;\r\n\t\tdouble h;\r\n\t\t for (int i = 0; i < a.height; i++)\r\n\t\t {\r\n\t\t\t //Apply the matrix to this vector\r\n\r\n\t\t\t for (int j = 0; j < a.width; j++)\r\n\t\t\t {\r\n\t\t\t\t vdot = 0.0f;\r\n\t\t\t\t for (int k = 0; k < a.width; k++)\r\n\t\t\t\t {\r\n\t\t\t vdot += a.value[i*a.width+k]*b.value[k*b.width+j];\r\n\t\t\t\t }\r\n\t\t\t\t //Add what would be the homogenious value to translate correctly\r\n\t\t\t\t vdot += b.value[a.width*b.width+j];\r\n\t\t\t\t c.value[i*a.width+j] = vdot;\r\n\t\t\t }\r\n\t\t\t h = 0.0f;\r\n\t\t\t for (int k = 0; k < a.width; k++)\r\n\t\t\t {\r\n\t\t h += a.value[i*a.width+k]*b.value[k*b.width+3];\r\n\t\t\t }\r\n\t\t\t //Add implicit h\r\n\t\t\t h += b.value[a.width*b.width+3];\r\n\t\t\t //Divide by h\r\n\t\t\t for (int j = 0; j < a.width; j++)\r\n\t\t\t {\r\n\t\t\t\t c.value[i*a.width+j] /= h;\r\n\t\t\t }\r\n\t\t }\r\n\t}\r\n\r\n\tpublic static final double rowdot(GeneralMatrixDouble a,int ai,GeneralMatrixDouble b,int bi)\r\n\t{\r\n\t\tdouble result = 0.0f;\r\n\t\tfor(int i=0;i<a.width;i++)\r\n\t\t{\r\n\t\t\tresult += a.value[i+ai*a.width]*b.value[i+bi*b.width];\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\r\n\tpublic static final void add(GeneralMatrixDouble a,GeneralMatrixDouble b,GeneralMatrixDouble c)\r\n\t{\r\n\t\t for (int i = 0; i < a.width*a.height; i++)\r\n\t\t {\r\n\t\t\t c.value[i] = a.value[i]+b.value[i];\r\n\t\t }\r\n\t}\r\n\r\n\tpublic static final void addWithScale(GeneralMatrixDouble a,GeneralMatrixDouble b,double s,GeneralMatrixDouble c)\r\n\t{\r\n\t\t for (int i = 0; i < a.width*a.height; i++)\r\n\t\t {\r\n\t\t\t c.value[i] = a.value[i]+b.value[i]*s;\r\n\t\t }\r\n\t}\r\n\r\n\t\r\n\t\r\n\tpublic static final void rowadd(GeneralMatrixDouble a,GeneralMatrixDouble b,GeneralMatrixDouble c)\r\n\t{\r\n\t\tint ai = 0;\r\n\t\t for (int i = 0; i < a.height; i++)\r\n\t\t {\r\n\t\t\t for (int j = 0; j < a.width; j++)\r\n\t\t\t {\r\n\t\t\t\t c.value[ai] = a.value[ai]+b.value[j];\r\n\t\t\t\t ai++;\r\n\t\t\t }\r\n\t\t }\r\n\t}\r\n\r\n\tpublic static final void sub(GeneralMatrixDouble a,GeneralMatrixDouble b,GeneralMatrixDouble c)\r\n\t{\r\n\t\t for (int i = 0; i < a.width*a.height; i++)\r\n\t\t {\r\n\t\t\t c.value[i] = a.value[i]-b.value[i];\r\n\t\t }\r\n\t}\r\n\r\n\tpublic static final void rowsub(GeneralMatrixDouble a,GeneralMatrixDouble b,GeneralMatrixDouble c)\r\n\t{\r\n\t\tint ai = 0;\r\n\t\t for (int i = 0; i < a.height; i++)\r\n\t\t {\r\n\t\t\t for (int j = 0; j < a.width; j++)\r\n\t\t\t {\r\n\t\t\t\t c.value[ai] = a.value[ai]-b.value[j];\r\n\t\t\t\t ai++;\r\n\t\t\t }\r\n\t\t }\r\n\t}\r\n\r\n\tpublic static final void scale(GeneralMatrixDouble a,double b,GeneralMatrixDouble c)\r\n\t{\r\n\t\t for (int i = 0; i < a.width*a.height; i++)\r\n\t\t {\r\n\t\t\t c.value[i] = a.value[i]*b;\r\n\t\t }\r\n\t}\r\n\r\n\tpublic static final void negate(GeneralMatrixDouble a,GeneralMatrixDouble b)\r\n\t{\r\n\t\t for (int i = 0; i < a.width*a.height; i++)\r\n\t\t {\r\n\t\t\t b.value[i] = -a.value[i];\r\n\t\t }\r\n\t}\r\n\r\n\tpublic static final void transpose(GeneralMatrixDouble a,GeneralMatrixDouble at)\r\n\t{\r\n\t\tint i,j;\r\n\r\n\t\tint ai = 0;\r\n\t\tint atjR;\r\n\t for (i = 0; i < a.height; i++) {\r\n\r\n\t \t\tatjR = 0;\r\n\t for (j = 0; j < a.width; j++) {\r\n\r\n\t at.value[atjR+i] = a.value[ai];\r\n\t ai++;\r\n\t atjR += a.height;\r\n\t }\r\n\r\n\t }\r\n\t}\r\n\r\n\tpublic static final double trace(GeneralMatrixDouble a)\r\n\t{\r\n\t\tdouble sum = 0.0f;\r\n\t\tint index = 0;\r\n\t\tfor (int i = 0; i < a.height; i++)\r\n\t\t{\r\n\t\t\tsum += a.value[index];\r\n\t\t\tindex += a.height+1;\r\n\t\t}\r\n\t\treturn sum;\r\n\t}\r\n\r\n\tpublic double[][] getAs2DArray()\r\n\t{\r\n\t\tdouble[][] result = new double[height][width];\r\n\t\tint i=0;\r\n\t\tfor(int y=0;y<height;y++)\r\n\t\t{\r\n\t\t\tfor(int x=0;x<width;x++)\r\n\t\t\t{\r\n\t\t\t\tresult[y][x]=value[i];\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\r\n\tpublic void setFrom2DArray(double[][] a)\r\n\t{\r\n\t\tint i=0;\r\n\t\tfor(int y=0;y<height;y++)\r\n\t\t{\r\n\t\t\tfor(int x=0;x<width;x++)\r\n\t\t\t{\r\n\t\t\t\tvalue[i]=a[y][x];\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t \r\n\t public GeneralMatrixDouble(int width)\r\n\t {\r\n\t\t this.width = width;\r\n\t }\r\n\r\n\t public int appendRows(int numRows)\r\n\t {\r\n\t \tint newSize = width*(height+numRows);\r\n\t \tif(value==null)\r\n\t \t{\r\n\t \t\tvalue = new double[newSize];\r\n\t\t\t\theight+=numRows;\r\n\t\t\t\treturn height-numRows;\r\n\t \t}\r\n\t \tif(newSize>value.length)\r\n\t \t{\r\n\t \t\tensureCapacity(newSize);\r\n\t \t}\r\n\t\t\theight+=numRows;\r\n\t\t\treturn height-numRows;\r\n\t }\r\n\r\n\t public int appendRow()\r\n\t {\r\n\t \tint newSize = width*(height+1);\r\n\t \tif(value==null)\r\n\t \t{\r\n\t \t\tvalue = new double[newSize];\r\n\t\t\t\theight++;\r\n\t\t\t\treturn height-1;\r\n\t \t}\r\n\t \tif(newSize>value.length)\r\n\t \t{\r\n\t \t\tensureCapacity(newSize);\r\n\t \t}\r\n\t\t\theight++;\r\n\t\t\treturn height-1;\r\n\t }\r\n\r\n\t public void ensureCapacityNoCopy(int mincap)\r\n\t {\r\n\t \tif(value==null)\r\n\t \t{\r\n\t \t\tvalue = new double[mincap];\r\n\t \t}\r\n\t \telse\r\n\t \tif(mincap>value.length)\r\n\t \t{\r\n\t\t int newcap = (value.length * 3)/2 + 1;\r\n\t\t double[] olddata = value;\r\n\t\t value = new double[newcap < mincap ? mincap : newcap];\r\n\t \t}\r\n\t }\r\n\r\n\t public void ensureCapacity(int mincap)\r\n\t {\r\n\t \tif(value==null)\r\n\t \t{\r\n\t \t\tvalue = new double[mincap];\r\n\t \t}\r\n\t \telse\r\n\t \tif(mincap>value.length)\r\n\t \t{\r\n\t\t int newcap = (value.length * 3)/2 + 1;\r\n\t\t double[] olddata = value;\r\n\t\t value = new double[newcap < mincap ? mincap : newcap];\r\n\t\t System.arraycopy(olddata,0,value,0,width*height);\r\n\t \t}\r\n\t }\r\n\r\n\t public void setDimensions(int w,int h)\r\n\t {\r\n\t \tensureCapacity(w*h);\r\n\t \twidth = w;\r\n\t \theight = h;\r\n\t }\r\n\t public void setDimensionsNoCopy(int w,int h)\r\n\t {\r\n\t \tensureCapacityNoCopy(w*h);\r\n\t \twidth = w;\r\n\t \theight = h;\r\n\t }\r\n\r\n\t public void push_back(double val)\r\n\t {\r\n\t \tint ind = appendRow();\r\n\t \tvalue[ind] = val;\r\n\t }\r\n\t public void push_back_row(double val1,double val2)\r\n\t {\r\n\t \tint ind = appendRow();\r\n\t \tvalue[ind*2+0] = val1;\r\n\t \tvalue[ind*2+1] = val2;\r\n\t }\r\n\t public void push_back_row(double val1,double val2,double val3)\r\n\t {\r\n\t \tint ind = appendRow();\r\n\t \tvalue[ind*3+0] = val1;\r\n\t \tvalue[ind*3+1] = val2;\r\n\t \tvalue[ind*3+2] = val3;\r\n\t }\r\n\t public void push_back_row(double val1,double val2,double val3,double val4)\r\n\t {\r\n\t \tint ind = appendRow();\r\n\t \tvalue[ind*4+0] = val1;\r\n\t \tvalue[ind*4+1] = val2;\r\n\t \tvalue[ind*4+2] = val3;\r\n\t \tvalue[ind*4+3] = val4;\r\n\t }\r\n\t public void push_back_row(double val1,double val2,double val3,double val4,double val5,double val6)\r\n\t {\r\n\t \tint ind = appendRow();\r\n\t \tvalue[ind*6+0] = val1;\r\n\t \tvalue[ind*6+1] = val2;\r\n\t \tvalue[ind*6+2] = val3;\r\n\t \tvalue[ind*6+3] = val4;\r\n\t \tvalue[ind*6+4] = val5;\r\n\t \tvalue[ind*6+5] = val6;\r\n\t }\r\n\r\n\t public int push_back_row(double[] row)\r\n\t {\r\n\t \tint ind = appendRow();\r\n\t \tSystem.arraycopy(row, 0, value, width*(height-1), width);\r\n\t \treturn ind;\r\n\t }\r\n\t public int push_back_row(float[] row)\r\n\t {\r\n\t \tint ind = appendRow();\r\n\t \tint off = width*ind;\r\n\t \tfor(int i=0;i<width;i++)\r\n\t \t\tvalue[off+i] = row[i];\r\n\t \treturn ind;\r\n\t }\r\n\r\n\t public int push_back_row(double[] row, int off)\r\n\t {\r\n\t \tint ind = appendRow();\r\n\t \tSystem.arraycopy(row, off, value, width*(height-1), width);\r\n\t \treturn ind;\r\n\t }\r\n\t public void push_back_rows(GeneralMatrixDouble rows)\r\n\t {\r\n\t \tif(rows.height==0)\r\n\t \t\treturn;\r\n\t \tappendRows(rows.height);\r\n\t \tSystem.arraycopy(rows.value, 0, value, width*(height-rows.height), width*rows.height);\r\n\t }\r\n}\r", "public class GeneralMatrixFloat implements Serializable\r\n{\r\n\tprivate static final long serialVersionUID = 1L;\r\n\r\n\tpublic static final float EPSILON = 0.000000001f;\r\n\t//public static final float EPSILON=5.9e-8f;\r\n\tpublic int width = 0; //columns\r\n\tpublic int height = 0; //rows\r\n\tpublic float[] value = null; //array of values\r\n\r\n\tpublic GeneralMatrixFloat()\r\n\t{\r\n\t\twidth = 0;\r\n\t\theight = 0;\r\n\t}\r\n\tpublic GeneralMatrixFloat(float val)\r\n\t{\r\n\t\tthis.width = 1;\r\n\t\tthis.height = 1;\r\n\t\tthis.value = new float[1];\r\n\t\tthis.value[0] = val;\r\n\t}\r\n\tpublic GeneralMatrixFloat(float val0,float val1)\r\n\t{\r\n\t\tthis.width = 1;\r\n\t\tthis.height = 2;\r\n\t\tthis.value = new float[2];\r\n\t\tthis.value[0] = val0;\r\n\t\tthis.value[1] = val1;\r\n\t}\r\n\tpublic GeneralMatrixFloat(float val0,float val1,float val2)\r\n\t{\r\n\t\tthis.width = 1;\r\n\t\tthis.height = 3;\r\n\t\tthis.value = new float[3];\r\n\t\tthis.value[0] = val0;\r\n\t\tthis.value[1] = val1;\r\n\t\tthis.value[2] = val2;\r\n\t}\r\n\tpublic GeneralMatrixFloat(float val0,float val1,float val2,float val3)\r\n\t{\r\n\t\tthis.width = 1;\r\n\t\tthis.height = 4;\r\n\t\tthis.value = new float[4];\r\n\t\tthis.value[0] = val0;\r\n\t\tthis.value[1] = val1;\r\n\t\tthis.value[2] = val2;\r\n\t\tthis.value[3] = val3;\r\n\t}\r\n\tpublic GeneralMatrixFloat(float[] vals)\r\n\t{\r\n\t\tthis.width = vals.length;\r\n\t\tthis.height = 1;\r\n\t\tthis.value = vals;\r\n\t}\r\n\tpublic GeneralMatrixFloat(int width)\r\n\t{\r\n\t\tthis.width = width;\r\n\t}\r\n\tpublic GeneralMatrixFloat(int width,int height)\r\n\t{\r\n\t\tthis.width = width;\r\n\t\tthis.height = height;\r\n\t\tvalue = new float[width*height];\r\n\t}\r\n\tpublic GeneralMatrixFloat(int width,int height,float[] vals)\r\n\t{\r\n\t\tthis.width = width;\r\n\t\tthis.height = height;\r\n\t\tvalue = vals;\r\n\t}\r\n\tpublic GeneralMatrixFloat(GeneralMatrixFloat o)\r\n\t{\r\n\t\twidth = o.width;\r\n\t\theight = o.height;\r\n\t\tvalue = new float[width*height];\r\n\t\tset(o);\r\n\t}\r\n\tpublic GeneralMatrixFloat(GeneralMatrixDouble o)\r\n\t{\r\n\t\twidth = o.width;\r\n\t\theight = o.height;\r\n\t\tvalue = new float[width*height];\r\n\t\tset(o);\r\n\t}\r\n\r\n\tpublic boolean isequal(GeneralMatrixFloat o)\r\n\t{\r\n\t\tboolean is = true;\r\n\t\tis = is && (width==o.width);\r\n\t\tis = is && (height==o.height);\r\n\t\tif(is)\r\n\t\t{\r\n\t\t\tfor(int i=0;i<width*height;i++)\r\n\t\t\t{\r\n\t\t\t\tis = is && (value[i]==o.value[i]);\r\n\t\t\t}\r\n\t\t}\r\n\t\tif(!is)\r\n\t\t\tSystem.out.println(\"diff!\");\r\n\t\treturn is;\r\n\t}\r\n\t\r\n\tpublic boolean includesNAN()\r\n\t{\r\n\t\tfor (int i = 0; i < width*height; i++)\r\n\t\t{\r\n\t\t\tif(Float.isNaN(value[i]))\r\n\t\t\t\treturn true;\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\t\r\n\tpublic void clear(float v)\r\n\t{\r\n\t\tfor (int i = 0; i < width*height; i++)\r\n\t\t{\r\n\t\t\tvalue[i] = v;\r\n\t\t}\r\n\t}\r\n\tpublic void clearSubset(int xs,int ys,int sw,int sh,float v)\r\n\t{\r\n\t\tint maxy = ys+sh;\r\n\t\tint maxx = xs+sw;\r\n\t\tfor(int y=ys;y<maxy;y++)\r\n\t\t{\r\n\t\t\tfor(int x=xs;x<maxx;x++)\r\n\t\t\t{\r\n\t\t\t\tvalue[x+y*width] = v;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tpublic final float get(int i,int j)\r\n\t{\r\n\t\treturn value[j*width+i];\r\n\t}\r\n\t\r\n\tpublic float getMirror(int x, int y)\r\n {\r\n if (x >= width)\r\n x = width - (x - width + 2);\r\n\r\n if (y >= height)\r\n y = height - (y - height + 2);\r\n\r\n if (x < 0)\r\n {\r\n int tmp = 0;\r\n int dir = 1;\r\n\r\n while (x < 0)\r\n {\r\n tmp += dir;\r\n if (tmp == width - 1 || tmp == 0)\r\n dir *= -1;\r\n x++;\r\n }\r\n x = tmp;\r\n }\r\n\r\n if (y < 0)\r\n {\r\n int tmp = 0;\r\n int dir = 1;\r\n\r\n while (y < 0)\r\n {\r\n tmp += dir;\r\n if (tmp == height - 1 || tmp == 0)\r\n dir *= -1;\r\n y++;\r\n }\r\n y = tmp;\r\n }\r\n\r\n return value[x+y*width];\r\n }\t\r\n\tpublic void set(int i,int j,float v)\r\n\t{\r\n\t\tvalue[j*width+i] = v;\r\n\t}\r\n\r\n\tpublic void set(GeneralMatrixFloat a)\r\n\t{\r\n\t\tensureCapacityNoCopy(a.width*a.height);\r\n\t\twidth = a.width;\r\n\t\theight = a.height;\r\n\t\t for (int i = 0; i < width*height; i++)\r\n\t\t {\r\n\t\t\t value[i] = a.value[i];\r\n\t\t }\r\n\t}\r\n\tpublic void set(GeneralMatrixInt a)\r\n\t{\r\n\t\t for (int i = 0; i < width*height; i++) \r\n\t\t {\r\n\t\t\t value[i] = a.value[i];\r\n\t\t }\r\n\t}\r\n\tpublic void set(GeneralMatrixDouble a)\r\n\t{\r\n\t\t for (int i = 0; i < width*height; i++) \r\n\t\t {\r\n\t\t\t value[i] = (float)a.value[i];\r\n\t\t }\r\n\t}\r\n\t\r\n\tpublic void set(float[] a)\r\n\t{\r\n\t\t for (int i = 0; i < width*height; i++)\r\n\t\t {\r\n\t\t\t value[i] = a[i];\r\n\t\t }\r\n\t}\r\n\tpublic void set(double[] a)\r\n\t{\r\n\t\t for (int i = 0; i < width*height; i++)\r\n\t\t {\r\n\t\t\t value[i] = (float)a[i];\r\n\t\t }\r\n\t}\r\n\tpublic void set(double[][] a)\r\n\t{\r\n\t\t for (int j = 0; j < height; j++)\r\n\t\t {\r\n\t\t\t for (int i = 0; i < width; i++)\r\n\t\t\t {\r\n\t\t\t\t value[i+j*width] = (float)a[j][i];\r\n\t\t\t }\r\n\t\t }\r\n\t}\r\n\r\n\t public int find(float v0,float v1,float eps)\r\n\t {\r\n\t\t for(int i=0;i<(width*height);i+=2)\r\n\t\t {\r\n\t\t\t if((Math.abs(value[i]-v0)<=eps)&&(Math.abs(value[i+1]-v1)<=eps))\r\n\t\t\t\t return i/2;\r\n\t\t }\r\n\t\t return -1;\r\n\t }\r\n\t public int find(float v0,float v1,float v2,float eps)\r\n\t {\r\n\t\t for(int i=0;i<(width*height);i+=3)\r\n\t\t {\r\n\t\t\t if((Math.abs(value[i]-v0)<=eps)&&(Math.abs(value[i+1]-v1)<=eps)&&(Math.abs(value[i+2]-v2)<=eps))\r\n\t\t\t\t return i/3;\r\n\t\t }\r\n\t\t return -1;\r\n\t }\r\n\t public int find(float v0,float v1,float v2,float v3,float v4,float eps)\r\n\t {\r\n\t\t for(int i=0;i<(width*height);i+=5)\r\n\t\t {\r\n\t\t\t if((Math.abs(value[i]-v0)<=eps)&&(Math.abs(value[i+1]-v1)<=eps)&&(Math.abs(value[i+2]-v2)<=eps)&&(Math.abs(value[i+3]-v3)<=eps)&&(Math.abs(value[i+4]-v4)<=eps))\r\n\t\t\t\t return i/5;\r\n\t\t }\r\n\t\t return -1;\r\n\t }\r\n\r\n\t//Insertion and deletion\r\n public int appendRow()\r\n {\r\n \tint newSize = width*(height+1);\r\n \tif(value==null)\r\n \t{\r\n \t\tvalue = new float[newSize];\r\n\t\t\theight++;\r\n\t\t\treturn height-1;\r\n \t}\r\n \tif(newSize>value.length)\r\n \t{\r\n \t\tensureCapacity(newSize);\r\n \t}\r\n\t\theight++;\r\n\t\treturn height-1;\r\n }\r\n\r\n public int appendRows(int size)\r\n {\r\n \tint newSize = width*(height+size);\r\n \tif(value==null)\r\n \t{\r\n \t\tvalue = new float[newSize];\r\n\t\t\theight+=size;\r\n\t\t\treturn height-size;\r\n \t}\r\n \tif(newSize>value.length)\r\n \t{\r\n \t\tensureCapacity(newSize);\r\n \t}\r\n\t\theight+=size;\r\n\t\treturn height-size;\r\n }\r\n \r\n public int appendRows(int size,float defaultValue)\r\n {\r\n \tint newSize = width*(height+size);\r\n \tif(value==null)\r\n \t{\r\n \t\tvalue = new float[newSize];\r\n\t\t\theight+=size;\r\n\t\t\tclear(defaultValue);\r\n\t\t\treturn height-size;\r\n \t}\r\n \tif(newSize>value.length)\r\n \t{\r\n \t\tensureCapacity(newSize);\r\n \t}\r\n\t\tfor(int i=width*height;i<(width*(height+size));i++)\r\n\t\t{\r\n\t\t\tvalue[i] = defaultValue;\r\n\t\t}\r\n\t\theight+=size;\r\n\t\treturn height-size;\r\n }\r\n \r\n public void removeRow(int index)\r\n {\r\n \tif(index>=height)\r\n \t{\r\n \t\tSystem.out.println(\"Row being removed larger than matrix\");\r\n \t}\r\n \tfor(int i=index*width;i<((height-1))*width;i++)\r\n \t{\r\n \t\tvalue[i] = value[(i+width)];\r\n \t}\r\n \theight--;\r\n }\r\n\r\n public void insertRowAfter(int index)\r\n {\r\n \tappendRow();\r\n \tSystem.arraycopy(value, (index+1)*width, value, (index+2)*width, (height-1-(index+1))*width);\r\n }\r\n\r\n public void insertRowBefore(int index)\r\n {\r\n \tint srcind = (index)*width;\r\n \tint destind = (index+1)*width;\r\n \tint length = (height-1-(index))*width;\r\n \ttry{\r\n\t \tappendRow();\r\n\t \tSystem.arraycopy(value, srcind, value, destind, length);\t \t\t\r\n \t}\r\n \tcatch(Exception e)\r\n \t{\r\n \t\tSystem.out.println(\"insertRowBefore error\");\r\n \t}\r\n }\r\n \r\n public void ensureCapacityNoCopy(int mincap)\r\n {\r\n \tif(value==null)\r\n \t{\r\n \t\tvalue = new float[mincap];\r\n \t}\r\n \telse\r\n \tif(mincap>value.length)\r\n \t{\r\n\t int newcap = mincap;//(value.length * 3)/2 + 1;\r\n\t //float[] olddata = value;\r\n\t value = new float[newcap < mincap ? mincap : newcap];\r\n \t}\r\n }\r\n\r\n public void ensureCapacity(int mincap)\r\n {\r\n \tif(value==null)\r\n \t{\r\n \t\tvalue = new float[mincap];\r\n \t}\r\n \telse\r\n \tif(mincap>value.length)\r\n \t{\r\n\t int newcap = (value.length * 3)/2 + 1;\r\n\t float[] olddata = value;\r\n\t value = new float[newcap < mincap ? mincap : newcap];\r\n\t System.arraycopy(olddata,0,value,0,olddata.length);\r\n \t}\r\n }\r\n public void setDimensions(int w,int h)\r\n {\r\n \tensureCapacity(w*h);\r\n \twidth = w;\r\n \theight = h;\r\n }\r\n public void setDimensionsNoCopy(int w,int h)\r\n {\r\n \tensureCapacityNoCopy(w*h);\r\n \twidth = w;\r\n \theight = h;\r\n }\r\n public int push_back(float val)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind] = val;\r\n \treturn ind;\r\n }\r\n \r\n public void set_row(int row,float val1,float val2)\r\n {\r\n \tint ind = row*width;\r\n \tvalue[ind+0] = val1;\r\n \tvalue[ind+1] = val2; \t\r\n } \r\n public int push_back_row(float val1,float val2)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*2+0] = val1;\r\n \tvalue[ind*2+1] = val2;\r\n \treturn ind;\r\n }\r\n public void set_row(int row,float val1,float val2,float val3)\r\n {\r\n \tint ind = row*width;\r\n \tvalue[ind+0] = val1;\r\n \tvalue[ind+1] = val2; \t\r\n \tvalue[ind+2] = val3; \t\r\n } \r\n public int push_back_row(float val1,float val2,float val3)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*width+0] = val1;\r\n \tvalue[ind*width+1] = val2;\r\n \tvalue[ind*width+2] = val3;\r\n \treturn ind;\r\n }\r\n public void set_row(int row,float val1,float val2,float val3,float val4)\r\n {\r\n \tint ind = row*width;\r\n \tvalue[ind+0] = val1;\r\n \tvalue[ind+1] = val2; \t\r\n \tvalue[ind+2] = val3; \t\r\n \tvalue[ind+3] = val4; \t\r\n } \r\n public int push_back_row(float val1,float val2,float val3,float val4)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*4+0] = val1;\r\n \tvalue[ind*4+1] = val2;\r\n \tvalue[ind*4+2] = val3;\r\n \tvalue[ind*4+3] = val4;\r\n \treturn ind;\r\n }\r\n public void set_row(int row,float val1,float val2,float val3,float val4,float val5)\r\n {\r\n \tint ind = row*width;\r\n \tvalue[ind+0] = val1;\r\n \tvalue[ind+1] = val2; \t\r\n \tvalue[ind+2] = val3; \t\r\n \tvalue[ind+3] = val4; \t\r\n \tvalue[ind+4] = val5; \t\r\n } \r\n public void push_back_row(float val1,float val2,float val3,float val4,float val5)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*5+0] = val1;\r\n \tvalue[ind*5+1] = val2;\r\n \tvalue[ind*5+2] = val3;\r\n \tvalue[ind*5+3] = val4;\r\n \tvalue[ind*5+4] = val5;\r\n }\r\n public void set_row(int row,float val1,float val2,float val3,float val4,float val5,float val6)\r\n {\r\n \tint ind = row*width;\r\n \tvalue[ind+0] = val1;\r\n \tvalue[ind+1] = val2; \t\r\n \tvalue[ind+2] = val3; \t\r\n \tvalue[ind+3] = val4; \t\r\n \tvalue[ind+4] = val5; \t\r\n \tvalue[ind+5] = val6; \t\r\n } \r\n public int push_back_row(float val1,float val2,float val3,float val4,float val5,float val6)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*6+0] = val1;\r\n \tvalue[ind*6+1] = val2;\r\n \tvalue[ind*6+2] = val3;\r\n \tvalue[ind*6+3] = val4;\r\n \tvalue[ind*6+4] = val5;\r\n \tvalue[ind*6+5] = val6;\r\n \treturn ind;\r\n }\r\n public int push_back_row(float val1,float val2,float val3,float val4,float val5,float val6,float val7)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*7+0] = val1;\r\n \tvalue[ind*7+1] = val2;\r\n \tvalue[ind*7+2] = val3;\r\n \tvalue[ind*7+3] = val4;\r\n \tvalue[ind*7+4] = val5;\r\n \tvalue[ind*7+5] = val6;\r\n \tvalue[ind*7+6] = val7;\r\n \treturn ind;\r\n }\r\n public int push_back_row(float val1,float val2,float val3,float val4,float val5,float val6,float val7,float val8)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*8+0] = val1;\r\n \tvalue[ind*8+1] = val2;\r\n \tvalue[ind*8+2] = val3;\r\n \tvalue[ind*8+3] = val4;\r\n \tvalue[ind*8+4] = val5;\r\n \tvalue[ind*8+5] = val6;\r\n \tvalue[ind*8+6] = val7;\r\n \tvalue[ind*8+7] = val8;\r\n \treturn ind;\r\n }\r\n public void push_back_row(float val1,float val2,float val3,float val4,float val5,float val6,float val7,float val8,float val9)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*9+0] = val1;\r\n \tvalue[ind*9+1] = val2;\r\n \tvalue[ind*9+2] = val3;\r\n \tvalue[ind*9+3] = val4;\r\n \tvalue[ind*9+4] = val5;\r\n \tvalue[ind*9+5] = val6;\r\n \tvalue[ind*9+6] = val7;\r\n \tvalue[ind*9+7] = val8;\r\n \tvalue[ind*9+8] = val9;\r\n }\r\n public void push_back_row(float val1,float val2,float val3,float val4,float val5,float val6,float val7,float val8,float val9,float val10,float val11)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*11+0] = val1;\r\n \tvalue[ind*11+1] = val2;\r\n \tvalue[ind*11+2] = val3;\r\n \tvalue[ind*11+3] = val4;\r\n \tvalue[ind*11+4] = val5;\r\n \tvalue[ind*11+5] = val6;\r\n \tvalue[ind*11+6] = val7;\r\n \tvalue[ind*11+7] = val8;\r\n \tvalue[ind*11+8] = val9;\r\n \tvalue[ind*11+9] = val10;\r\n \tvalue[ind*11+10] = val11;\r\n }\r\n public void push_back_row(float val1,float val2,float val3,float val4,float val5,float val6,float val7,float val8,float val9,float val10,float val11,float val12,float val13,float val14)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*14+0] = val1;\r\n \tvalue[ind*14+1] = val2;\r\n \tvalue[ind*14+2] = val3;\r\n \tvalue[ind*14+3] = val4;\r\n \tvalue[ind*14+4] = val5;\r\n \tvalue[ind*14+5] = val6;\r\n \tvalue[ind*14+6] = val7;\r\n \tvalue[ind*14+7] = val8;\r\n \tvalue[ind*14+8] = val9;\r\n \tvalue[ind*14+9] = val10;\r\n \tvalue[ind*14+10] = val11;\r\n \tvalue[ind*14+11] = val12;\r\n \tvalue[ind*14+12] = val13;\r\n \tvalue[ind*14+13] = val14;\r\n }\r\n\r\n public void push_back_row(float val1,float val2,float val3,float val4,float val5,float val6,float val7,float val8,float val9,float val10,float val11,float val12,float val13,float val14,float val15,float val16)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*16+0] = val1;\r\n \tvalue[ind*16+1] = val2;\r\n \tvalue[ind*16+2] = val3;\r\n \tvalue[ind*16+3] = val4;\r\n \tvalue[ind*16+4] = val5;\r\n \tvalue[ind*16+5] = val6;\r\n \tvalue[ind*16+6] = val7;\r\n \tvalue[ind*16+7] = val8;\r\n \tvalue[ind*16+8] = val9;\r\n \tvalue[ind*16+9] = val10;\r\n \tvalue[ind*16+10] = val11;\r\n \tvalue[ind*16+11] = val12;\r\n \tvalue[ind*16+12] = val13;\r\n \tvalue[ind*16+13] = val14;\r\n \tvalue[ind*16+14] = val15;\r\n \tvalue[ind*16+15] = val16;\r\n }\r\n\r\n public void push_back_row(GeneralMatrixFloat row)\r\n {\r\n \tappendRow();\r\n \tSystem.arraycopy(row.value, 0, value, width*(height-1), width);\r\n }\r\n\r\n public void push_back_row_from_matrix(GeneralMatrixFloat row,int i)\r\n {\r\n \tappendRow();\r\n \tSystem.arraycopy(row.value, i*width, value, width*(height-1), width);\r\n }\r\n\r\n public void push_back_row(GeneralMatrixDouble row)\r\n {\r\n \tappendRow();\r\n \tint off = width*(height-1); \r\n \tfor(int i=0;i<width;i++)\r\n \t{\r\n \t\tvalue[off+i] = (float)row.value[i];\r\n \t}\r\n }\r\n\r\n public int push_back_row(float[] row)\r\n {\r\n \tint ind = appendRow();\r\n \tSystem.arraycopy(row, 0, value, width*(height-1), width);\r\n \treturn ind;\r\n }\r\n public int push_back_row(float[] row,int off)\r\n {\r\n \tint ind = appendRow();\r\n \tSystem.arraycopy(row, off, value, width*(height-1), width);\r\n \treturn ind;\r\n }\r\n public int push_back_row(float[] row,int off,int w)\r\n {\r\n \tint ind = appendRow();\r\n \tint inoff = width*(height-1);\r\n \tSystem.arraycopy(row, off, value, inoff, Math.min(width,w));\r\n \tfor(int i=w;i<width;i++)\r\n \t{\r\n \t\tvalue[inoff+i] = 0.0f;\r\n \t}\r\n \treturn ind;\r\n }\r\n public void push_back_row_from_block(GeneralMatrixFloat row,int yFromFull)\r\n {\r\n \tappendRow();\r\n \tSystem.arraycopy(row.value, yFromFull*width, value, width*(height-1), width);\r\n }\r\n \r\n public void push_back_rows(GeneralMatrixFloat rows)\r\n {\r\n \tif(rows.height==0)\r\n \t\treturn;\r\n \tappendRows(rows.height);\r\n \tSystem.arraycopy(rows.value, 0, value, width*(height-rows.height), width*rows.height);\r\n }\r\n\r\n public void push_back_matrices_as_row(GeneralMatrixFloat m0,GeneralMatrixFloat m1)\r\n {\r\n \tint ind = appendRow();\r\n \tint m0num = m0.width*m0.height;\r\n \tSystem.arraycopy(m0.value, 0, value, width*ind, m0num);\r\n \tint m1num = m1.width*m1.height;\r\n \tSystem.arraycopy(m1.value, 0, value, width*ind+m0num, m1num); \t\r\n }\r\n \r\n\tpublic void swapRows(int r1,int r2,float[] buffer)\r\n\t{\r\n\t\tSystem.arraycopy(value, r1*width, buffer, 0, width);\r\n\t\tSystem.arraycopy(value, r2*width, value, r1*width, width);\r\n\t\tSystem.arraycopy(buffer, 0, value, r2*width, width);\r\n\t}\r\n\r\n public void setRow(int r,GeneralMatrixFloat row)\r\n {\r\n \tSystem.arraycopy(row.value, 0, value, width*(r), width);\r\n }\r\n\r\n public void setRow(int r,GeneralMatrixDouble row)\r\n {\r\n \tfor(int i=0;i<width;i++)\r\n \t\tvalue[width*r+i] = (float)row.value[i];\r\n }\r\n \r\n public void setRowFromSubset(int r,GeneralMatrixFloat full,int ys)\r\n {\r\n \tSystem.arraycopy(full.value, ys*width, value, width*(r), width);\r\n }\r\n\r\n\t//For setting a vec or mat from an array of vecs/mats\r\n\tpublic void setFromSubset(GeneralMatrixFloat full,int ys)\r\n\t{\r\n\t\tint i=0;\r\n\t\tint fi = ys*width;\r\n\t\tfor(int y=0;y<height;y++)\r\n\t\t{\r\n\t\t\tfor(int x=0;x<width;x++)\r\n\t\t\t{\r\n\t\t\t\tvalue[i] = full.value[fi];\r\n\t\t\t\ti++;\r\n\t\t\t\tfi++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tpublic void setFromSubset(GeneralMatrixDouble full,int ys)\r\n\t{\r\n\t\tint i=0;\r\n\t\tint fi = ys*width;\r\n\t\tfor(int y=0;y<height;y++)\r\n\t\t{\r\n\t\t\tfor(int x=0;x<width;x++)\r\n\t\t\t{\r\n\t\t\t\tvalue[i] = (float)full.value[fi];\r\n\t\t\t\ti++;\r\n\t\t\t\tfi++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic void setSubset(GeneralMatrixFloat subset,int xs,int ys)\r\n\t{\r\n\t\tint maxy = ys+subset.height;\r\n\t\tint maxx = xs+subset.width;\r\n\t\tfor(int y=ys;y<maxy;y++)\r\n\t\t{\r\n\t\t\tfor(int x=xs;x<maxx;x++)\r\n\t\t\t{\r\n\t\t\t\tvalue[x+y*width] = subset.value[(x-xs)+(y-ys)*subset.width];\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t//Setup matrix transforms\r\n\t\r\n\tpublic void set3DTransformPosition(float x,float y,float z)\r\n\t{\r\n\t\tvalue[4*3+0] = x;\r\n\t\tvalue[4*3+1] = y;\r\n\t\tvalue[4*3+2] = z;\r\n\t}\r\n\tpublic void calcBasisFromNormal(float x,float y,float z)\r\n\t{\r\n\t\tvalue[4*2+0] = x;\r\n\t\tvalue[4*2+1] = y;\r\n\t\tvalue[4*2+2] = z;\r\n\r\n\t\tif(\r\n\t\t\t\t(Math.abs(x)<=Math.abs(y))&&(Math.abs(x)<=Math.abs(z))\r\n\t\t )\r\n\t\t{\r\n\t\t\tvalue[4*0+0] = 1.0f;\r\n\t\t\tvalue[4*0+1] = 0.0f;\r\n\t\t\tvalue[4*0+2] = 0.0f;\r\n\t\t}\t\r\n\t\telse\r\n\t\tif(Math.abs(y)<Math.abs(z))\r\n\t\t{\r\n\t\t\tvalue[4*0+0] = 0.0f;\r\n\t\t\tvalue[4*0+1] = 1.0f;\r\n\t\t\tvalue[4*0+2] = 0.0f;\t\t\t\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tvalue[4*0+0] = 0.0f;\r\n\t\t\tvalue[4*0+1] = 0.0f;\r\n\t\t\tvalue[4*0+2] = 1.0f;\t\t\t\r\n\t\t}\r\n\t\t\r\n\t\tvalue[4*1+0] = y*value[4*0+2]-value[4*0+1]*z;\r\n\t\tvalue[4*1+1] = z*value[4*0+0]-value[4*0+2]*x;\r\n\t\tvalue[4*1+2] = x*value[4*0+1]-value[4*0+0]*y;\r\n\r\n\t\t//Normalise\r\n\t\tfloat total = value[4*1+0]*value[4*1+0];\r\n\t\ttotal += value[4*1+1]*value[4*1+1];\r\n\t\ttotal += value[4*1+2]*value[4*1+2];\r\n\t\tif(total<=EPSILON)\r\n\t\t{\r\n\t\t\tvalue[4*1+0] = 1.0f;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\ttotal = (float)Math.sqrt(total);\r\n\t\t}\r\n\t\tvalue[4*1+0] /= total;\r\n\t\tvalue[4*1+1] /= total;\r\n\t\tvalue[4*1+2] /= total;\r\n\t\t\r\n\t\tvalue[4*0+0] = y*value[4*1+2]-value[4*1+1]*z;\r\n\t\tvalue[4*0+1] = z*value[4*1+0]-value[4*1+2]*x;\r\n\t\tvalue[4*0+2] = x*value[4*1+1]-value[4*1+0]*y;\r\n\r\n\t\ttotal = value[4*0+0]*value[4*0+0];\r\n\t\ttotal += value[4*0+1]*value[4*0+1];\r\n\t\ttotal += value[4*0+2]*value[4*0+2];\r\n\t\tif(total<=EPSILON)\r\n\t\t{\r\n\t\t\tvalue[4*0+0] = 1.0f;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\ttotal = (float)Math.sqrt(total);\r\n\t\t}\r\n\t\tvalue[4*0+0] /= total;\r\n\t\tvalue[4*0+1] /= total;\r\n\t\tvalue[4*0+2] /= total;\r\n\t}\r\n\tpublic void calcBasisFromY(float x,float y,float z)\r\n\t{\r\n\t\tif((Math.abs(x)<=EPSILON)&&(Math.abs(y)<=EPSILON)&&(Math.abs(z)<=EPSILON))\r\n\t\t{\r\n\t\t\tsetIdentity();\r\n\t\t}\r\n\t\telse\r\n\t\tif(\r\n\t\t\t\t(Math.abs(x)<=Math.abs(y))&&(Math.abs(x)<=Math.abs(z))\r\n\t\t )\r\n\t\t{\r\n\t\t\tcalcBasisFromY(x, y, z, 1.0f, 0.0f, 0.0f);\r\n\t\t}\t\r\n\t\telse\r\n\t\tif(Math.abs(y)<=Math.abs(z))\r\n\t\t{\r\n\t\t\tcalcBasisFromY(x, y, z, 0.0f, 1.0f, 0.0f);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tcalcBasisFromY(x, y, z, 0.0f, 0.0f, 1.0f);\r\n\t\t}\r\n\r\n\t}\r\n\tpublic void calcBasisFromY(float x,float y,float z,\r\n\t\t\tfloat Xx,float Xy,float Xz)\r\n\t{\r\n\t\tvalue[width*1+0] = x;\r\n\t\tvalue[width*1+1] = y;\r\n\t\tvalue[width*1+2] = z;\r\n\t\tfloat total = x*x;\r\n\t\ttotal += y*y;\r\n\t\ttotal += z*z;\r\n\t\tif(total<=EPSILON)\r\n\t\t{\r\n\t\t\tvalue[width*1+0] = 1.0f;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\ttotal = (float)Math.sqrt(total);\r\n\t\t}\r\n\t\tvalue[width*1+0] /= total;\r\n\t\tvalue[width*1+1] /= total;\r\n\t\tvalue[width*1+2] /= total;\r\n\t\t\r\n\t\ttotal = Xx*Xx;\r\n\t\ttotal += Xy*Xy;\r\n\t\ttotal += Xz*Xz;\r\n\t\tif(total<=EPSILON)\r\n\t\t{\r\n\t\t\tvalue[width*0+0] = 1.0f;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\ttotal = (float)Math.sqrt(total);\r\n\t\t\tvalue[width*0+0] = Xx/total;\r\n\t\t\tvalue[width*0+1] = Xy/total;\r\n\t\t\tvalue[width*0+2] = Xz/total;\r\n\t\t}\r\n\r\n\t\t\r\n\t\tvalue[width*2+0] = -y*value[width*0+2]+value[width*0+1]*z;\r\n\t\tvalue[width*2+1] = -z*value[width*0+0]+value[width*0+2]*x;\r\n\t\tvalue[width*2+2] = -x*value[width*0+1]+value[width*0+0]*y;\r\n\r\n\t\t//Normalise\r\n\t\ttotal = value[width*2+0]*value[width*2+0];\r\n\t\ttotal += value[width*2+1]*value[width*2+1];\r\n\t\ttotal += value[width*2+2]*value[width*2+2];\r\n\t\tif(total<=EPSILON)\r\n\t\t{\r\n\t\t\tvalue[width*2+0] = 1.0f;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\ttotal = (float)Math.sqrt(total);\r\n\t\t\tvalue[width*2+0] /= total;\r\n\t\t\tvalue[width*2+1] /= total;\r\n\t\t\tvalue[width*2+2] /= total;\r\n\t\t}\r\n\t\t\r\n\t\tvalue[width*0+0] = y*value[width*2+2]-value[width*2+1]*z;\r\n\t\tvalue[width*0+1] = z*value[width*2+0]-value[width*2+2]*x;\r\n\t\tvalue[width*0+2] = x*value[width*2+1]-value[width*2+0]*y;\r\n\r\n\t\ttotal = value[width*0+0]*value[width*0+0];\r\n\t\ttotal += value[width*0+1]*value[width*0+1];\r\n\t\ttotal += value[width*0+2]*value[width*0+2];\r\n\t\tif(total<=EPSILON)\r\n\t\t{\r\n\t\t\tvalue[width*0+0] = 1.0f;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\ttotal = (float)Math.sqrt(total);\r\n\t\t\tvalue[width*0+0] /= total;\r\n\t\t\tvalue[width*0+1] /= total;\r\n\t\t\tvalue[width*0+2] /= total;\r\n\t\t}\r\n\t}\r\n\tpublic void flipX()\r\n\t{\r\n\t\tvalue[4*0+0] = -value[4*0+0];\r\n\t\tvalue[4*0+1] = -value[4*0+1];\r\n\t\tvalue[4*0+2] = -value[4*0+2];\r\n\t}\r\n\tpublic void flipY()\r\n\t{\r\n\t\tvalue[4*1+0] = -value[4*1+0];\r\n\t\tvalue[4*1+1] = -value[4*1+1];\r\n\t\tvalue[4*1+2] = -value[4*1+2];\r\n\t}\r\n\tpublic void flipZ()\r\n\t{\r\n\t\tvalue[4*2+0] = -value[4*2+0];\r\n\t\tvalue[4*2+1] = -value[4*2+1];\r\n\t\tvalue[4*2+2] = -value[4*2+2];\r\n\t}\r\n\tpublic void set3DBasis(GeneralMatrixFloat basis)\r\n\t{\r\n\t\tvalue[4*0+0] = basis.value[3*0+0];\r\n\t\tvalue[4*0+1] = basis.value[3*0+1];\r\n\t\tvalue[4*0+2] = basis.value[3*0+2];\r\n\r\n\t\tvalue[4*1+0] = basis.value[3*1+0];\r\n\t\tvalue[4*1+1] = basis.value[3*1+1];\r\n\t\tvalue[4*1+2] = basis.value[3*1+2];\r\n\r\n\t\tvalue[4*2+0] = basis.value[3*2+0];\r\n\t\tvalue[4*2+1] = basis.value[3*2+1];\r\n\t\tvalue[4*2+2] = basis.value[3*2+2];\r\n\t}\r\n\tpublic void set3DTransformScale(float scale)\r\n\t{\r\n\t\tvalue[4*0+0] *= scale;\r\n\t\tvalue[4*0+1] *= scale;\r\n\t\tvalue[4*0+2] *= scale;\r\n\t\t\r\n\t\tvalue[4*1+0] *= scale;\r\n\t\tvalue[4*1+1] *= scale;\r\n\t\tvalue[4*1+2] *= scale;\r\n\t\t\r\n\t\tvalue[4*2+0] *= scale;\r\n\t\tvalue[4*2+1] *= scale;\r\n\t\tvalue[4*2+2] *= scale;\r\n\t}\r\n\tpublic void set3DBasis(float Xx,float Xy,float Xz,\r\n\t\t\t\t\t\t\tfloat Yx,float Yy,float Yz,\r\n\t\t\t\t\t\t\tfloat Zx,float Zy,float Zz)\r\n\t{\r\n\t\tvalue[4*0+0] = Xx;\r\n\t\tvalue[4*0+1] = Xy;\r\n\t\tvalue[4*0+2] = Xz;\r\n\r\n\t\tvalue[4*1+0] = Yx;\r\n\t\tvalue[4*1+1] = Yy;\r\n\t\tvalue[4*1+2] = Yz;\r\n\r\n\t\tvalue[4*2+0] = Zx;\r\n\t\tvalue[4*2+1] = Zy;\r\n\t\tvalue[4*2+2] = Zz;\r\n\t}\r\n\tpublic void set3DBasis(float[] basis, int offset)\r\n\t{\r\n\t\tvalue[4*0+0] = basis[3*0+0+offset];\r\n\t\tvalue[4*0+1] = basis[3*0+1+offset];\r\n\t\tvalue[4*0+2] = basis[3*0+2+offset];\r\n\r\n\t\tvalue[4*1+0] = basis[3*1+0+offset];\r\n\t\tvalue[4*1+1] = basis[3*1+1+offset];\r\n\t\tvalue[4*1+2] = basis[3*1+2+offset];\r\n\r\n\t\tvalue[4*2+0] = basis[3*2+0+offset];\r\n\t\tvalue[4*2+1] = basis[3*2+1+offset];\r\n\t\tvalue[4*2+2] = basis[3*2+2+offset];\r\n\t}\r\n\tpublic void get3DBasis(float[] basis, int offset)\r\n\t{\r\n\t\tbasis[3*0+0+offset] = value[4*0+0];\r\n\t\tbasis[3*0+1+offset] = value[4*0+1];\r\n\t\tbasis[3*0+2+offset] = value[4*0+2];\r\n\r\n\t\tbasis[3*1+0+offset] = value[4*1+0];\r\n\t\tbasis[3*1+1+offset] = value[4*1+1];\r\n\t\tbasis[3*1+2+offset] = value[4*1+2];\r\n\r\n\t\tbasis[3*2+0+offset] = value[4*2+0];\r\n\t\tbasis[3*2+1+offset] = value[4*2+1];\r\n\t\tbasis[3*2+2+offset] = value[4*2+2];\r\n\t}\r\n\tpublic void set2DTransformZRotation(float z)\r\n\t{\r\n\t\tfloat sin=(float)Math.sin(z);\r\n\t\tfloat cos=(float)Math.cos(z);\r\n\t\tvalue[2*0+0] = cos;\r\n\t\tvalue[2*0+1] = -sin;\r\n\t\tvalue[2*1+0] = sin;\r\n\t\tvalue[2*1+1] = cos;\r\n\t}\r\n\r\n\tpublic void set3DTransformZRotation(float z)\r\n\t{\r\n\t\tfloat sin=(float)Math.sin(z);\r\n\t\tfloat cos=(float)Math.cos(z);\r\n\t\tvalue[4*0+0] = cos;\r\n\t\tvalue[4*0+1] = -sin;\r\n\t\tvalue[4*1+0] = sin;\r\n\t\tvalue[4*1+1] = cos;\r\n\t\tvalue[4*2+2] = 1.0f;\r\n\t}\r\n\tpublic void set3DTransformYRotation(float y)\r\n\t{\r\n\t\tfloat sin=(float)Math.sin(y);\r\n\t\tfloat cos=(float)Math.cos(y);\r\n\t\tif(width==4)\r\n\t\t{\r\n\t\t\tvalue[4*0+0] = cos;\r\n\t\t\tvalue[4*0+2] = sin;\r\n\t\t\tvalue[4*2+0] = -sin;\r\n\t\t\tvalue[4*2+2] = cos;\r\n\t\t\tvalue[4*1+1] = 1.0f;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tvalue[3*0+0] = cos;\r\n\t\t\tvalue[3*0+2] = sin;\r\n\t\t\tvalue[3*2+0] = -sin;\r\n\t\t\tvalue[3*2+2] = cos;\r\n\t\t\tvalue[3*1+1] = 1.0f;\r\n\t\t}\r\n\t}\r\n\tpublic void set3DTransformXRotation(float x)\r\n\t{\r\n\t\tsetIdentity();\r\n\t\tfloat sin=(float)Math.sin(x);\r\n\t\tfloat cos=(float)Math.cos(x);\r\n\t\tif(width==4)\r\n\t\t{\r\n\t\t\tvalue[4*1+1] = cos;\r\n\t\t\tvalue[4*1+2] = -sin;\r\n\t\t\tvalue[4*2+1] = sin;\r\n\t\t\tvalue[4*2+2] = cos;\r\n\t\t\tvalue[4*0+0] = 1.0f;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tvalue[3*1+1] = cos;\r\n\t\t\tvalue[3*1+2] = -sin;\r\n\t\t\tvalue[3*2+1] = sin;\r\n\t\t\tvalue[3*2+2] = cos;\r\n\t\t\tvalue[3*0+0] = 1.0f;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic void set3DTransformRotation(double x,double y,double z)\r\n\t{\r\n\t\tfloat sx=(float)Math.sin(x);\r\n\t\tfloat cx=(float)Math.cos(x);\r\n\t\tfloat sy=(float)Math.sin(y);\r\n\t\tfloat cy=(float)Math.cos(y);\r\n\t\tfloat sz=(float)Math.sin(z);\r\n\t\tfloat cz=(float)Math.cos(z);\r\n\r\n\t\tif(width==4)\r\n\t\t{\r\n\t\t\tvalue[4*0+0] = cz*cy;\r\n\t\t\tvalue[4*0+1] = (sy*sx*cz-cx*sz);\r\n\t\t\tvalue[4*0+2] = (sy*cx*cz+sz*sx);\r\n\t\r\n\t\t\tvalue[4*1+0] = sz*cy;\r\n\t\t\tvalue[4*1+1] = (sy*sx*sz+cx*cz);\r\n\t\t\tvalue[4*1+2] = (sy*cx*sz-cz*sx);\r\n\t\r\n\t\t\tvalue[4*2+0] = -sy;\r\n\t\t\tvalue[4*2+1] = cy*sx;\r\n\t\t\tvalue[4*2+2] = cy*cx;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tvalue[3*0+0] = cz*cy;\r\n\t\t\tvalue[3*0+1] = (sy*sx*cz-cx*sz);\r\n\t\t\tvalue[3*0+2] = (sy*cx*cz+sz*sx);\r\n\t\r\n\t\t\tvalue[3*1+0] = sz*cy;\r\n\t\t\tvalue[3*1+1] = (sy*sx*sz+cx*cz);\r\n\t\t\tvalue[3*1+2] = (sy*cx*sz-cz*sx);\r\n\t\r\n\t\t\tvalue[3*2+0] = -sy;\r\n\t\t\tvalue[3*2+1] = cy*sx;\r\n\t\t\tvalue[3*2+2] = cy*cx;\r\n\t\t}\r\n\t}\r\n\t\r\n//\t[ cz*cy ,-(sz), cz*sy ]\r\n//\t[ ]\r\n//\t[(cx*sz*cy)+((-(sx))*(-(sy))),cx*cz,(cx*sz*sy)+((-(sx))*cy)]\r\n//\t[ ]\r\n//\t[ (sx*sz*cy)+(cx*(-(sy))) ,sx*cz, (sx*sz*sy)+(cx*cy) ]\r\n\tpublic void set3DTransformRotationXZY(double x,double y,double z)\r\n\t{\r\n\t\tfloat sx=(float)Math.sin(x);\r\n\t\tfloat cx=(float)Math.cos(x);\r\n\t\tfloat sy=(float)Math.sin(y);\r\n\t\tfloat cy=(float)Math.cos(y);\r\n\t\tfloat sz=(float)Math.sin(z);\r\n\t\tfloat cz=(float)Math.cos(z);\r\n\r\n\t\tif(width==4)\r\n\t\t{\r\n\t\t\tvalue[4*0+0] = cz*cy;\r\n\t\t\tvalue[4*0+1] = -(sz);\r\n\t\t\tvalue[4*0+2] = cz*sy;\r\n\t\r\n\t\t\tvalue[4*1+0] = (cx*sz*cy)+((-(sx))*(-(sy)));\r\n\t\t\tvalue[4*1+1] = cx*cz;\r\n\t\t\tvalue[4*1+2] = (cx*sz*sy)+((-(sx))*cy);\r\n\t\r\n\t\t\tvalue[4*2+0] = (sx*sz*cy)+(cx*(-(sy)));\r\n\t\t\tvalue[4*2+1] = sx*cz;\r\n\t\t\tvalue[4*2+2] = (sx*sz*sy)+(cx*cy);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tvalue[3*0+0] = cz*cy;\r\n\t\t\tvalue[3*0+1] = -(sz);\r\n\t\t\tvalue[3*0+2] = cz*sy;\r\n\t\r\n\t\t\tvalue[3*1+0] = (cx*sz*cy)+((-(sx))*(-(sy)));\r\n\t\t\tvalue[3*1+1] = cx*cz;\r\n\t\t\tvalue[3*1+2] = (cx*sz*sy)+((-(sx))*cy);\r\n\t\r\n\t\t\tvalue[3*2+0] = (sx*sz*cy)+(cx*(-(sy)));\r\n\t\t\tvalue[3*2+1] = sx*cz;\r\n\t\t\tvalue[3*2+2] = (sx*sz*sy)+(cx*cy);\r\n\t\t}\r\n\t}\r\n\t\r\n//\t [ (cy*cz)+(sy*sx*sz) , (cy*(-(sz)))+(sy*sx*cz) ,sy*cx]\r\n//\t [ ]\r\n//\t [ cx*sz , cx*cz ,-(sx)]\r\n//\t [ ]\r\n//\t [((-(sy))*cz)+(cy*sx*sz),((-(sy))*(-(sz)))+(cy*sx*cz),cy*cx]\r\n\tpublic void set3DTransformRotationYXZ(double x,double y,double z)\r\n\t{\r\n\t\tfloat sx=(float)Math.sin(x);\r\n\t\tfloat cx=(float)Math.cos(x);\r\n\t\tfloat sy=(float)Math.sin(y);\r\n\t\tfloat cy=(float)Math.cos(y);\r\n\t\tfloat sz=(float)Math.sin(z);\r\n\t\tfloat cz=(float)Math.cos(z);\r\n\r\n\t\tif(width==4)\r\n\t\t{\r\n\t\t\tvalue[4*0+0] = (cy*cz)+(sy*sx*sz);\r\n\t\t\tvalue[4*0+1] = (cy*(-(sz)))+(sy*sx*cz);\r\n\t\t\tvalue[4*0+2] = sy*cx;\r\n\t\r\n\t\t\tvalue[4*1+0] = cx*sz;\r\n\t\t\tvalue[4*1+1] = cx*cz;\r\n\t\t\tvalue[4*1+2] = -(sx);\r\n\t\r\n\t\t\tvalue[4*2+0] = ((-(sy))*cz)+(cy*sx*sz);\r\n\t\t\tvalue[4*2+1] = ((-(sy))*(-(sz)))+(cy*sx*cz);\r\n\t\t\tvalue[4*2+2] = cy*cx;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tvalue[3*0+0] = (cy*cz)+(sy*sx*sz);\r\n\t\t\tvalue[3*0+1] = (cy*(-(sz)))+(sy*sx*cz);\r\n\t\t\tvalue[3*0+2] = sy*cx;\r\n\t\r\n\t\t\tvalue[3*1+0] = cx*sz;\r\n\t\t\tvalue[3*1+1] = cx*cz;\r\n\t\t\tvalue[3*1+2] = -(sx);\r\n\t\r\n\t\t\tvalue[3*2+0] = ((-(sy))*cz)+(cy*sx*sz);\r\n\t\t\tvalue[3*2+1] = ((-(sy))*(-(sz)))+(cy*sx*cz);\r\n\t\t\tvalue[3*2+2] = cy*cx;\r\n\t\t}\r\n\t}\r\n\r\n//\t[ cy*cz , (cy*(-(sz))*cx)+(sy*sx) , ((cy*(-(sz)))*(-(sx)))+(sy*cx) ]\r\n//\t[ ]\r\n//\t[ sz , cz*cx , cz*(-(sx)) ]\r\n//\t[ ]\r\n//\t[(-(sy))*cz,((-(sy))*(-(sz))*cx)+(cy*sx),(((-(sy))*(-(sz)))*(-(sx)))+(cy*cx)]\t\r\n\tpublic void set3DTransformRotationYZX(double x,double y,double z)\r\n\t{\r\n\t\tfloat sx=(float)Math.sin(x);\r\n\t\tfloat cx=(float)Math.cos(x);\r\n\t\tfloat sy=(float)Math.sin(y);\r\n\t\tfloat cy=(float)Math.cos(y);\r\n\t\tfloat sz=(float)Math.sin(z);\r\n\t\tfloat cz=(float)Math.cos(z);\r\n\r\n\t\tif(width==4)\r\n\t\t{\r\n\t\t\tvalue[4*0+0] = cy*cz;\r\n\t\t\tvalue[4*0+1] = (cy*(-(sz))*cx)+(sy*sx);\r\n\t\t\tvalue[4*0+2] = ((cy*(-(sz)))*(-(sx)))+(sy*cx);\r\n\t\r\n\t\t\tvalue[4*1+0] = sz;\r\n\t\t\tvalue[4*1+1] = cz*cx;\r\n\t\t\tvalue[4*1+2] = cz*(-(sx));\r\n\t\r\n\t\t\tvalue[4*2+0] = (-(sy))*cz;\r\n\t\t\tvalue[4*2+1] = ((-(sy))*(-(sz))*cx)+(cy*sx);\r\n\t\t\tvalue[4*2+2] = (((-(sy))*(-(sz)))*(-(sx)))+(cy*cx);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tvalue[3*0+0] = cy*cz;\r\n\t\t\tvalue[3*0+1] = (cy*(-(sz))*cx)+(sy*sx);\r\n\t\t\tvalue[3*0+2] = ((cy*(-(sz)))*(-(sx)))+(sy*cx);\r\n\t\r\n\t\t\tvalue[3*1+0] = sz;\r\n\t\t\tvalue[3*1+1] = cz*cx;\r\n\t\t\tvalue[3*1+2] = cz*(-(sx));\r\n\t\r\n\t\t\tvalue[3*2+0] = (-(sy))*cz;\r\n\t\t\tvalue[3*2+1] = ((-(sy))*(-(sz))*cx)+(cy*sx);\r\n\t\t\tvalue[3*2+2] = (((-(sy))*(-(sz)))*(-(sx)))+(cy*cx);\r\n\t\t}\r\n\t}\r\n\r\n\t///*\r\n\tpublic void set3DTransformRotationZXY(double x,double y,double z)\r\n\t{\r\n\t\tfloat sx=(float)Math.sin(x);\r\n\t\tfloat cx=(float)Math.cos(x);\r\n\t\tfloat sy=(float)Math.sin(y);\r\n\t\tfloat cy=(float)Math.cos(y);\r\n\t\tfloat sz=(float)Math.sin(z);\r\n\t\tfloat cz=(float)Math.cos(z);\r\n\r\n\t\tif(width==4)\r\n\t\t{\r\n\t\t\tvalue[4*0+0] = (cz*cx-sz*sy*sx);\r\n\t\t\tvalue[4*0+1] = -sx*cy;\r\n\t\t\tvalue[4*0+2] = (sz*cx+cz*sy*sx);\r\n\t\r\n\t\t\tvalue[4*1+0] = cx*sy*sz+sx*cz;\r\n\t\t\tvalue[4*1+1] = cx*cy;\r\n\t\t\tvalue[4*1+2] = sz*sx-cz*sy*cx;\r\n\t\r\n\t\t\tvalue[4*2+0] = -cy*sz;\r\n\t\t\tvalue[4*2+1] = sy;\r\n\t\t\tvalue[4*2+2] = cy*cz;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tvalue[3*0+0] = (cz*cx-sz*sy*sx);\r\n\t\t\tvalue[3*0+1] = -sx*cy;\r\n\t\t\tvalue[3*0+2] = (sz*cx+cz*sy*sx);\r\n\t\r\n\t\t\tvalue[3*1+0] = cx*sy*sz+sx*cz;\r\n\t\t\tvalue[3*1+1] = cx*cy;\r\n\t\t\tvalue[3*1+2] = sz*sx-cz*sy*cx;\r\n\t\r\n\t\t\tvalue[3*2+0] = -cy*sz;\r\n\t\t\tvalue[3*2+1] = sy;\r\n\t\t\tvalue[3*2+2] = cy*cz;\r\n//\t\t\tvalue[3*0+0] = (cz*cx-sz*sy*sx);\r\n//\t\t\tvalue[3*0+1] = -sz*cy;\r\n//\t\t\tvalue[3*0+2] = (sz*sx+cz*sy*cx);\r\n//\t\r\n//\t\t\tvalue[3*1+0] = cz*sy*sx+sz*cz;\r\n//\t\t\tvalue[3*1+1] = cz*cy;\r\n//\t\t\tvalue[3*1+2] = sz*sx-cz*sy*cx;\r\n//\t\r\n//\t\t\tvalue[3*2+0] = -cy*sx;\r\n//\t\t\tvalue[3*2+1] = sy;\r\n//\t\t\tvalue[3*2+2] = cy*cx;\r\n\t\t}\r\n\t}\r\n\r\n//\t[cz*cy,((-(sz))*cx)+(cz*sy*sx),((-(sz))*(-(sx)))+(cz*sy*cx)]\r\n//\t[ ]\r\n//\t[sz*cy, (cz*cx)+(sz*sy*sx) , (cz*(-(sx)))+(sz*sy*cx) ]\r\n//\t[ ]\r\n//\t[-(sy), cy*sx , cy*cx ]\r\n\tpublic void set3DTransformRotationZYX(double x,double y,double z)\r\n\t{\r\n\t\tfloat sx=(float)Math.sin(x);\r\n\t\tfloat cx=(float)Math.cos(x);\r\n\t\tfloat sy=(float)Math.sin(y);\r\n\t\tfloat cy=(float)Math.cos(y);\r\n\t\tfloat sz=(float)Math.sin(z);\r\n\t\tfloat cz=(float)Math.cos(z);\r\n\r\n\t\tif(width==4)\r\n\t\t{\r\n\t\t\tvalue[4*0+0] = cz*cy;\r\n\t\t\tvalue[4*0+1] = ((-(sz))*cx)+(cz*sy*sx);\r\n\t\t\tvalue[4*0+2] = ((-(sz))*(-(sx)))+(cz*sy*cx);\r\n\t\r\n\t\t\tvalue[4*1+0] = sz*cy;\r\n\t\t\tvalue[4*1+1] = (cz*cx)+(sz*sy*sx);\r\n\t\t\tvalue[4*1+2] = (cz*(-(sx)))+(sz*sy*cx);\r\n\t\r\n\t\t\tvalue[4*2+0] = -(sy);\r\n\t\t\tvalue[4*2+1] = cy*sx;\r\n\t\t\tvalue[4*2+2] = cy*cx;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tvalue[3*0+0] = cz*cy;\r\n\t\t\tvalue[3*0+1] = ((-(sz))*cx)+(cz*sy*sx);\r\n\t\t\tvalue[3*0+2] = ((-(sz))*(-(sx)))+(cz*sy*cx);\r\n\t\r\n\t\t\tvalue[3*1+0] = sz*cy;\r\n\t\t\tvalue[3*1+1] = (cz*cx)+(sz*sy*sx);\r\n\t\t\tvalue[3*1+2] = (cz*(-(sx)))+(sz*sy*cx);\r\n\t\r\n\t\t\tvalue[3*2+0] = -(sy);\r\n\t\t\tvalue[3*2+1] = cy*sx;\r\n\t\t\tvalue[3*2+2] = cy*cx;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic void set3DTransformRotationZXY_opengl(double x,double y,double z)\r\n\t{\r\n\t\tfloat sx=(float)Math.sin(x);\r\n\t\tfloat cx=(float)Math.cos(x);\r\n\t\tfloat sy=(float)Math.sin(y);\r\n\t\tfloat cy=(float)Math.cos(y);\r\n\t\tfloat sz=(float)Math.sin(z);\r\n\t\tfloat cz=(float)Math.cos(z);\r\n\r\n\t\tif(width==4)\r\n\t\t{\r\n\t\t\tvalue[4*0+0] = (cz*cx-sz*sy*sx);\r\n\t\t\tvalue[4*1+0] = -sx*cy;\r\n\t\t\tvalue[4*2+0] = (sz*cx+cz*sy*sx);\r\n\t\r\n\t\t\tvalue[4*0+1] = cx*sy*sz+sx*cz;\r\n\t\t\tvalue[4*1+1] = cx*cy;\r\n\t\t\tvalue[4*2+1] = sz*sx-cz*sy*cx;\r\n\t\r\n\t\t\tvalue[4*0+2] = -cy*sz;\r\n\t\t\tvalue[4*1+2] = sy;\r\n\t\t\tvalue[4*2+2] = cy*cz;\r\n\t\t}\r\n\t}\r\n\t//*/\r\n\tpublic void set3DTransformRotation_opengl(double x,double y,double z)\r\n\t{\r\n\t\tfloat sx=(float)Math.sin(x);\r\n\t\tfloat cx=(float)Math.cos(x);\r\n\t\tfloat sy=(float)Math.sin(y);\r\n\t\tfloat cy=(float)Math.cos(y);\r\n\t\tfloat sz=(float)Math.sin(z);\r\n\t\tfloat cz=(float)Math.cos(z);\r\n\r\n\t\tif(width==4)\r\n\t\t{\r\n\t\t\tvalue[4*0+0] = cz*cy;\r\n\t\t\tvalue[4*1+0] = (sy*sx*cz-cx*sz);\r\n\t\t\tvalue[4*2+0] = (sy*cx*cz+sz*sx);\r\n\t\r\n\t\t\tvalue[4*0+1] = sz*cy;\r\n\t\t\tvalue[4*1+1] = (sy*sx*sz+cx*cz);\r\n\t\t\tvalue[4*2+1] = (sy*cx*sz-cz*sx);\r\n\t\r\n\t\t\tvalue[4*0+2] = -sy;\r\n\t\t\tvalue[4*1+2] = cy*sx;\r\n\t\t\tvalue[4*2+2] = cy*cx;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic boolean isIdentity()\r\n\t{\r\n\t\tfloat maxdif = 0.000001f;\r\n\t\tint ind = 0;\r\n\t\tfor(int j=0;j<height;j++)\r\n\t\t{\r\n\t\t\tfor(int i=0;i<width;i++)\r\n\t\t\t{\r\n\t\t\t\tif(i==j)\r\n\t\t\t\t{\r\n\t\t\t\t\tif(Math.abs(value[ind]-1.0f)>maxdif)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\treturn false;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tif(Math.abs(value[ind]-0.0f)>maxdif)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\treturn false;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tind++;\r\n\t\t\t}\t\t\t\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\t\r\n\tpublic boolean orthonormalTransform()\r\n\t{\r\n\t\tint mw = width;\r\n\t\tfloat maxdif = 0.001f;\r\n\t\tfloat len;\r\n\t\tlen = value[mw*0+0]*value[mw*0+0]+value[mw*0+1]*value[mw*0+1]+value[mw*0+2]*value[mw*0+2];\r\n\t\tif(Math.abs(len-1.0f)>maxdif)\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tlen = value[mw*1+0]*value[mw*1+0]+value[mw*1+1]*value[mw*1+1]+value[mw*1+2]*value[mw*1+2];\r\n\t\tif(Math.abs(len-1.0f)>maxdif)\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tlen = value[mw*2+0]*value[mw*2+0]+value[mw*2+1]*value[mw*2+1]+value[mw*2+2]*value[mw*2+2];\r\n\t\tif(Math.abs(len-1.0f)>maxdif)\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\t\r\n\t\tfloat dot;\r\n\t\tdot = value[mw*0+0]*value[mw*1+0]+value[mw*0+1]*value[mw*1+1]+value[mw*0+2]*value[mw*1+2];\r\n\t\tif(Math.abs(dot)>maxdif)\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tdot = value[mw*0+0]*value[mw*2+0]+value[mw*0+1]*value[mw*2+1]+value[mw*0+2]*value[mw*2+2];\r\n\t\tif(Math.abs(dot)>maxdif)\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tdot = value[mw*1+0]*value[mw*2+0]+value[mw*1+1]*value[mw*2+1]+value[mw*1+2]*value[mw*2+2];\r\n\t\tif(Math.abs(dot)>maxdif)\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\t\r\n\t\treturn true;\r\n\t}\r\n\t\r\n\tpublic static final void getEulerZXY(GeneralMatrixFloat m, GeneralMatrixFloat euler) \r\n\t{\r\n//\t\tvalue[4*0+0] = (cz*cx-sz*sy*sx);\r\n//\t\tvalue[4*0+1] = -sx*cy;\r\n//\t\tvalue[4*0+2] = (sz*cx+cz*sy*sx);\r\n//\r\n//\t\tvalue[4*1+0] = cx*sy*sz+sx*cz;\r\n//\t\tvalue[4*1+1] = cx*cy;\r\n//\t\tvalue[4*1+2] = sz*sx-cz*sy*cx;\r\n//\r\n//\t\tvalue[4*2+0] = -cy*sz;\r\n//\t\tvalue[4*2+1] = sy;\r\n//\t\tvalue[4*2+2] = cy*cz;\r\n\r\n\t\tfinal int i=0;\r\n\t\tfinal int j=1;\r\n\t\tfinal int k=2;\r\n\r\n\t\tfinal int w=m.width;\r\n\t\t\r\n\t\tdouble cy = Math.sqrt(m.value[i*w+j]*m.value[i*w+j] + m.value[j*w+j]*m.value[j*w+j]);\r\n\t\tif (cy > 16*EPSILON) \r\n\t\t{\r\n\t\t euler.value[0] = (float)Math.atan2(-m.value[i*w+j], m.value[j*w+j]);\r\n\t\t euler.value[1] = (float)Math.atan2(m.value[k*w+j], cy);\r\n\t\t euler.value[2] = (float)Math.atan2(-m.value[k*w+i], m.value[k*w+k]);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t euler.value[0] = 0.0f;\r\n\t\t euler.value[1] = (float)Math.atan2(m.value[k*w+j], cy);\t\t\t\r\n\t\t euler.value[2] = (float)Math.atan2(m.value[i*w+k], m.value[i*w+i]);\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static final void getEulerYXZ(GeneralMatrixFloat m, GeneralMatrixFloat euler) \r\n\t{\r\n//\t\tvalue[4*0+0] = (cy*cz)+(sy*sx*sz);\r\n//\t\tvalue[4*0+1] = (cy*(-(sz)))+(sy*sx*cz);\r\n//\t\tvalue[4*0+2] = sy*cx;\r\n//\r\n//\t\tvalue[4*1+0] = cx*sz;\r\n//\t\tvalue[4*1+1] = cx*cz;\r\n//\t\tvalue[4*1+2] = -(sx);\r\n//\r\n//\t\tvalue[4*2+0] = ((-(sy))*cz)+(cy*sx*sz);\r\n//\t\tvalue[4*2+1] = ((-(sy))*(-(sz)))+(cy*sx*cz);\r\n//\t\tvalue[4*2+2] = cy*cx;\r\n\r\n\t\tfinal int i=0;\r\n\t\tfinal int j=1;\r\n\t\tfinal int k=2;\r\n\r\n\t\tfinal int w=m.width;\r\n\t\t\r\n\t\tdouble cx = Math.sqrt(m.value[j*w+i]*m.value[j*w+i] + m.value[j*w+j]*m.value[j*w+j]);\r\n\t\tif (cx > 16*EPSILON) {\r\n\t\t euler.value[0] = (float)Math.atan2(-m.value[j*w+k], cx);\r\n\t\t euler.value[1] = (float)Math.atan2(m.value[i*w+k], m.value[k*w+k]);\r\n\t\t euler.value[2] = (float)Math.atan2(m.value[j*w+i], m.value[j*w+j]);\r\n\t\t} else {\r\n\t\t\teuler.value[0] = (float)Math.atan2(-m.value[j*w+k], cx);\r\n\t\t euler.value[1] = 0;\r\n\t\t euler.value[2] = (float)Math.atan2(m.value[i*w+i], m.value[i*w+j]);\r\n\t\t}\r\n\t}\r\n\r\n\tpublic static final void getEuler(GeneralMatrixFloat m, GeneralMatrixFloat euler) \r\n\t{\r\n\t\tfinal int i=0;\r\n\t\tfinal int j=1;\r\n\t\tfinal int k=2;\r\n\r\n//\t\tvalue[4*0+0] = cz*cy;\r\n//\t\tvalue[4*0+1] = (sy*sx*cz-cx*sz);\r\n//\t\tvalue[4*0+2] = (sy*cx*cz+sz*sx);\r\n//\r\n//\t\tvalue[4*1+0] = sz*cy;\r\n//\t\tvalue[4*1+1] = (sy*sx*sz+cx*cz);\r\n//\t\tvalue[4*1+2] = (sy*cx*sz-cz*sx);\r\n//\r\n//\t\tvalue[4*2+0] = -sy;\r\n//\t\tvalue[4*2+1] = cy*sx;\r\n//\t\tvalue[4*2+2] = cy*cx;\r\n\t\t\r\n\t\tfinal int w=m.width;\r\n\r\n\t\tdouble cy = Math.sqrt(m.value[i*w+i]*m.value[i*w+i] + m.value[j*w+i]*m.value[j*w+i]);\r\n\t\tif (cy > 16*EPSILON) {\r\n\t\t euler.value[0] = (float)Math.atan2(m.value[k*w+j], m.value[k*w+k]);\r\n\t\t euler.value[1] = (float)Math.atan2(-m.value[k*w+i], cy);\r\n\t\t euler.value[2] = (float)Math.atan2(m.value[j*w+i], m.value[i*w+i]);\r\n\t\t} else {\r\n\t\t\t//pretty much pointing down x\r\n\t\t\tif(Math.abs(m.value[4*2+0]-(1.0f))<EPSILON)\r\n\t\t\t{\r\n\t\t\t\teuler.value[0] = 0.0f;\r\n\t\t\t\teuler.value[2] = 0.0f;\r\n\t\t\t\teuler.value[1] = (float)(Math.PI*0.5);\r\n//\t\t\t\tvalue[4*0+1] = (-sx*cz-cx*sz);\r\n//\t\t\t\tvalue[4*0+2] = (-cx*cz+sz*sx);\r\n//\t\t\t\tvalue[4*1+1] = (-sx*sz+cx*cz);\r\n//\t\t\t\tvalue[4*1+2] = (-cx*sz-cz*sx);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\tif(Math.abs(m.value[4*2+0]-(-1.0f))<EPSILON)\r\n\t\t\t{\r\n\t\t\t\teuler.value[0] = 0.0f;\r\n\t\t\t\teuler.value[2] = 0.0f;\r\n\t\t\t\teuler.value[1] = -(float)(Math.PI*0.5);\r\n//\t\t\t\tvalue[4*0+1] = (sx*cz-cx*sz);\r\n//\t\t\t\tvalue[4*0+2] = (cx*cz+sz*sx);\r\n//\t\t\t\tvalue[4*1+1] = (sx*sz+cx*cz);\r\n//\t\t\t\tvalue[4*1+2] = (cx*sz-cz*sx);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t euler.value[0] = (float)Math.atan2(-m.value[i*w+k], m.value[j*w+j]);\r\n\t\t\t euler.value[1] = (float)Math.atan2(-m.value[k*w+i], cy);\r\n\t\t\t euler.value[2] = 0;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tpublic static final void rowtransform(GeneralMatrixFloat a,GeneralMatrixFloat b,GeneralMatrixFloat c)\r\n\t{\r\n\t\t// wxh\r\n\t\t//a is 3xn (h value of 1.0 is implied)\r\n\t\t//B is 3x4 (or at least the other values are unused)\r\n\t\t//float vdot;\r\n\t\t for (int i = 0; i < a.height; i++)\r\n\t\t {\r\n\t\t\t //Apply the matrix to this vector\r\n\r\n\t\t\t //for (int j = 0; j < a.width; j++)\r\n\t\t\t //{\r\n\t\t\t int j = 0;\r\n\t\t\t\tfloat x = 0.0f;\r\n\t\t\t\tfor (int k = 0; k < a.width; k++)\r\n\t\t\t\t{\r\n\t\t\t\t\tx += a.value[i*a.width+k]*b.value[k*b.width+j];\r\n\t\t\t\t}\r\n\t\t\t\t x += b.value[a.width*b.width+j];\r\n\t\t\t\tj++;\r\n\t\t\t\tfloat y = 0.0f;\r\n\t\t\t\tfor (int k = 0; k < a.width; k++)\r\n\t\t\t\t{\r\n\t\t\t\t\ty += a.value[i*a.width+k]*b.value[k*b.width+j];\r\n\t\t\t\t}\r\n\t\t\t\t y += b.value[a.width*b.width+j];\r\n\t\t\t\tj++;\r\n\t\t\t\tfloat z = 0.0f;\r\n\t\t\t\tfor (int k = 0; k < a.width; k++)\r\n\t\t\t\t{\r\n\t\t\t\t\tz += a.value[i*a.width+k]*b.value[k*b.width+j];\r\n\t\t\t\t}\r\n\t\t\t\t z += b.value[a.width*b.width+j];\r\n\t\t\t\t //Add what would be the homogenious value to translate correctly\r\n\t\t\t //}\r\n\t\t\t \r\n\t\t\t c.value[i*a.width+0] = x;\r\n\t\t\t c.value[i*a.width+1] = y;\r\n\t\t\t c.value[i*a.width+2] = z;\r\n\t\t }\r\n\t}\r\n\tpublic float norm()\r\n\t{\r\n\t\tfloat total = 0.0f;\r\n\t\tfor (int i = 0; i < width*height; i++)\r\n\t\t{\r\n\t\t\ttotal += value[i]*value[i];\r\n\t\t}\r\n\t\ttotal = (float)Math.sqrt(total);\r\n\t\treturn total;\r\n\t}\r\n\t\r\n\tpublic static float sqrdist(GeneralMatrixFloat a,GeneralMatrixFloat b)\r\n\t{\r\n\t\tint s = a.width*b.width;\r\n\t\tfloat d = 0.0f;\r\n\t\tfor(int i=0;i<s;i++)\r\n\t\t{\r\n\t\t\tfloat dv = b.value[i]-a.value[i];\r\n\t\t\td += dv*dv;\r\n\t\t}\r\n\t\treturn d;//(float)Math.sqrt(d);\r\n\t}\r\n\r\n\tpublic static float rowdist(GeneralMatrixFloat a,int rowa,GeneralMatrixFloat b,int rowb)\r\n\t{\r\n\t\tint offa = rowa*a.width;\r\n\t\tint offb = rowb*b.width;\r\n\t\tfloat d = 0.0f;\r\n\t\tfor(int i=0;i<a.width;i++)\r\n\t\t{\r\n\t\t\tfloat dv = b.value[offb+i]-a.value[offa+i];\r\n\t\t\td += dv*dv;\r\n\t\t}\r\n\t\treturn (float)Math.sqrt(d);\r\n\t}\r\n\t\r\n\tpublic void normalise()\r\n\t{\r\n\t\tfloat total = 0.0f;\r\n\t\tfor (int i = 0; i < width*height; i++)\r\n\t\t{\r\n\t\t\ttotal += value[i]*value[i];\r\n\t\t}\r\n\t\tif(total<=EPSILON)\r\n\t\t{\r\n\t\t\tvalue[0] = 1.0f;\r\n\t\t\treturn;\r\n\t\t}\r\n\t\ttotal = (float)Math.sqrt(total);\r\n\t\tfor (int i = 0; i < width*height; i++)\r\n\t\t{\r\n\t\t\tvalue[i] /= total;\r\n\t\t}\r\n\t}\r\n\tpublic void normaliseRow(int row,float len)\r\n\t{\r\n\t\tint ind = row*width;\r\n\t\tfloat total = 0.0f;\r\n\t\tfor (int i = 0; i < width; i++)\r\n\t\t{\r\n\t\t\ttotal += value[i+ind]*value[i+ind];\r\n\t\t}\r\n\t\tif(total<=EPSILON)\r\n\t\t{\r\n\t\t\tvalue[0+ind] = 1.0f;\r\n\t\t\treturn;\r\n\t\t}\r\n\t\ttotal = (float)Math.sqrt(total)/len;\r\n\t\tfor (int i = 0; i < width; i++)\r\n\t\t{\r\n\t\t\tvalue[i+ind] /= total;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic void scale(float s)\r\n\t{\r\n\t\t for (int i = 0; i < width*height; i++)\r\n\t\t {\r\n\t\t\t value[i] = value[i]*s;\r\n\t\t }\r\n\t}\r\n\r\n\tpublic void setIdentity()\r\n\t{\r\n\t\tint i=0;\r\n\t\tfor(int y=0;y<height;y++)\r\n\t\t{\r\n\t\t\tfor(int x=0;x<width;x++)\r\n\t\t\t{\r\n\t\t\t\tif(x==y)\r\n\t\t\t\t\tvalue[i] = 1.0f;\r\n\t\t\t\telse\r\n\t\t\t\t\tvalue[i] = 0.0f;\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/*\r\n\tpublic static final boolean invert3x3(GeneralMatrixFloat a,GeneralMatrixFloat ia)\r\n\t{\r\n//\t\t| a11 a12 a13 |-1 | a33a22-a32a23 -(a33a12-a32a13) a23a12-a22a13 |\r\n//\t\t| a21 a22 a23 | = 1/DET * | -(a33a21-a31a23) a33a11-a31a13 -(a23a11-a21a13) |\r\n//\t\t| a31 a32 a33 | | a32a21-a31a22 -(a32a11-a31a12) a22a11-a21a12 |\r\n//\r\n//\t\twith DET = a11(a33a22-a32a23)-a21(a33a12-a32a13)+a31(a23a12-a22a13)\r\n\r\n//\t\tfloat det = a.value[0*3+0]*(a.value[0*3+0]*a.value[0*3+0]-a.value[0*3+0]*a.value[0*3+0]);\r\n//\t\tdet -= a.value[0*3+0]*(a.value[0*3+0]*a.value[0*3+0]-a.value[0*3+0]*a.value[0*3+0]);\r\n//\t\tdet += a.value[0*3+0]*(a.value[0*3+0]*a.value[0*3+0]-a.value[0*3+0]*a.value[0*3+0]);\r\n\t\tia.value[0*3+0] = (a.value[2*3+2]*a.value[1*3+1]-a.value[2*3+1]*a.value[1*3+2]);\r\n\t\tia.value[0*3+1] =-(a.value[2*3+2]*a.value[0*3+1]-a.value[2*3+1]*a.value[0*3+2]);\r\n\t\tia.value[0*3+2] = (a.value[1*3+2]*a.value[0*3+1]-a.value[1*3+1]*a.value[0*3+2]);\r\n\r\n\t\tia.value[1*3+0] = (a.value[2*3+2]*a.value[1*3+0]-a.value[2*3+0]*a.value[1*3+2]);\r\n\t\tia.value[1*3+1] = (a.value[2*3+2]*a.value[0*3+0]-a.value[2*3+0]*a.value[0*3+2]);\r\n\t\tia.value[1*3+2] =-(a.value[1*3+2]*a.value[0*3+0]-a.value[1*3+0]*a.value[0*3+2]);\r\n\r\n\t\tia.value[2*3+0] = (a.value[2*3+1]*a.value[1*3+0]-a.value[2*3+0]*a.value[1*3+1]);\r\n\t\tia.value[2*3+1] =-(a.value[2*3+1]*a.value[0*3+0]-a.value[2*3+0]*a.value[0*3+1]);\r\n\t\tia.value[2*3+2] = (a.value[1*3+1]*a.value[0*3+0]-a.value[1*3+0]*a.value[0*3+1]);\r\n\t\t\r\n\t\tfloat odet = GeneralMatrixFloat.determinant(a);\r\n\t\tfloat det = a.value[0*0+0]*ia.value[0*3+0]+a.value[1*0+0]*ia.value[0*3+1]+a.value[2*0+0]*ia.value[0*3+2];\r\n\t\tif(Math.abs(det)<EPSILON)\r\n\t\t{\r\n\t\t\tSystem.out.println(\"matrix invert failed\");\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tfloat idet = 1.0f/det;\r\n\t\tia.value[0] *= idet;\r\n\t\tia.value[1] *= idet;\r\n\t\tia.value[2] *= idet;\r\n\t\tia.value[3] *= idet;\r\n\t\tia.value[4] *= idet;\r\n\t\tia.value[5] *= idet;\r\n\t\tia.value[6] *= idet;\r\n\t\tia.value[7] *= idet;\r\n\t\tia.value[8] *= idet;\r\n\t\treturn true;\r\n\t}\r\n\t*/\r\n\t\r\n\tpublic static final void invertTransform(GeneralMatrixFloat cameraTransformMatrix,GeneralMatrixFloat modelMatrix)\r\n\t{\r\n\t\t//GeneralMatrixFloat.invert(cameraTransformMatrix,modelMatrix);\r\n\t\t//*\r\n\t\tmodelMatrix.value[0*4+0] = cameraTransformMatrix.value[0*4+0];\r\n\t\tmodelMatrix.value[1*4+0] = cameraTransformMatrix.value[0*4+1];\r\n\t\tmodelMatrix.value[2*4+0] = cameraTransformMatrix.value[0*4+2];\r\n\r\n\t\tmodelMatrix.value[0*4+1] = cameraTransformMatrix.value[1*4+0];\r\n\t\tmodelMatrix.value[1*4+1] = cameraTransformMatrix.value[1*4+1];\r\n\t\tmodelMatrix.value[2*4+1] = cameraTransformMatrix.value[1*4+2];\r\n\r\n\t\tmodelMatrix.value[0*4+2] = cameraTransformMatrix.value[2*4+0];\r\n\t\tmodelMatrix.value[1*4+2] = cameraTransformMatrix.value[2*4+1];\r\n\t\tmodelMatrix.value[2*4+2] = cameraTransformMatrix.value[2*4+2];\r\n\r\n\t\tfloat x = -cameraTransformMatrix.value[3*4+0];\r\n\t\tfloat y = -cameraTransformMatrix.value[3*4+1];\r\n\t\tfloat z = -cameraTransformMatrix.value[3*4+2];\r\n\t\t\r\n\t\t//needs to be rotated like the rest of the points in space\r\n\t\tfloat tx = modelMatrix.value[0*4+0]*x+modelMatrix.value[1*4+0]*y+modelMatrix.value[2*4+0]*z;\r\n\t\tfloat ty = modelMatrix.value[0*4+1]*x+modelMatrix.value[1*4+1]*y+modelMatrix.value[2*4+1]*z;\r\n\t\tfloat tz = modelMatrix.value[0*4+2]*x+modelMatrix.value[1*4+2]*y+modelMatrix.value[2*4+2]*z;\r\n\t\tmodelMatrix.value[3*4+0] = tx;\r\n\t\tmodelMatrix.value[3*4+1] = ty;\r\n\t\tmodelMatrix.value[3*4+2] = tz;\t\t\r\n\t\t//*/\r\n\t}\r\n\r\n\tpublic static final boolean invert(GeneralMatrixFloat a,GeneralMatrixFloat ia)\r\n\t{\r\n\t\tGeneralMatrixFloat temp = new GeneralMatrixFloat(a.width,a.height);\r\n\t\ttemp.set(a);\r\n\r\n\t\tia.setIdentity();\r\n\t\tint i,j,k,swap;\r\n\t\tfloat t;\r\n\t\tfor(i=0;i<a.width;i++)\r\n\t\t{\r\n\t\t\tswap = i;\r\n\t\t\tfor (j = i + 1; j < a.height; j++) {\r\n\t\t\t if (Math.abs(a.get(i, j)) > Math.abs(a.get(i, j)))\r\n\t\t\t {\r\n\t\t\t \tswap = j;\r\n\t\t\t }\r\n\t\t\t}\r\n\r\n\t\t\tif (swap != i)\r\n\t\t\t{\r\n\t\t\t /*\r\n\t\t\t ** Swap rows.\r\n\t\t\t */\r\n\t\t\t for (k = 0; k < a.width; k++)\r\n\t\t\t {\r\n\t\t\t\t\tt = temp.get(k,i);\r\n\t\t\t\t\ttemp.set(k,i,temp.get(k, swap));\r\n\t\t\t\t\ttemp.set(k, swap,t);\r\n\r\n\t\t\t\t\tt = ia.get(k,i);\r\n\t\t\t\t\tia.set(k,i,ia.get(k, swap));\r\n\t\t\t\t\tia.set(k, swap,t);\r\n\t\t\t }\r\n\t\t\t}\r\n\r\n\t\t\tt = temp.get(i,i);\r\n\t\t\tif (t == 0.0f)\r\n\t\t\t{\r\n\t\t\t /*\r\n\t\t\t ** No non-zero pivot. The matrix is singular, which shouldn't\r\n\t\t\t ** happen. This means the user gave us a bad matrix.\r\n\t\t\t */\r\n\t\t\t\tSystem.out.println(\"inverse failed\");\r\n\t\t\t return false;\r\n\t\t\t}\r\n\r\n\t\t\tfor (k = 0; k < a.width; k++)\r\n\t\t\t{\r\n\t\t\t\ttemp.set(k,i,temp.get(k,i) / t);\r\n\t\t\t\tia.set(k,i,ia.get(k,i) / t);\r\n\t\t\t}\r\n\t\t\tfor (j = 0; j < a.width; j++)\r\n\t\t\t{\r\n\t\t\t if (j != i)\r\n\t\t\t {\r\n\t\t\t \tt = temp.get(i,j);\r\n\t\t\t \tfor (k = 0; k < a.width; k++)\r\n\t\t\t \t{\r\n\t\t\t \t\ttemp.set(k,j, temp.get(k,j) - temp.get(k,i)*t);\r\n\t\t\t \t\tia.set(k,j, ia.get(k,j) - ia.get(k,i)*t);\r\n\t\t\t \t}\r\n\t\t\t }\r\n\t\t\t}\r\n\t }\r\n\t return true;\r\n\t}\r\n\r\n\tpublic static final float dotProduct(GeneralMatrixFloat a,int arow,GeneralMatrixFloat b,int brow)\r\n\t{\r\n\t\tint aind = arow*a.width;\r\n\t\tint bind = brow*b.width;\r\n\t\tfloat result = 0.0f;\r\n\t\tfor(int i=0;i<a.width;i++)\r\n\t\t{\r\n\t\t\tresult += a.value[aind]*b.value[bind];\r\n\t\t\taind++;\r\n\t\t\tbind++;\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\t\r\n\tpublic static final float dotProduct3(GeneralMatrixFloat a,GeneralMatrixFloat b)\r\n\t{\r\n\t\treturn a.value[0]*b.value[0]+a.value[1]*b.value[1]+a.value[2]*b.value[2];\r\n\t}\r\n\t\r\n\tpublic static final void crossProduct3(GeneralMatrixFloat a,GeneralMatrixFloat b,GeneralMatrixFloat c)\r\n\t{\r\n\t\tc.value[0] = a.value[1]*b.value[2]-b.value[1]*a.value[2];\r\n\t\tc.value[1] = a.value[2]*b.value[0]-b.value[2]*a.value[0];\r\n\t\tc.value[2] = a.value[0]*b.value[1]-b.value[0]*a.value[1];\r\n\t}\r\n\r\n\tpublic static final void multInPlace(GeneralMatrixFloat a,GeneralMatrixFloat b)\r\n\t{\r\n\t\tGeneralMatrixFloat c = new GeneralMatrixFloat(a.width,1);\r\n\r\n\t\tint n = a.height;\r\n\t\tint p = a.width;\r\n\t\tint r = b.width;\r\n\r\n\t\tif(a.width!=b.height)\r\n\t\t{\r\n\t\t\tSystem.out.println(\"Mult error, matricies sizes dont match\");\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t float vdot;\r\n\t int i,j,k,m;\r\n\r\n\r\n int r5 = r*5;\r\n\t int rowI = 0;\r\n\t int crowI = 0;\r\n\t for (i = 0; i < n; i++) {\r\n\r\n\t for (j = 0; j < r; j++) {\r\n\r\n\t vdot = 0.0f;\r\n\r\n\t m = p%5;\r\n\r\n\t int rowK = 0;\r\n\t for (k = 0; k < m; k++) {\r\n\r\n\t vdot += a.value[rowI+k]*b.value[rowK+j];\r\n\t rowK += r;\r\n\t }\r\n\r\n\t for (k = m; k < p; k += 5) {\r\n\r\n\t vdot += a.value[rowI+k]*b.value[rowK+j] +\r\n\t a.value[rowI+k+1]*b.value[rowK+r+j] +\r\n\t a.value[rowI+k+2]*b.value[rowK+r*2+j] +\r\n\t a.value[rowI+k+3]*b.value[rowK+r*3+j] +\r\n\t a.value[rowI+k+4]*b.value[rowK+r*4+j];\r\n\r\n\t rowK += r5;\r\n\t }\r\n\r\n\t c.value[j] = vdot;\r\n\r\n\t }\r\n\t //now overright the a rowI\r\n\t for (j = 0; j < r; j++) \r\n\t {\r\n\t \t a.value[rowI+j] = c.value[j];\r\n\t }\r\n\t rowI += p;\r\n\t crowI += r;\r\n\t }\r\n\t}\r\n\t\r\n\tpublic static final void mult(GeneralMatrixFloat a,GeneralMatrixFloat b,GeneralMatrixFloat c)\r\n\t{\r\n\t\tint n = a.height;\r\n\t\tint p = a.width;\r\n\t\tint r = b.width;\r\n\r\n\t\tif(a.width!=b.height)\r\n\t\t{\r\n\t\t\tSystem.out.println(\"Mult error, matricies sizes dont match\");\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t float vdot;\r\n\t int i,j,k,m;\r\n\r\n\r\n int r5 = r*5;\r\n\t int rowI = 0;\r\n\t int crowI = 0;\r\n\t for (i = 0; i < n; i++) {\r\n\r\n\t for (j = 0; j < r; j++) {\r\n\r\n\t vdot = 0.0f;\r\n\r\n\t m = p%5;\r\n\r\n\t int rowK = 0;\r\n\t for (k = 0; k < m; k++) {\r\n\r\n\t vdot += a.value[rowI+k]*b.value[rowK+j];\r\n\t rowK += r;\r\n\t }\r\n\r\n\t for (k = m; k < p; k += 5) {\r\n\r\n\t vdot += a.value[rowI+k]*b.value[rowK+j] +\r\n\t a.value[rowI+k+1]*b.value[rowK+r+j] +\r\n\t a.value[rowI+k+2]*b.value[rowK+r*2+j] +\r\n\t a.value[rowI+k+3]*b.value[rowK+r*3+j] +\r\n\t a.value[rowI+k+4]*b.value[rowK+r*4+j];\r\n\r\n\t rowK += r5;\r\n\t }\r\n\r\n\t c.value[crowI+j] = vdot;\r\n\r\n\t }\r\n\t rowI += p;\r\n\t crowI += r;\r\n\t }\r\n\r\n\t}\r\n\r\n\tpublic static final void add(GeneralMatrixFloat a,GeneralMatrixFloat b,GeneralMatrixFloat c)\r\n\t{\r\n\t\t for (int i = 0; i < a.width*a.height; i++)\r\n\t\t {\r\n\t\t\t c.value[i] = a.value[i]+b.value[i];\r\n\t\t }\r\n\t}\r\n\tpublic static final void add(GeneralMatrixFloat a,int arow,GeneralMatrixFloat b,int brow,GeneralMatrixFloat c,int crow)\r\n\t{\r\n\t\tint aoff = a.width*arow;\r\n\t\tint boff = b.width*brow;\r\n\t\tint coff = c.width*crow;\r\n\t\t for (int i = 0; i < a.width; i++)\r\n\t\t {\r\n\t\t\t c.value[coff+i] = a.value[aoff+i]+b.value[boff+i];\r\n\t\t }\r\n\t}\r\n\tpublic static final void addsqa(GeneralMatrixFloat a,GeneralMatrixFloat b,GeneralMatrixFloat c)\r\n\t{\r\n\t\t for (int i = 0; i < a.width*a.height; i++)\r\n\t\t {\r\n\t\t\t c.value[i] = a.value[i]*a.value[i]+b.value[i];\r\n\t\t }\r\n\t}\r\n\r\n\tpublic static final void transpose(GeneralMatrixFloat a,GeneralMatrixFloat at)\r\n\t{\r\n\t\tint i,j;\r\n\r\n\t\tint ai = 0;\r\n\t\tint atjR;\r\n\t for (i = 0; i < a.height; i++) {\r\n\r\n\t \t\tatjR = 0;\r\n\t for (j = 0; j < a.width; j++) {\r\n\r\n\t at.value[atjR+i] = a.value[ai];\r\n\t ai++;\r\n\t atjR += a.height;\r\n\t }\r\n\r\n\t }\r\n\t}\r\n\r\n\tpublic final float trace()\r\n\t{\r\n\t\tfloat sum = 0.0f;\r\n\t\tint index = 0;\r\n\t\tfor (int i = 0; i < height; i++)\r\n\t\t{\r\n\t\t\tsum += value[index];\r\n\t\t\tindex += height+1;\r\n\t\t}\r\n\t\treturn sum;\r\n\t}\r\n\r\n\tpublic static float determinant(GeneralMatrixFloat m)\r\n\t{\r\n\t\tint n = m.width; \r\n\t\tif(n==1)\r\n\t\t\treturn m.value[0];\r\n\t\telse\r\n\t\tif(n==2)\r\n\t\t{\r\n\t\t\treturn m.value[0*2+0] * m.value[1*2+1] - m.value[1*2+0] * m.value[0*2+1];\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tfloat det = 0.0f;\r\n\t\t\tfor (int j1=0;j1<n;j1++) \r\n\t\t\t{\r\n\t\t if(m.value[0*n+j1]==0.0f)\r\n\t\t \t continue;\r\n\r\n\t\t GeneralMatrixFloat subm = new GeneralMatrixFloat(n-1,n-1);\r\n\r\n\t\t for (int i=1;i<n;i++) \r\n\t\t {\r\n\t\t int j2 = 0;\r\n\t\t for (int j=0;j<n;j++) \r\n\t\t {\r\n\t\t if (j == j1)\r\n\t\t continue;\r\n\t\t subm.value[(i-1)*(n-1)+j2] = m.value[i*n+j];\r\n\t\t j2++;\r\n\t\t }\r\n\t\t }\r\n\t\t int ind = 1+j1+1;\r\n\t\t \r\n\t\t if((ind%2)==0)\r\n\t\t \t det += m.value[0*n+j1] * determinant(subm);\r\n\t\t else\r\n\t\t \t det -= m.value[0*n+j1] * determinant(subm);\r\n\t\t\t}\r\n\t\t\treturn det;\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static final void sub(GeneralMatrixFloat a,GeneralMatrixFloat b,GeneralMatrixFloat c)\r\n\t{\r\n\t\t for (int i = 0; i < a.width*a.height; i++)\r\n\t\t {\r\n\t\t\t c.value[i] = a.value[i]-b.value[i];\r\n\t\t }\r\n\t}\r\n\tpublic static final void sub(GeneralMatrixFloat a,int arow,GeneralMatrixFloat b,int brow,GeneralMatrixFloat c,int crow)\r\n\t{\r\n\t\tint aoff = a.width*arow;\r\n\t\tint boff = b.width*brow;\r\n\t\tint coff = c.width*crow;\r\n\t\t for (int i = 0; i < a.width; i++)\r\n\t\t {\r\n\t\t\t c.value[coff+i] = a.value[aoff+i]-b.value[boff+i];\r\n\t\t }\r\n\t}\r\n\tpublic static final void subsqb(GeneralMatrixFloat a,GeneralMatrixFloat b,GeneralMatrixFloat c)\r\n\t{\r\n\t\t for (int i = 0; i < a.width*a.height; i++)\r\n\t\t {\r\n\t\t\t c.value[i] = a.value[i]-b.value[i]*b.value[i];\r\n\t\t }\r\n\t}\r\n\r\n\tpublic static final void rowsub(GeneralMatrixFloat a,GeneralMatrixFloat b,GeneralMatrixFloat c)\r\n\t{\r\n\t\tint ai = 0;\r\n\t\t for (int i = 0; i < a.height; i++)\r\n\t\t {\r\n\t\t\t for (int j = 0; j < a.width; j++)\r\n\t\t\t {\r\n\t\t\t\t c.value[ai] = a.value[ai]-b.value[j];\r\n\t\t\t\t ai++;\r\n\t\t\t }\r\n\t\t }\r\n\t}\r\n\r\n\tpublic static final void setRow(int row,GeneralMatrixFloat a,GeneralMatrixFloat target)\r\n\t{\r\n\t\tint ind = row*a.width;\r\n\t\tfor(int i=0;i<a.width;i++)\r\n\t\t{\r\n\t\t\ttarget.value[ind+i] = a.value[ind+i];\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static final void blendRow(int row,float mag0,float mag1,GeneralMatrixFloat a,GeneralMatrixFloat b,GeneralMatrixFloat target)\r\n\t{\r\n\t\tint ind = row*a.width;\r\n\t\tfor(int i=0;i<a.width;i++)\r\n\t\t{\r\n\t\t\ttarget.value[ind+i] = a.value[ind+i]*mag0+b.value[ind+i]*mag1;\r\n\t\t}\r\n\t}\r\n\t\r\n//\tpublic static final void blendRotations(GeneralMatrixFloat a,GeneralMatrixFloat b,float f,GeneralMatrixFloat c)\r\n//\t{\r\n//\t\tfloat[] qa = new float[4];\r\n//\t\tfloat[] qb = new float[4];\r\n//\t\tfloat[] qc = new float[4];\r\n//\t\t\r\n//\t\tQuaternion.MatrixtoQuaternion(a.value, qa);\r\n//\t\tQuaternion.MatrixtoQuaternion(b.value, qb);\r\n//\t\tQuaternion.slerp(qa, qb, f, qc);\r\n//\t\tQuaternion.QuaterniontoMatrix(qc, c.value);\r\n//\t}\r\n}\r", "public class GeneralMatrixInt implements Serializable \r\n{\r\n\tprivate static final long serialVersionUID = 1L;\r\n\r\n\tpublic int width=0; //columns\r\n\tpublic int height=0; //rows\r\n\tpublic int[] value=null; //array of values\r\n\r\n\tpublic GeneralMatrixInt()\r\n\t{\r\n\t\twidth = 0;\r\n\t\theight = 0;\r\n\t}\t\r\n\tpublic GeneralMatrixInt(int val0,int val1,int val2,int val3)\r\n\t{\r\n\t\tthis.width = 1;\r\n\t\tthis.height = 4;\r\n\t\tthis.value = new int[4];\r\n\t\tthis.value[0] = val0;\r\n\t\tthis.value[1] = val1;\r\n\t\tthis.value[2] = val2;\r\n\t\tthis.value[3] = val3;\r\n\t}\r\n\r\n\tpublic GeneralMatrixInt(int[] vals)\r\n\t{\r\n\t\tthis.width = vals.length;\r\n\t\tthis.height = 1;\r\n\t\tthis.value = vals;\r\n\t}\r\n\tpublic GeneralMatrixInt(int[] vals,int h)\r\n\t{\r\n\t\tthis.width = 1;\r\n\t\tthis.height = h;\r\n\t\tthis.value = vals;\r\n\t}\r\n\tpublic GeneralMatrixInt(int width)\r\n\t{\r\n\t\tthis.width = width;\r\n\t}\r\n\tpublic GeneralMatrixInt(int width,int height)\r\n\t{\r\n\t\tthis.width = width;\r\n\t\tthis.height = height;\r\n\t\tvalue = new int[width*height];\r\n\t}\r\n\tpublic GeneralMatrixInt(int width,int height,int[] vals)\r\n\t{\r\n\t\tthis.width = width;\r\n\t\tthis.height = height;\r\n\t\tthis.value = vals;\r\n\t}\r\n\tpublic GeneralMatrixInt(int width,int height,int val)\r\n\t{\r\n\t\tthis.width = width;\r\n\t\tthis.height = height;\r\n\t\tthis.value = new int[width*height];\r\n\t\tfor(int i=0;i<value.length;i++)\r\n\t\t\tvalue[i] = val;\r\n\t}\r\n\tpublic GeneralMatrixInt(GeneralMatrixInt o)\r\n\t{\r\n\t\tthis.width = o.width;\r\n\t\tthis.height = o.height;\r\n\t\tvalue = new int[width*height];\r\n\t\tset(o);\r\n\t}\r\n\r\n\t public boolean isequal(GeneralMatrixInt m)\r\n\t {\r\n\t\t if(width!=m.width)\r\n\t\t\t return false;\r\n\t\t if(height!=m.height)\r\n\t\t\t return false;\r\n\t\t for (int i = 0; i < width*height; i++) \r\n\t\t {\r\n\t\t\t if(value[i]!=m.value[i])\r\n\t\t\t\t return false;\r\n\t\t }\t\t \r\n\t\t return true;\r\n\t }\r\n\r\n\t public boolean isequal(int[] m)\r\n\t {\r\n\t\t if(width!=1)\r\n\t\t\t return false;\r\n\t\t if(height!=m.length)\r\n\t\t\t return false;\r\n\t\t for (int i = 0; i < width*height; i++) \r\n\t\t {\r\n\t\t\t if(value[i]!=m[i])\r\n\t\t\t\t return false;\r\n\t\t }\t\t \r\n\t\t return true;\r\n\t }\r\n//\tpublic boolean isequal(GeneralMatrixInt o)\r\n//\t{\r\n//\t\tboolean is = true;\r\n//\t\tis = is && (width==o.width);\r\n//\t\tis = is && (height==o.height);\r\n//\t\tif(is)\r\n//\t\t{\r\n//\t\t\tfor(int i=0;i<width*height;i++)\r\n//\t\t\t{\r\n//\t\t\t\tis = is && (value[i]==o.value[i]);\r\n//\t\t\t}\r\n//\t\t}\r\n//\t\tif(!is)\r\n//\t\t\tSystem.out.println(\"diff!\");\r\n//\t\treturn is;\r\n//\t}\r\n\t\r\n\t\tpublic void enumerate()\r\n\t\t{\r\n\t\t\tfor (int i = 0; i < width*height; i++)\r\n\t\t\t{\r\n\t\t\t\tvalue[i] = i;\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tpublic void enumerate(int from)\r\n\t\t{\r\n\t\t\tfor (int i = 0; i < width*height; i++)\r\n\t\t\t{\r\n\t\t\t\tvalue[i] = i+from;\r\n\t\t\t}\r\n\t\t}\r\n\t\tpublic void denumerate(int from)\r\n\t\t{\t\t\t\r\n\t\t\tfor (int i = 0; i < width*height; i++)\r\n\t\t\t{\r\n\t\t\t\tint v = (width*height-1)-i;\r\n\t\t\t\tvalue[i] = i+from;\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\tpublic void clear(int v)\r\n\t{\r\n\t\tfor (int i = 0; i < width*height; i++)\r\n\t\t{\r\n\t\t\tvalue[i] = v;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic final int get(int i,int j)\r\n\t{\r\n\t\treturn value[j*width+i];\r\n\t}\r\n\tpublic void set(int i,int j,int v)\r\n\t{\r\n\t\tvalue[j*width+i] = v;\r\n\t}\r\n\tpublic void set(final GeneralMatrixInt rb)\r\n\t{\r\n\t\tsetDimensionsNoCopy(rb.width, rb.height);\r\n\t\tint s = width*height;\r\n\t\tif(s>0)\r\n\t\t\tSystem.arraycopy(rb.value,0,value,0,s);\r\n\t}\r\n\tpublic void setInto(final GeneralMatrixInt rb)\r\n\t{\r\n\t\tif(\r\n\t\t\t\t(rb.width==0)||(rb.height==0)\r\n\t\t )\r\n\t\t{\r\n\t\t}\r\n\t\telse\r\n\t\tif(\r\n\t\t\t\t(rb.width==width)&&\r\n\t\t\t\t(rb.height==height)\r\n\t\t )\r\n\t\t{\r\n\t\t\tSystem.arraycopy(rb.value,0,value,0,width*height);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tfinal int minHeight = Math.min(rb.height, height);\r\n\t\t\tfinal int minWidth = Math.min(rb.width, width);\r\n\t\t\tfor(int y=0;y<minHeight;y++)\r\n\t\t\t{\r\n\t\t\t\tSystem.arraycopy(rb.value,y*rb.width,value,y*width,minWidth);\t\t\t\t\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tpublic void set(final int[] vals)\r\n\t{\r\n\t\tSystem.arraycopy(vals, 0, value, 0, width*height);\r\n\t}\r\n\t public boolean equals(GeneralMatrixInt m)\r\n\t {\r\n\t\t if(width!=m.width)\r\n\t\t\t return false;\r\n\t\t if(height!=m.height)\r\n\t\t\t return false;\r\n\t\t for (int i = 0; i < width*height; i++) \r\n\t\t {\r\n\t\t\t if(value[i]!=m.value[i])\r\n\t\t\t\t return false;\r\n\t\t }\t\t \r\n\t\t return true;\r\n\t }\r\n\t \r\n\t public boolean contains(int v)\r\n\t {\r\n\t\t for(int i=(width*height-1);i>=0;i--)\r\n\t\t {\r\n\t\t\t if(value[i]==v)\r\n\t\t\t\t return true;\r\n\t\t }\r\n\t\t return false;\r\n\t }\r\n\t \r\n\t public int find(int[] v)\r\n\t {\r\n\t\t int ind = 0;\r\n\t\t for(int j=0;j<(height);j++)\r\n\t\t {\r\n\t\t\t boolean found = true;\r\n\t\t\t for(int i=0;i<(width);i++)\r\n\t\t\t {\r\n\t\t\t\t if(value[ind+i]!=v[i])\r\n\t\t\t\t {\r\n\t\t\t\t\t found = false;\r\n\t\t\t\t\t break;\r\n\t\t\t\t }\r\n\t\t\t }\r\n\t\t\t if(found)\r\n\t\t\t\t return j;\r\n\t\t\t ind+=width;\r\n\t\t }\r\n\t\t return -1;\r\n\t }\r\n\t public int find(int v)\r\n\t {\r\n\t\t for(int i=0;i<(width*height);i++)\r\n\t\t {\r\n\t\t\t if(value[i]==v)\r\n\t\t\t\t return i;\r\n\t\t }\r\n\t\t return -1;\r\n\t }\r\n\t public int find(int v0,int v1)\r\n\t {\r\n\t\t for(int i=0;i<(width*height);i+=2)\r\n\t\t {\r\n\t\t\t if((value[i]==v0)&&(value[i+1]==v1))\r\n\t\t\t\t return i/2;\r\n\t\t }\r\n\t\t return -1;\r\n\t }\r\n\r\n\t public int find_thresh(int v0,int v1,int t)\r\n\t {\r\n\t\t for(int i=0;i<(width*height);i+=2)\r\n\t\t {\r\n\t\t\t if((Math.abs(value[i]-v0)<=t)&&(Math.abs(value[i+1]-v1)<=t))\r\n\t\t\t\t return i/2;\r\n\t\t }\r\n\t\t return -1;\r\n\t }\r\n\r\n\t public int find(int v0,int v1,int v2,int v3)\r\n\t {\r\n\t\t for(int i=0;i<(width*height);i+=4)\r\n\t\t {\r\n\t\t\t if((value[i]==v0)&&(value[i+1]==v1)&&(value[i+2]==v2)&&(value[i+3]==v3))\r\n\t\t\t\t return i/4;\r\n\t\t }\r\n\t\t return -1;\r\n\t }\r\n\t \r\n\t public int findincolumn(int c,int v)\r\n\t {\r\n\t\t for(int i=0;i<(height);i++)\r\n\t\t {\r\n\t\t\t if(value[width*i+c]==v)\r\n\t\t\t\t return i;\r\n\t\t }\r\n\t\t return -1;\r\n\t }\r\n\t public int findinrow(int v,int row)\r\n\t {\r\n\t\t for(int i=width*row;i<(width*(row+1));i++)\r\n\t\t {\r\n\t\t\t if(value[i]==v)\r\n\t\t\t\t return i;\r\n\t\t }\r\n\t\t return -1;\r\n\t }\r\n\t \r\n\t\t//Insertion and deletion\r\n\t public int appendRow()\r\n\t {\r\n\t \tint newSize = width*(height+1);\r\n\t \tif(value==null)\r\n\t \t{\r\n\t \t\tvalue = new int[newSize];\r\n\t\t\t\theight++;\r\n\t\t\t\treturn height-1;\r\n\t \t}\r\n\t \tif(newSize>value.length)\r\n\t \t{\r\n\t \t\tensureCapacity(newSize);\r\n\t \t}\r\n\t\t\theight++;\r\n\t\t\treturn height-1;\r\n\t }\r\n\r\n\t public int appendRows(int size)\r\n\t {\r\n\t \tint newSize = width*(height+size);\r\n\t \tif(value==null)\r\n\t \t{\r\n\t \t\tvalue = new int[newSize];\r\n\t\t\t\theight+=size;\r\n\t\t\t\treturn height-size;\r\n\t \t}\r\n\t \tif(newSize>value.length)\r\n\t \t{\r\n\t \t\tensureCapacity(newSize);\r\n\t \t}\r\n\t\t\theight+=size;\r\n\t\t\treturn height-size;\r\n\t }\r\n\t \r\n\t public int appendRows(int size,int defaultValue)\r\n\t {\r\n\t \tint newSize = width*(height+size);\r\n\t \tif(value==null)\r\n\t \t{\r\n\t \t\tvalue = new int[newSize];\r\n\t\t\t\theight+=size;\r\n\t\t\t\tclear(defaultValue);\r\n\t\t\t\treturn height-size;\r\n\t \t}\r\n\t \tif(newSize>value.length)\r\n\t \t{\r\n\t \t\tensureCapacity(newSize);\r\n\t \t}\r\n\t\t\tfor(int i=width*height;i<(width*(height+size));i++)\r\n\t\t\t{\r\n\t\t\t\tvalue[i] = defaultValue;\r\n\t\t\t}\r\n\t\t\theight+=size;\r\n\t\t\treturn height-size;\r\n\t }\r\n\t \r\n\t public void removeRow(int index)\r\n\t {\r\n\t \tif(index>=height)\r\n\t \t{\r\n\t \t\tSystem.out.println(\"Row being removed larger than matrix\");\r\n\t \t}\r\n\t \tfor(int i=index*width;i<((height-1))*width;i++)\r\n\t \t{\r\n\t \t\tvalue[i] = value[(i+width)];\r\n\t \t}\r\n\t \theight--;\r\n\t }\r\n\t public void removeRows(int index,int size)\r\n\t {\r\n\t \tfor(int i=index*width;i<((height-size))*width;i++)\r\n\t \t{\r\n\t \t\tvalue[i] = value[i+width*size];\r\n\t \t}\r\n\t \theight-=size;\r\n\t }\r\n\r\n\t public void insertRowAfter(int index)\r\n\t {\r\n\t \tappendRow();\r\n\t \tSystem.arraycopy(value, (index+1)*width, value, (index+2)*width, (height-1-(index+1))*width);\r\n\t }\r\n\r\n\t public void insertRowBefore(int index)\r\n\t {\r\n\t \tint srcind = (index)*width;\r\n\t \tint destind = (index+1)*width;\r\n\t \tint length = (height-(index))*width;\r\n\t \ttry{\r\n\t\t \tappendRow();\r\n\t\t \tSystem.arraycopy(value, srcind, value, destind, length);\t \t\t\r\n\t \t}\r\n\t \tcatch(Exception e)\r\n\t \t{\r\n\t \t\tSystem.out.println(\"insertRowBefore error\");\r\n\t \t}\r\n\t }\r\n\t \r\n\t public void insertRowsBefore(int index,GeneralMatrixInt rows)\r\n\t {\r\n\t \tint srcind = (index)*width;\r\n\t \tint destind = (index+rows.height)*width;\r\n\t \tint length = (height-(index))*width;\r\n\t \ttry{\r\n\t\t \tappendRows(rows.height);\r\n\t\t \tSystem.arraycopy(value, srcind, value, destind, length);\t \t\t\r\n\t\t \tSystem.arraycopy(rows.value, 0, value, srcind, rows.width*rows.height);\t \t\t\r\n\t \t}\r\n\t \tcatch(Exception e)\r\n\t \t{\r\n\t \t\tSystem.out.println(\"insertRowBefore error\");\r\n\t \t}\r\n\t }\r\n\t \r\n\t public void ensureCapacityNoCopy(int mincap)\r\n\t {\r\n\t \tif(value==null)\r\n\t \t{\r\n\t \t\tvalue = new int[mincap];\r\n\t \t}\r\n\t \telse\r\n\t \tif(mincap>value.length)\r\n\t \t{\r\n\t\t int newcap = (value.length * 3)/2 + 1;\r\n\t\t //int[] olddata = value;\r\n\t\t value = new int[newcap < mincap ? mincap : newcap];\r\n\t \t}\r\n\t }\r\n\r\n\t public void ensureCapacity(int mincap)\r\n\t {\r\n\t \tif(value==null)\r\n\t \t{\r\n\t \t\tvalue = new int[mincap];\r\n\t \t}\r\n\t \telse\r\n\t \tif(mincap>value.length)\r\n\t \t{\r\n\t\t int newcap = (value.length * 3)/2 + 1;\r\n\t\t \tif(newcap>100000000)\r\n\t\t \t{\r\n\t\t \t\tnewcap = mincap+1000000;\r\n\t\t \t}\r\n\t\t int[] olddata = value;\r\n\t\t value = new int[newcap < mincap ? mincap : newcap];\r\n\t\t System.arraycopy(olddata,0,value,0,olddata.length);\r\n\t \t}\r\n\t }\r\n\t \r\n\t public void setDimensions(int w,int h)\r\n\t {\r\n\t \tensureCapacity(w*h);\r\n\t \twidth = w;\r\n\t \theight = h;\r\n\t }\r\n\t public void setDimensionsAndClearNew(int w,int h,int init)\r\n\t {\r\n\t \tint oldl = width*height;\r\n\t \tensureCapacity(w*h);\r\n\t \twidth = w;\r\n\t \theight = h;\r\n\t \tint newl = w*h;\r\n\t \tfor(int i=oldl;i<newl;i++)\r\n\t \t{\r\n\t \t\tvalue[i] = init;\r\n\t \t}\r\n\t }\r\n\t public void setDimensionsNoCopy(int w,int h)\r\n\t {\r\n\t \tensureCapacityNoCopy(w*h);\r\n\t \twidth = w;\r\n\t \theight = h;\r\n\t }\r\n\t public void setDimensionsExact(int w,int h)\r\n\t {\r\n\t \tint[] oldv = value;\r\n\t \tvalue = new int[w*h];\r\n\t \tint min = value.length;\r\n\t \tif(oldv.length<min)\r\n\t \t\tmin = oldv.length;\r\n\t \tSystem.arraycopy(oldv, 0, value, 0, min);\r\n\t \twidth = w;\r\n\t \theight = h;\r\n\t }\r\n\t public void setDimensionsExactNoCopy(int w,int h)\r\n\t {\r\n\t \tvalue = new int[w*h];\r\n\t \twidth = w;\r\n\t \theight = h;\r\n\t }\r\n\t public int pop_back()\r\n\t {\r\n\t \theight--;\r\n\t \treturn value[height];\r\n\t }\r\n\t public int push_back(int val)\r\n\t {\r\n\t \tint ind = appendRow();\r\n\t \tvalue[ind] = val;\r\n\t \treturn ind;\r\n\t }\r\n\t \r\n\t public void set_row(int row,int val1,int val2)\r\n\t {\r\n\t \tint ind = row*width;\r\n\t \tvalue[ind+0] = val1;\r\n\t \tvalue[ind+1] = val2; \t\r\n\t } \r\n\t public int push_back_row(int val1,int val2)\r\n\t {\r\n\t \tint ind = appendRow();\r\n\t \tvalue[ind*2+0] = val1;\r\n\t \tvalue[ind*2+1] = val2;\r\n\t \treturn ind;\r\n\t }\r\n\t public int push_back_row(int val1,int val2,int val3)\r\n\t {\r\n\t \tint ind = appendRow();\r\n\t \tvalue[ind*3+0] = val1;\r\n\t \tvalue[ind*3+1] = val2;\r\n\t \tvalue[ind*3+2] = val3;\r\n\t \treturn ind;\r\n\t }\r\n\r\n\t public int push_back_row(int val1,int val2,int val3,int val4)\r\n\t {\r\n\t \tint ind = appendRow();\r\n\t \tvalue[ind*4+0] = val1;\r\n\t \tvalue[ind*4+1] = val2;\r\n\t \tvalue[ind*4+2] = val3;\r\n\t \tvalue[ind*4+3] = val4;\r\n\t \treturn ind;\r\n\t }\r\n\r\n\t public int push_back_row(int val1,int val2,int val3,int val4,int val5)\r\n\t {\r\n\t \tint ind = appendRow();\r\n\t \tvalue[ind*5+0] = val1;\r\n\t \tvalue[ind*5+1] = val2;\r\n\t \tvalue[ind*5+2] = val3;\r\n\t \tvalue[ind*5+3] = val4;\r\n\t \tvalue[ind*5+4] = val5;\r\n\t \treturn ind;\r\n\t }\r\n\r\n\t public int push_back_row(int val1,int val2,int val3,int val4,int val5,int val6)\r\n\t {\r\n\t \tint ind = appendRow();\r\n\t \tvalue[ind*6+0] = val1;\r\n\t \tvalue[ind*6+1] = val2;\r\n\t \tvalue[ind*6+2] = val3;\r\n\t \tvalue[ind*6+3] = val4;\r\n\t \tvalue[ind*6+4] = val5;\r\n\t \tvalue[ind*6+5] = val6;\r\n\t \treturn ind;\r\n\t }\r\n\r\n\t public int push_back_row(int val1,int val2,int val3,int val4,int val5,int val6,int val7,int val8)\r\n\t {\r\n\t \tint ind = appendRow();\r\n\t \tvalue[ind*8+0] = val1;\r\n\t \tvalue[ind*8+1] = val2;\r\n\t \tvalue[ind*8+2] = val3;\r\n\t \tvalue[ind*8+3] = val4;\r\n\t \tvalue[ind*8+4] = val5;\r\n\t \tvalue[ind*8+5] = val6;\r\n\t \tvalue[ind*8+6] = val7;\r\n\t \tvalue[ind*8+7] = val8;\r\n\t \treturn ind;\r\n\t }\r\n\r\n\t public int push_back_row(int[] row)\r\n\t {\r\n\t \tint ind = appendRow();\r\n\t \tSystem.arraycopy(row, 0, value, width*(height-1), width);\r\n\t \treturn ind;\r\n\t }\r\n\t public void push_back_row(GeneralMatrixInt row)\r\n\t {\r\n\t \tappendRow();\r\n\t \tSystem.arraycopy(row.value, 0, value, width*(height-1), width);\r\n\t }\r\n\t public void push_back_row_from_block(GeneralMatrixInt row,int yFromFull)\r\n\t {\r\n\t \tappendRow();\r\n\t \tSystem.arraycopy(row.value, yFromFull*width, value, width*(height-1), width);\r\n\t }\r\n\t \r\n\t public void push_back_rows(GeneralMatrixInt rows)\r\n\t {\r\n\t \tif(rows.height==0)\r\n\t \t\treturn;\r\n\t \tappendRows(rows.height);\r\n\t \tSystem.arraycopy(rows.value, 0, value, width*(height-rows.height), width*rows.height);\r\n\t }\r\n\t\r\n\t\tpublic void appendColumn(int defaultvalue)\r\n\t\t{\r\n\t\t\tint newSize = (width+1)*height;\r\n\t \tif(value==null)\r\n\t \t{\r\n\t\t\t\twidth++;\r\n\t\t\t\treturn;\r\n\t \t}\r\n\t \t//if(newSize>value.length)\r\n\t \t{\r\n\t \t\tint[] oldv = value;\r\n\t \t\tvalue = new int[newSize];\r\n\t \t\twidth++;\r\n\t \t\tclear(defaultvalue);\r\n\t \t\tfor(int i=0;i<height;i++)\r\n\t \t\t{\r\n\t \t\t\tSystem.arraycopy(oldv, i*(width-1), value, i*(width), (width-1));\r\n\t \t\t}\r\n\t \t}\r\n\t\t}\r\n\t\r\n\t public void removeBlock(int column,int size)\r\n\t {\r\n\t \tif(width!=1)\r\n\t \t{\r\n\t \t\tSystem.out.println(\"Block removal only possible on 1d arrays\");\r\n\t \t}\r\n\t \tfor(int i=column;i<(height-size);i++)\r\n\t \t{\r\n\t \t\tvalue[i] = value[i+size];\r\n\t \t}\r\n\t \theight-=size;\r\n\t \tif(height<0)\r\n\t \t{\r\n\t \t\tSystem.out.println(\"Removal from nothing!\");\r\n\t \t}\r\n\t }\r\n\t \r\n\t public void insertBlockAfter(int index,int size)\r\n\t {\r\n\t \tinsertBlockBefore(index+1,size);\r\n\t }\t \r\n\t public void insertBlockBefore(int index,int size)\r\n\t {\r\n\t \tif(width!=1)\r\n\t \t{\r\n\t \t\tSystem.out.println(\"Block additions only possible on 1d arrays\");\r\n\t \t}\r\n\r\n\t \tint oldwidth = height;\r\n\t \tint newSize = height+size;\r\n\t \tif(value==null)\r\n\t \t{\r\n\t \t\tvalue = new int[newSize];\r\n\t \t}\r\n\t \telse\r\n\t \tif(newSize>value.length)\r\n\t \t{\r\n\t \t\tensureCapacity(newSize);\r\n\t \t}\r\n\t \theight = newSize;\r\n\t \tSystem.arraycopy(value, index, value, index+size, (oldwidth-index));\r\n\t }\r\n\r\n\t //For rectangles\r\n\t public void scaleAroundCenter(float f)\r\n\t {\r\n\t\t\tint y = (int)(value[1]-((float)value[3]*f-value[3])/2);\r\n\t\t\tif (y < 0) y = 0;\r\n\t\t\tint x = (int)(value[0]-((float)value[2]*f-value[2])/2);\r\n\t\t\tif (x < 0) x = 0;\r\n\t\t\tint h = (int)(value[3]*f);\r\n\t\t\tint w = (int)(value[2]*f);\r\n\t\t\tvalue[0] = x;\r\n\t\t\tvalue[1] = y;\r\n\t\t\tvalue[2] = w;\r\n\t\t\tvalue[3] = h;\r\n\t }\r\n}\r", "public class GeneralMatrixObject implements Serializable \r\n{\r\n\tprivate static final long serialVersionUID = 1L;\r\n\r\n\tpublic int width;\r\n\tpublic int height;\r\n\tpublic Object[] value;\r\n\r\n public GeneralMatrixObject()\r\n {\r\n \twidth = 0;\r\n \theight = 0;\r\n \tvalue = new Object[8];\r\n }\r\n public GeneralMatrixObject(Object a)\r\n {\r\n \twidth = 1;\r\n \theight = 1;\r\n \tvalue = new Object[1];\r\n \tvalue[0] = a;\r\n }\r\n public GeneralMatrixObject(GeneralMatrixObject o)\r\n {\r\n \tthis.width = o.width;\r\n \tthis.height = o.height;\r\n \tvalue = new Object[width*height];\r\n \tif(value.length>0)\r\n \t\tSystem.arraycopy(o.value, 0, value, 0, value.length);\r\n }\r\n public GeneralMatrixObject(Object[] o)\r\n {\r\n \tthis.width = 1;\r\n \tthis.height = o.length;\r\n \tvalue = new Object[width*height];\r\n \tif(value.length>0)\r\n \t\tSystem.arraycopy(o, 0, value, 0, value.length);\r\n }\r\n public GeneralMatrixObject(int width)\r\n {\r\n \tthis.width = width;\r\n \theight = 0;\r\n \tvalue = new Object[8];\r\n }\r\n public GeneralMatrixObject(int width,int height)\r\n {\r\n \tthis.width = width;\r\n \tthis.height = height;\r\n \tvalue = new Object[width*height];\r\n }\r\n public GeneralMatrixObject(int width,int height,int mincap)\r\n {\r\n \tthis.width = width;\r\n \tthis.height = height;\r\n \tvalue = new Object[mincap];\r\n }\r\n \r\n public Object clone()\r\n {\r\n \tGeneralMatrixObject o = new GeneralMatrixObject(width,height);\r\n \tfor(int i=0;i<(width*height);i++)\r\n \t{\r\n \t\tObject v = value[i];\r\n \t\tif(v instanceof GeneralMatrixObject)\r\n \t\t{\r\n \t\t\tv = ((GeneralMatrixObject)v).clone();\r\n \t\t}\r\n \t\telse\r\n \t\tif(v instanceof GeneralMatrixString)\r\n \t\t{\r\n \t\t\tv = ((GeneralMatrixString)v).clone(); \t\t\t\r\n \t\t}\r\n \t\to.value[i] = v;\r\n \t}\r\n \treturn o;\r\n }\r\n\r\n \r\n public int push_back(Object o)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind] = o;\r\n \treturn ind;\r\n }\r\n \r\n public int appendRow()\r\n {\r\n \tint newSize = width*(height+1);\r\n \tif(newSize>value.length)\r\n \t{\r\n \t\tensureCapacity(newSize);\r\n \t}\r\n\t\theight++;\r\n\t\treturn height-1;\r\n }\r\n \r\n public int appendRows(int size)\r\n {\r\n \tint newSize = width*(height+size);\r\n \tif(value==null)\r\n \t{\r\n \t\tvalue = new Object[newSize];\r\n\t\t\theight+=size;\r\n\t\t\treturn height-size;\r\n \t}\r\n \tif(newSize>value.length)\r\n \t{\r\n \t\tensureCapacity(newSize);\r\n \t}\r\n\t\theight+=size;\r\n\t\treturn height-size;\r\n }\r\n\r\n public void removeRow(int index)\r\n {\r\n \tfor(int i=index*width;i<((height-1))*width;i++)\r\n \t{\r\n \t\tvalue[i] = value[i+width];\r\n \t}\r\n \theight--;\r\n }\r\n\r\n public void ensureCapacity(int mincap)\r\n {\r\n \tif(value==null)\r\n \t{\r\n \t\tvalue = new Object[mincap];\r\n \t}\r\n \telse\r\n \tif(mincap>value.length)\r\n \t{\r\n\t int newcap = (value.length * 3)/2 + 1;\r\n\t Object[] olddata = value;\r\n\t value = new Object[newcap < mincap ? mincap : newcap];\r\n\t System.arraycopy(olddata,0,value,0,olddata.length);\r\n \t}\r\n }\r\n// public void ensureCapacity(int mincap)\r\n// {\r\n// int newcap = (value.length * 3)/2 + 1;\r\n// Object[] olddata = value;\r\n// value = new Object[newcap < mincap ? mincap : newcap];\r\n// System.arraycopy(olddata,0,value,0,olddata.length); \t\t\r\n// }\r\n\r\n\r\n public void clear()\r\n\t{\r\n\t\tfor (int i = 0; i < width*height; i++)\r\n\t\t{\r\n\t\t\tvalue[i] = null;\r\n\t\t}\r\n\t}\r\n\r\n\t public int find(Object v)\r\n\t {\r\n\t\t for(int i=0;i<(width*height);i++)\r\n\t\t {\r\n\t\t\t if(value[i]==v)\r\n\t\t\t\t return i;\r\n\t\t }\r\n\t\t return -1;\r\n\t }\r\n \r\n\t public void set(GeneralMatrixObject o)\r\n\t {\r\n\t\t setDimensions(o.width, o.height);\r\n\t\t int len = o.width*o.height;\r\n \t if(len>0)\r\n \t\t System.arraycopy(o.value, 0, value, 0, len);\r\n\t }\r\n\t\tpublic void setFromSubset(GeneralMatrixObject full,int ys)\r\n\t\t{\r\n\t\t\tint i=0;\r\n\t\t\tint fi = ys*width;\r\n\t\t\tfor(int y=0;y<height;y++)\r\n\t\t\t{\r\n\t\t\t\tfor(int x=0;x<width;x++)\r\n\t\t\t\t{\r\n\t\t\t\t\tvalue[i] = full.value[fi];\r\n\t\t\t\t\ti++;\r\n\t\t\t\t\tfi++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n public void setDimensions(int w,int h)\r\n {\r\n \tensureCapacity(w*h);\r\n \twidth = w;\r\n \theight = h;\r\n }\r\n\r\n public void setDimensionsAndClearNew(int w,int h)\r\n {\r\n \tint oldl = width*height;\r\n \tensureCapacity(w*h);\r\n \twidth = w;\r\n \theight = h;\r\n \tint newl = w*h;\r\n \tfor(int i=oldl;i<newl;i++)\r\n \t{\r\n \t\tvalue[i] = null;\r\n \t}\r\n }\r\n \r\n public int push_back_row(Object val1,Object val2)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*2+0] = val1;\r\n \tvalue[ind*2+1] = val2;\r\n \treturn ind;\r\n }\r\n\r\n public int push_back_row(Object val1,Object val2,Object val3)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*3+0] = val1;\r\n \tvalue[ind*3+1] = val2;\r\n \tvalue[ind*3+2] = val3;\r\n \treturn ind;\r\n }\r\n\r\n public int push_back_row(Object val1,Object val2,Object val3,Object val4)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*4+0] = val1;\r\n \tvalue[ind*4+1] = val2;\r\n \tvalue[ind*4+2] = val3;\r\n \tvalue[ind*4+3] = val4;\r\n \treturn ind;\r\n }\r\n\r\n public int push_back_row(Object val1,Object val2,Object val3,Object val4,Object val5)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*5+0] = val1;\r\n \tvalue[ind*5+1] = val2;\r\n \tvalue[ind*5+2] = val3;\r\n \tvalue[ind*5+3] = val4;\r\n \tvalue[ind*5+4] = val5;\r\n \treturn ind;\r\n }\r\n\r\n public int push_back_row(Object val1,Object val2,Object val3,Object val4,Object val5,Object val6)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*6+0] = val1;\r\n \tvalue[ind*6+1] = val2;\r\n \tvalue[ind*6+2] = val3;\r\n \tvalue[ind*6+3] = val4;\r\n \tvalue[ind*6+4] = val5;\r\n \tvalue[ind*6+5] = val6;\r\n \treturn ind;\r\n }\r\n\r\n public int push_back_row(Object val1,Object val2,Object val3,Object val4,Object val5,Object val6,Object val7,Object val8,Object val9)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*9+0] = val1;\r\n \tvalue[ind*9+1] = val2;\r\n \tvalue[ind*9+2] = val3;\r\n \tvalue[ind*9+3] = val4;\r\n \tvalue[ind*9+4] = val5;\r\n \tvalue[ind*9+5] = val6;\r\n \tvalue[ind*9+6] = val7;\r\n \tvalue[ind*9+7] = val8;\r\n \tvalue[ind*9+8] = val9;\r\n \treturn ind;\r\n }\r\n\r\n public int push_back_row(Object val1,Object val2,Object val3,Object val4,Object val5,Object val6,Object val7,Object val8,Object val9,Object val10)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*10+0] = val1;\r\n \tvalue[ind*10+1] = val2;\r\n \tvalue[ind*10+2] = val3;\r\n \tvalue[ind*10+3] = val4;\r\n \tvalue[ind*10+4] = val5;\r\n \tvalue[ind*10+5] = val6;\r\n \tvalue[ind*10+6] = val7;\r\n \tvalue[ind*10+7] = val8;\r\n \tvalue[ind*10+8] = val9;\r\n \tvalue[ind*10+9] = val10;\r\n \treturn ind;\r\n }\r\n\r\n public void push_back_rows(GeneralMatrixObject rows)\r\n {\r\n \tif(rows.height==0)\r\n \t\treturn;\r\n \tappendRows(rows.height);\r\n \tSystem.arraycopy(rows.value, 0, value, width*(height-rows.height), width*rows.height);\r\n }\r\n\r\n public void push_back_row_from_block(GeneralMatrixObject row,int yFromFull)\r\n {\r\n \tappendRow();\r\n \tSystem.arraycopy(row.value, yFromFull*width, value, width*(height-1), width);\r\n }\r\n\r\n }\r", "public class GeneralMatrixString implements Serializable \r\n{\r\n\tprivate static final long serialVersionUID = 1L;\r\n\r\n\tpublic int width = 0;\r\n\tpublic int height = 0;\r\n\tpublic String[] value;\r\n\r\n public GeneralMatrixString()\r\n {\r\n }\r\n public GeneralMatrixString(int width)\r\n {\r\n \tthis.width = width;\r\n \theight = 0;\r\n \tvalue = new String[8];\r\n }\r\n public GeneralMatrixString(int width,int height)\r\n {\r\n \tthis.width = width;\r\n \tthis.height = height;\r\n \tvalue = new String[height*width];\r\n }\r\n public GeneralMatrixString(int width,int height,int mincap)\r\n {\r\n \tthis.width = width;\r\n \tthis.height = height;\r\n \tvalue = new String[mincap];\r\n }\r\n public GeneralMatrixString(String val)\r\n {\r\n \tthis.width = 1;\r\n \tthis.height = 1;\r\n \tvalue = new String[1];\r\n \tvalue[0] = val;\r\n }\r\n public GeneralMatrixString(String val0,String val1)\r\n {\r\n \tthis.width = 1;\r\n \tthis.height = 2;\r\n \tvalue = new String[2];\r\n \tvalue[0] = val0;\r\n \tvalue[1] = val1;\r\n }\r\n public GeneralMatrixString(String val0,String val1,String val2)\r\n {\r\n \tthis.width = 1;\r\n \tthis.height = 3;\r\n \tvalue = new String[3];\r\n \tvalue[0] = val0;\r\n \tvalue[1] = val1;\r\n \tvalue[2] = val2;\r\n }\r\n public GeneralMatrixString(String val0,String val1,String val2,String val3)\r\n {\r\n \tthis.width = 1;\r\n \tthis.height = 4;\r\n \tvalue = new String[4];\r\n \tvalue[0] = val0;\r\n \tvalue[1] = val1;\r\n \tvalue[2] = val2;\r\n \tvalue[3] = val3;\r\n }\r\n public GeneralMatrixString(String val0,String val1,String val2,String val3,String val4)\r\n {\r\n \tthis.width = 1;\r\n \tthis.height = 5;\r\n \tvalue = new String[5];\r\n \tvalue[0] = val0;\r\n \tvalue[1] = val1;\r\n \tvalue[2] = val2;\r\n \tvalue[3] = val3;\r\n \tvalue[4] = val4;\r\n }\r\n public GeneralMatrixString(String val0,String val1,String val2,String val3,String val4,String val5)\r\n {\r\n \tthis.width = 1;\r\n \tthis.height = 6;\r\n \tvalue = new String[6];\r\n \tvalue[0] = val0;\r\n \tvalue[1] = val1;\r\n \tvalue[2] = val2;\r\n \tvalue[3] = val3;\r\n \tvalue[4] = val4;\r\n \tvalue[5] = val5;\r\n }\r\n public GeneralMatrixString(String val0,String val1,String val2,String val3,String val4,String val5,String val6)\r\n {\r\n \tthis.width = 1;\r\n \tthis.height = 7;\r\n \tvalue = new String[7];\r\n \tvalue[0] = val0;\r\n \tvalue[1] = val1;\r\n \tvalue[2] = val2;\r\n \tvalue[3] = val3;\r\n \tvalue[4] = val4;\r\n \tvalue[5] = val5;\r\n \tvalue[6] = val6;\r\n }\r\n public GeneralMatrixString(String val0,String val1,String val2,String val3,String val4,String val5,String val6,String val7)\r\n {\r\n \tthis.width = 1;\r\n \tthis.height = 8;\r\n \tvalue = new String[8];\r\n \tvalue[0] = val0;\r\n \tvalue[1] = val1;\r\n \tvalue[2] = val2;\r\n \tvalue[3] = val3;\r\n \tvalue[4] = val4;\r\n \tvalue[5] = val5;\r\n \tvalue[6] = val6;\r\n \tvalue[7] = val7;\r\n }\r\n public GeneralMatrixString(String val0,String val1,String val2,String val3,String val4,String val5,String val6,String val7,String val8)\r\n {\r\n \tthis.width = 1;\r\n \tthis.height = 9;\r\n \tvalue = new String[9];\r\n \tvalue[0] = val0;\r\n \tvalue[1] = val1;\r\n \tvalue[2] = val2;\r\n \tvalue[3] = val3;\r\n \tvalue[4] = val4;\r\n \tvalue[5] = val5;\r\n \tvalue[6] = val6;\r\n \tvalue[7] = val7;\r\n \tvalue[8] = val8;\r\n }\r\n public GeneralMatrixString(String val0,String val1,String val2,String val3,String val4,String val5,String val6,String val7,String val8,String val9,String val10,String val11,String val12)\r\n {\r\n \tthis.width = 1;\r\n \tthis.height = 13;\r\n \tvalue = new String[13];\r\n \tvalue[0] = val0;\r\n \tvalue[1] = val1;\r\n \tvalue[2] = val2;\r\n \tvalue[3] = val3;\r\n \tvalue[4] = val4;\r\n \tvalue[5] = val5;\r\n \tvalue[6] = val6;\r\n \tvalue[7] = val7;\r\n \tvalue[8] = val8;\r\n \tvalue[9] = val9;\r\n \tvalue[10] = val10;\r\n \tvalue[11] = val11;\r\n \tvalue[12] = val12;\r\n }\r\n public GeneralMatrixString(final GeneralMatrixString val)\r\n {\r\n \tthis.width = val.width;\r\n \tthis.height = val.height;\r\n \tif(val.value!=null)\r\n \t\tvalue = val.value.clone();\r\n }\r\n public GeneralMatrixString(int width,int height,String[] val)\r\n {\r\n \tthis.width = width;\r\n \tthis.height = height;\r\n \tvalue = val;\r\n }\r\n public GeneralMatrixString(int width,int height,String val)\r\n {\r\n \tthis.width = width;\r\n \tthis.height = height;\r\n \tint mincap = width*height;\r\n \tvalue = new String[mincap];\r\n \tfor(int i=0;i<mincap;i++)\r\n \t\tvalue[i] = \"\"+val;\r\n }\r\n public GeneralMatrixString(String[] val)\r\n {\r\n \tthis.width = 1;\r\n \tif(val==null)\r\n \t{\r\n \t\tthis.height = 0;\r\n \t\tvalue = null;\r\n \t\treturn;\r\n \t}\r\n \tthis.height = val.length;\r\n \tvalue = val;\r\n }\r\n\r\n public Object clone()\r\n {\r\n \treturn new GeneralMatrixString(this);\r\n }\r\n \r\n\tpublic boolean isequal(GeneralMatrixString o)\r\n\t{\r\n\t\tif(!(width==o.width))\r\n\t\t\treturn false;\r\n\t\tif(!(height==o.height))\r\n\t\t\treturn false;\r\n\t\tfor(int i=0;i<width*height;i++)\r\n\t\t{\r\n\t\t\tif(!(value[i]).contentEquals(o.value[i]))\r\n\t\t\t\treturn false;\r\n\t\t}\r\n\t\treturn true;\r\n\r\n//\t\tboolean is = true;\r\n//\t\tis = is && (width==o.width);\r\n//\t\tis = is && (height==o.height);\r\n//\t\tif(is)\r\n//\t\t{\r\n//\t\t\tfor(int i=0;i<width*height;i++)\r\n//\t\t\t{\r\n//\t\t\t\tis = is && (value[i].contentEquals(o.value[i]));\r\n//\t\t\t}\r\n//\t\t}\r\n//\t\tif(!is)\r\n//\t\t\tSystem.out.println(\"diff!\");\r\n//\t\treturn is;\r\n\t}\r\n\t\r\n public void clear(String s)\r\n {\r\n \tfor(int i=0;i<(width*height);i++)\r\n \t{\r\n \t\tvalue[i] = \"\"+s;\r\n \t} \t\r\n }\r\n \r\n public int contains(String v)\r\n {\r\n \tfor(int i=0;i<(width*height);i++)\r\n \t{\r\n \t\tif(value[i].contains(v))\r\n \t\t\treturn i;\r\n \t}\r\n \treturn -1; \t\r\n }\r\n public int find(String v)\r\n {\r\n \tfor(int i=0;i<(width*height);i++)\r\n \t{\r\n \t\tif(value[i].equalsIgnoreCase(v))\r\n \t\t\treturn i;\r\n \t}\r\n \treturn -1;\r\n }\r\n public boolean includes(GeneralMatrixString subset)\r\n {\r\n \tfor(int j=0;j<(subset.width*subset.height);j++)\r\n \t{\r\n \t\tboolean found = false;\r\n\t \tfor(int i=0;i<(width*height);i++)\r\n\t \t{\r\n\t \t\tif(value[i].equalsIgnoreCase(subset.value[j]))\r\n\t \t\t{\r\n\t \t\t\tfound = true;\r\n\t \t\t\tbreak;\r\n\t \t\t}\r\n\t \t}\r\n\t\t\tif(!found)\r\n\t\t\t\treturn false;\r\n \t}\r\n \treturn true;\r\n }\r\n public int findContaining(String v)\r\n {\r\n \tfor(int i=0;i<(width*height);i++)\r\n \t{\r\n \t\tif(value[i].contains(v))\r\n \t\t\treturn i;\r\n \t}\r\n \treturn -1;\r\n }\r\n \r\n public void set(GeneralMatrixString o)\r\n {\r\n \twidth = o.width;\r\n\t\theight = o.height;\r\n\t\tensureCapacity(height*width);\t\r\n\t\tSystem.arraycopy(o.value, 0, value, 0, height*width);\r\n }\r\n public void set(String[] o,int h)\r\n {\r\n\t\tensureCapacity(h);\t\r\n \twidth = 1;\r\n\t\theight = h;\r\n\t\tSystem.arraycopy(o, 0, value, 0, height*width);\r\n }\r\n public int push_back(String o)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind] = o;\r\n \treturn ind;\r\n }\r\n \r\n public int appendRow()\r\n {\r\n \t\r\n \tint newSize = width*(height+1);\r\n \tif((value == null)||(newSize>value.length))\r\n \t{\r\n \t\tensureCapacity(newSize);\r\n \t}\r\n\t\theight++;\r\n\t\treturn height-1;\r\n }\r\n \r\n public int appendRows(int size)\r\n {\r\n \tint newSize = width*(height+size);\r\n \tif(value==null)\r\n \t{\r\n \t\tvalue = new String[newSize];\r\n\t\t\theight+=size;\r\n\t\t\treturn height-size;\r\n \t}\r\n \tif(newSize>value.length)\r\n \t{\r\n \t\tensureCapacity(newSize);\r\n \t}\r\n\t\theight+=size;\r\n\t\treturn height-size;\r\n }\r\n\r\n public void removeRow(int index)\r\n {\r\n \tfor(int i=index*width;i<((height-1))*width;i++)\r\n \t{\r\n \t\tvalue[i] = value[i+width];\r\n \t}\r\n \theight--;\r\n }\r\n\r\n public void ensureCapacity(int mincap)\r\n {\r\n \tif(value == null)\r\n \t{\r\n \t\tvalue = new String[mincap];\r\n \t\treturn;\r\n \t}\r\n \tif(mincap<=value.length)\r\n \t\treturn;\r\n int newcap = (value.length * 3)/2 + 1;\r\n String[] olddata = value;\r\n value = new String[newcap < mincap ? mincap : newcap];\r\n System.arraycopy(olddata,0,value,0,olddata.length); \t\t\r\n }\r\n \r\n\r\n\tpublic static int find(String[] value,String v)\r\n {\r\n\t\tint height = value.length;\r\n \tfor(int i=0;i<(height);i++)\r\n \t{\r\n \t\tif(value[i].equalsIgnoreCase(v))\r\n \t\t\treturn i;\r\n \t}\r\n \treturn -1;\r\n }\r\n\tpublic static int find(String[] value,int height,String v)\r\n {\r\n \tfor(int i=0;i<(height);i++)\r\n \t{\r\n \t\tif(value[i].equalsIgnoreCase(v))\r\n \t\t\treturn i;\r\n \t}\r\n \treturn -1;\r\n }\r\n\r\n public void push_back_row(String o1,String o2)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*2+0] = o1;\r\n \tvalue[ind*2+1] = o2;\r\n }\r\n \r\n public void push_back_row(String o1,String o2,String o3)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*3+0] = o1;\r\n \tvalue[ind*3+1] = o2;\r\n \tvalue[ind*3+2] = o3;\r\n }\r\n \r\n public void push_back_row(String o1,String o2,String o3,String o4)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*4+0] = o1;\r\n \tvalue[ind*4+1] = o2;\r\n \tvalue[ind*4+2] = o3;\r\n \tvalue[ind*4+3] = o4;\r\n }\r\n \r\n public void push_back_row(String o1,String o2,String o3,String o4,String o5)\r\n {\r\n \tint ind = appendRow();\r\n \tvalue[ind*5+0] = o1;\r\n \tvalue[ind*5+1] = o2;\r\n \tvalue[ind*5+2] = o3;\r\n \tvalue[ind*5+3] = o4;\r\n \tvalue[ind*5+4] = o5;\r\n }\r\n \r\n public void push_back_rows(GeneralMatrixString rows)\r\n {\r\n \tappendRows(rows.height);\r\n \tSystem.arraycopy(rows.value, 0, value, width*(height-rows.height), width*rows.height);\r\n }\r\n\r\n public void setDimensions(int w,int h)\r\n {\r\n \tensureCapacity(w*h);\r\n \twidth = w;\r\n \theight = h;\r\n }\r\n\r\n public void insertRowAfter(int index)\r\n {\r\n \tappendRow();\r\n \tSystem.arraycopy(value, (index+1)*width, value, (index+2)*width, (height-1-(index+1))*width);\r\n }\r\n \r\n public void insertRowBefore(int index)\r\n {\r\n \tint srcind = (index);\r\n \tint destind = (index+1);\r\n \tint length = (height-1-(index));\r\n \ttry{\r\n\t \tappendRow();\r\n\t \tSystem.arraycopy(value, srcind, value, destind, length);\t \t\t\r\n \t}\r\n \tcatch(Exception e)\r\n \t{\r\n \t\tSystem.out.println(\"insertRowBefore error\");\r\n \t}\r\n }\r\n}\r", "public class Quaternion implements Serializable \r\n{\r\n\tpublic static void MatrixtoQuaternion(float[] m,float[] a)\r\n\t{\r\n\t\t// Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes\r\n\t\t// article \"Quaternion Calculus and Fast Animation\".\r\n\r\n\t\tfinal float trace = m[3*0+0] + m[3*1+1] + m[3*2+2];\r\n\r\n\t\tif (trace>0)\r\n\t\t{\r\n\t\t\t// |w| > 1/2, may as well choose w > 1/2\r\n\r\n\t\t\tfloat root = (float)Math.sqrt(trace + 1.0f); // 2w\r\n\t\t\ta[3] = 0.5f * root;\r\n\t\t\troot = 0.5f / root; // 1/(4w)\r\n\t\t\ta[0] = (m[3*2+1]-m[3*1+2]) * root;\r\n\t\t\ta[1] = (m[3*0+2]-m[3*2+0]) * root;\r\n\t\t\ta[2] = (m[3*1+0]-m[3*0+1]) * root;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t// |w| <= 1/2\r\n\r\n\t\t\tfinal int[] next = { 1, 2, 0 };\r\n\t\t\t\r\n\t\t\tint i = 1;\r\n\t\t\tif (m[3*1+1]>m[3*0+0]) i = 2;\r\n\t\t\tif (m[3*2+2]>m[3*i+i]) i = 3;\r\n\t\t\tint j = next[i];\r\n\t\t\tint k = next[j];\r\n\t\t\t\r\n\t\t\t\r\n\t\t\tfloat root = (float)Math.sqrt(m[3*i+i]-m[3*j+j]-m[3*k+k] + 1.0f);\r\n\t\t\t//float *quaternion[3] = { &x, &y, &z };\r\n\t\t\ta[i] = 0.5f * root;\r\n\t\t\troot = 0.5f / root;\r\n\t\t\ta[3] = (m[3*k+j]-m[3*j+k])*root;\r\n\t\t\ta[j] = (m[3*j+i]+m[3*i+j])*root;\r\n\t\t\ta[k] = (m[3*k+i]+m[3*i+k])*root;\r\n\t\t}\r\n\t}\r\n\tpublic static void MatrixtoQuaternion(float[] m,int mo,float[] a)\r\n\t{\r\n\t\t// Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes\r\n\t\t// article \"Quaternion Calculus and Fast Animation\".\r\n\r\n\t\tfinal float trace = m[mo+3*0+0] + m[mo+3*1+1] + m[mo+3*2+2];\r\n\r\n\t\tif (trace>0)\r\n\t\t{\r\n\t\t\t// |w| > 1/2, may as well choose w > 1/2\r\n\r\n\t\t\tfloat root = (float)Math.sqrt(trace + 1.0f); // 2w\r\n\t\t\ta[3] = 0.5f * root;\r\n\t\t\troot = 0.5f / root; // 1/(4w)\r\n\t\t\ta[0] = (m[mo+3*2+1]-m[mo+3*1+2]) * root;\r\n\t\t\ta[1] = (m[mo+3*0+2]-m[mo+3*2+0]) * root;\r\n\t\t\ta[2] = (m[mo+3*1+0]-m[mo+3*0+1]) * root;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t// |w| <= 1/2\r\n\r\n\t\t\tfinal int[] next = { 1, 2, 0 };\r\n\t\t\t\r\n\t\t\tint i = 0;\r\n\t\t\tif (m[mo+3*1+1]>m[mo+3*0+0]) i = 1;\r\n\t\t\tif (m[mo+3*2+2]>m[mo+3*i+i]) i = 2;\r\n\t\t\tint j = next[i];\r\n\t\t\tint k = next[j];\r\n\t\t\t\r\n\t\t\t\r\n\t\t\tfloat root = (float)Math.sqrt(m[mo+3*i+i]-m[mo+3*j+j]-m[mo+3*k+k] + 1.0f);\r\n\t\t\t//float *quaternion[3] = { &x, &y, &z };\r\n\t\t\ta[i] = 0.5f * root;\r\n\t\t\troot = 0.5f / root;\r\n\t\t\ta[3] = (m[mo+3*k+j]-m[mo+3*j+k])*root;\r\n\t\t\ta[j] = (m[mo+3*j+i]+m[mo+3*i+j])*root;\r\n\t\t\ta[k] = (m[mo+3*k+i]+m[mo+3*i+k])*root;\r\n\t\t}\r\n\t}\r\n\tpublic static void QuaterniontoMatrix(float[] a,float[] m)\r\n\t{\r\n\t\tfloat fTx = 2.0f*a[0];\r\n\t\tfloat fTy = 2.0f*a[1];\r\n\t\tfloat fTz = 2.0f*a[2];\r\n\t\tfloat fTwx = fTx*a[3];\r\n\t\tfloat fTwy = fTy*a[3];\r\n\t\tfloat fTwz = fTz*a[3];\r\n\t\tfloat fTxx = fTx*a[0];\r\n\t\tfloat fTxy = fTy*a[0];\r\n\t\tfloat fTxz = fTz*a[0];\r\n\t\tfloat fTyy = fTy*a[1];\r\n\t\tfloat fTyz = fTz*a[1];\r\n\t\tfloat fTzz = fTz*a[2];\r\n\r\n\t\tm[0] = 1.0f-(fTyy+fTzz);\tm[1] = fTxy-fTwz;\t\t\tm[2] = fTxz+fTwy;\r\n\t\tm[0+3] = fTxy+fTwz;\t\t\tm[1+3] = 1.0f-(fTxx+fTzz);\tm[2+3] = fTyz-fTwx;\r\n\t\tm[0+6] = fTxz-fTwy;\t\t\tm[1+6] = fTyz+fTwx;\t\t\tm[2+6] = 1.0f-(fTxx+fTyy);\r\n\t}\r\n\tpublic static void QuaterniontoMatrix(float[] a,float[] m,int mo)\r\n\t{\r\n\t\tfloat fTx = 2.0f*a[0];\r\n\t\tfloat fTy = 2.0f*a[1];\r\n\t\tfloat fTz = 2.0f*a[2];\r\n\t\tfloat fTwx = fTx*a[3];\r\n\t\tfloat fTwy = fTy*a[3];\r\n\t\tfloat fTwz = fTz*a[3];\r\n\t\tfloat fTxx = fTx*a[0];\r\n\t\tfloat fTxy = fTy*a[0];\r\n\t\tfloat fTxz = fTz*a[0];\r\n\t\tfloat fTyy = fTy*a[1];\r\n\t\tfloat fTyz = fTz*a[1];\r\n\t\tfloat fTzz = fTz*a[2];\r\n\r\n\t\tm[mo+0] = 1.0f-(fTyy+fTzz);\t\tm[mo+1] = fTxy-fTwz;\t\t\tm[mo+2] = fTxz+fTwy;\r\n\t\tm[mo+0+3] = fTxy+fTwz;\t\t\tm[mo+1+3] = 1.0f-(fTxx+fTzz);\tm[mo+2+3] = fTyz-fTwx;\r\n\t\tm[mo+0+6] = fTxz-fTwy;\t\t\tm[mo+1+6] = fTyz+fTwx;\t\t\tm[mo+2+6] = 1.0f-(fTxx+fTyy);\r\n\t}\r\n\tpublic static void slerp(float[] a, float[] b, float t, float[] c) \r\n\t{\r\n\t\tassert(t>=0);\r\n\t\tassert(t<=1);\r\n\t\t\t\t\r\n\t\tfloat flip = 1;\r\n\r\n\t\tfloat cosine = a[3]*b[3] + a[0]*b[0] + a[1]*b[1] + a[2]*b[2];\r\n\t\t\r\n\t\tif (cosine<0) \r\n\t\t{ \r\n\t\t\tcosine = -cosine; \r\n\t\t\tflip = -1; \r\n\t\t} \r\n\t\t\r\n\t\tif ((1-cosine)<GeneralMatrixFloat.EPSILON)\r\n\t\t{\r\n\t\t\tfloat it = (1-t);\r\n\t\t\tfloat tf = (t*flip);\r\n\t\t\tc[0] = a[0]*it+b[0]*tf;\r\n\t\t\tc[1] = a[1]*it+b[1]*tf;\r\n\t\t\tc[2] = a[2]*it+b[2]*tf;\r\n\t\t\tc[3] = a[3]*it+b[3]*tf;\r\n\t\t\treturn; \r\n\t\t}\r\n\t\t\r\n\t\tfloat theta = (float)Math.acos(cosine); \r\n\t\tfloat sine = (float)Math.sin(theta); \r\n\t\tfloat beta = (float)Math.sin((1-t)*theta) / sine; \r\n\t\tfloat alpha = (float)Math.sin(t*theta) / sine * flip; \r\n\t\t\r\n\t\tc[0] = a[0]*beta+b[0]*alpha;\r\n\t\tc[1] = a[1]*beta+b[1]*alpha;\r\n\t\tc[2] = a[2]*beta+b[2]*alpha;\r\n\t\tc[3] = a[3]*beta+b[3]*alpha;\r\n\t} \r\n\r\n}\r", "public class HumanBones \n{\n\tpublic static int[] bones=\n\t{\n\t\t21,18,\n\t\t//18,21,\n\t\t18,19,\n\t\t19,20,\n\t\t20,2,\n\t\t2,1,\n\t\t1,0,\n\t\t21,100,\n\t\t100,101,\n\t\t101,102,\n\t\t102,103,\n\t\t103,104,\n\t\t21,76,\n\t\t76,77,\n\t\t77,78,\n\t\t78,79,\n\t\t79,80,\n\t\t0,4,\n\t\t0,11,\n\t\t0,15,\n\t\t2,22,\n\t\t2,49,\n\t\t4,3,\n\t\t11,12,\n\t\t15,16,\n\t\t11,9,\n\t\t11,10,\n\t\t15,13,\n\t\t15,14,\n\t\t49,51,\n\t\t51,52,\n\t\t52,53,\n\t\t53,68,\n\t\t53,55,\n\t\t53,54,\n\t\t53,56,\n\t\t55,60,\n\t\t55,68,\n\t\t54,64,\n\t\t54,72,\n\t\t22,24,\n\t\t24,25,\n\t\t25,26,\n\t\t26,41,\n\t\t26,28,\n\t\t26,27,\n\t\t26,29,\n\t\t28,33,\n\t\t28,41,\n\t\t27,37,\n\t\t27,45,\n\t\t56,57,\n\t\t57,58,\n\t\t58,59,\n\t\t60,61,\n\t\t61,62,\n\t\t62,63,\n\t\t68,69,\n\t\t69,70,\n\t\t70,71,\n\t\t64,65,\n\t\t65,66,\n\t\t66,67,\n\t\t72,73,\n\t\t73,74,\n\t\t74,75,\n\t\t29,30,\n\t\t30,31,\n\t\t31,32,\n\t\t33,34,\n\t\t34,35,\n\t\t35,36,\n\t\t41,42,\n\t\t42,43,\n\t\t43,44,\n\t\t37,38,\n\t\t38,39,\n\t\t39,40,\n\t\t45,46,\n\t\t46,47,\n\t\t47,48,\n\t\t3,5,\n\t\t5,6,\n\t\t6,7,\n\t\t7,8,\n\t};\n\n\tpublic static final float DEG2RAD = ((float)Math.PI)/180.0f;\n\t\n\tpublic static float[] bjlimits=\n\t{\n\t\t//Spine\n//\t\t\"joint-pelvistojoint-spine3\",\n\t\t-180.0f*DEG2RAD,180.0f*DEG2RAD,-180.0f*DEG2RAD,180.0f*DEG2RAD,-180.0f*DEG2RAD,180.0f*DEG2RAD,\n//\t\t-180.0f*DEG2RAD,180.0f*DEG2RAD,-16.0f*DEG2RAD,16.0f*DEG2RAD,-180.0f*DEG2RAD,180.0f*DEG2RAD,\n\t\t//\"joint-spine3tojoint-pelvis\",\n\t\t//-180.0f*DEG2RAD,180.0f*DEG2RAD,-16.0f*DEG2RAD,16.0f*DEG2RAD,-180.0f*DEG2RAD,180.0f*DEG2RAD,\n//\t\t\"joint-spine3tojoint-spine2\",\n\t\t-40.0f*DEG2RAD,50.0f*DEG2RAD,-16.0f*DEG2RAD,16.0f*DEG2RAD,-16.0f*DEG2RAD,16.0f*DEG2RAD,\n//\t\t\"joint-spine2tojoint-spine1\",\n\t\t-70.0f*DEG2RAD,60.0f*DEG2RAD,-16.0f*DEG2RAD,16.0f*DEG2RAD,-50.0f*DEG2RAD,50.0f*DEG2RAD,\n//\t\t\"joint-spine1tojoint-neck\",\n\t\t-20.0f*DEG2RAD,20.0f*DEG2RAD,-16.0f*DEG2RAD,16.0f*DEG2RAD,-20.0f*DEG2RAD,20.0f*DEG2RAD,\n\n\t\t//neck\n//\t\t\"joint-necktojoint-head\",\n\t\t-10.0f*DEG2RAD,20.0f*DEG2RAD,-16.0f*DEG2RAD,16.0f*DEG2RAD,-40.0f*DEG2RAD,40.0f*DEG2RAD,\n//\t\t\"joint-headtojoint-head2\",\n\t\t-30.0f*DEG2RAD,40.0f*DEG2RAD,-74.0f*DEG2RAD,74.0f*DEG2RAD,-30.0f*DEG2RAD,30.0f*DEG2RAD,\n\n\n\t\t//right leg\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t-110.0f*DEG2RAD,30.0f*DEG2RAD,-90.0f*DEG2RAD,90.0f*DEG2RAD,-90.0f*DEG2RAD,110.0f*DEG2RAD,\n\t\t-130.0f*DEG2RAD,20.0f*DEG2RAD,-25.0f*DEG2RAD,35.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t-50.0f*DEG2RAD,50.0f*DEG2RAD,-30.0f*DEG2RAD,30.0f*DEG2RAD,-45.0f*DEG2RAD,45.0f*DEG2RAD,\n\t\t-35.0f*DEG2RAD,45.0f*DEG2RAD,-20.0f*DEG2RAD,20.0f*DEG2RAD,-10.0f*DEG2RAD,10.0f*DEG2RAD,\n\n\t\t//left leg\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t-30.0f*DEG2RAD,110.0f*DEG2RAD,-90.0f*DEG2RAD,90.0f*DEG2RAD,-90.0f*DEG2RAD,110.0f*DEG2RAD,\n\t\t-130.0f*DEG2RAD,20.0f*DEG2RAD,-35.0f*DEG2RAD,25.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t-50.0f*DEG2RAD,50.0f*DEG2RAD,-3.0f*DEG2RAD,30.0f*DEG2RAD,-45.0f*DEG2RAD,45.0f*DEG2RAD,\n\t\t-35.0f*DEG2RAD,45.0f*DEG2RAD,-20.0f*DEG2RAD,20.0f*DEG2RAD,-10.0f*DEG2RAD,10.0f*DEG2RAD,\n\n\t\t//head to mouth\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t//head to leye\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t//head to reye\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t//neck to lclavicle\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t//neck to rclavicle\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t//jaw\n\t\t-30.0f*DEG2RAD,0.0f*DEG2RAD,-1.0f*DEG2RAD,1.0f*DEG2RAD,-20.0f*DEG2RAD,20.0f*DEG2RAD,\n\t\t//leye\n\t\t-50.0f*DEG2RAD,30.0f*DEG2RAD,-30.0f*DEG2RAD,30.0f*DEG2RAD,-35.0f*DEG2RAD,30.0f*DEG2RAD,\n\t\t//reye\n\t\t-50.0f*DEG2RAD,30.0f*DEG2RAD,-30.0f*DEG2RAD,30.0f*DEG2RAD,-30.0f*DEG2RAD,35.0f*DEG2RAD,\n\t\t//llid\n\t\t-25.0f*DEG2RAD,15.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,5.0f*DEG2RAD,\n\t\t-10.0f*DEG2RAD,5.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,5.0f*DEG2RAD,\n\t\t//rlid\n\t\t-25.0f*DEG2RAD,15.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-5.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t-5.0f*DEG2RAD,10.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-5.0f*DEG2RAD,0.0f*DEG2RAD,\n\n\t\t//rshoulder\n\t\t-45.0f*DEG2RAD,17.0f*DEG2RAD,-3.0f*DEG2RAD,3.0f*DEG2RAD,-16.0f*DEG2RAD,30.0f*DEG2RAD,\n\t\t-90.0f*DEG2RAD,90.0f*DEG2RAD,-110.0f*DEG2RAD,110.0f*DEG2RAD,-100.0f*DEG2RAD,70.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,130.0f*DEG2RAD,-40.0f*DEG2RAD,80.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t-45.0f*DEG2RAD,45.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-90.0f*DEG2RAD,90.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t-5.0f*DEG2RAD,50.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-35.0f*DEG2RAD,20.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,3.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,3.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,3.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,3.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t//lshoulder\n\t\t-17.0f*DEG2RAD,45.0f*DEG2RAD,-3.0f*DEG2RAD,3.0f*DEG2RAD,-16.0f*DEG2RAD,30.0f*DEG2RAD,\n\t\t-90.0f*DEG2RAD,90.0f*DEG2RAD,-110.0f*DEG2RAD,110.0f*DEG2RAD,-100.0f*DEG2RAD,70.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,130.0f*DEG2RAD,-80.0f*DEG2RAD,40.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t-45.0f*DEG2RAD,45.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-90.0f*DEG2RAD,90.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t-50.0f*DEG2RAD,5.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-35.0f*DEG2RAD,20.0f*DEG2RAD,\n\t\t-3.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t-3.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t-3.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t-3.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\n\t\t//rthumb\n\t\t-20.0f*DEG2RAD,50.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t-80.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t//\n\t\t-15.0f*DEG2RAD,15.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-75.0f*DEG2RAD,15.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-100.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-90.0f*DEG2RAD,0.0f*DEG2RAD,\n\n\t\t-15.0f*DEG2RAD,15.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-75.0f*DEG2RAD,15.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-100.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-90.0f*DEG2RAD,0.0f*DEG2RAD,\n\n\t\t-15.0f*DEG2RAD,15.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-75.0f*DEG2RAD,15.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-100.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-90.0f*DEG2RAD,0.0f*DEG2RAD,\n\n\t\t-15.0f*DEG2RAD,15.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-75.0f*DEG2RAD,15.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-100.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-90.0f*DEG2RAD,0.0f*DEG2RAD,\n\n\t\t//lthumb\n\t\t-50.0f*DEG2RAD,20.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,80.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\n\t\t-15.0f*DEG2RAD,15.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-75.0f*DEG2RAD,15.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-100.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-90.0f*DEG2RAD,0.0f*DEG2RAD,\n\n\t\t-15.0f*DEG2RAD,15.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-75.0f*DEG2RAD,15.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-100.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-90.0f*DEG2RAD,0.0f*DEG2RAD,\n\n\t\t//73 - problem with base\n\t\t-15.0f*DEG2RAD,15.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-75.0f*DEG2RAD,15.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-100.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-90.0f*DEG2RAD,0.0f*DEG2RAD,\n\n\t\t-15.0f*DEG2RAD,15.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-75.0f*DEG2RAD,15.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-100.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,-90.0f*DEG2RAD,0.0f*DEG2RAD,\n\n\t\t//tongue\n\t\t-60.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,0.0f*DEG2RAD,\n\t\t-20.0f*DEG2RAD,30.0f*DEG2RAD,-5.0f*DEG2RAD,5.0f*DEG2RAD,-20.0f*DEG2RAD,20.0f*DEG2RAD,\n\t\t-20.0f*DEG2RAD,30.0f*DEG2RAD,-5.0f*DEG2RAD,5.0f*DEG2RAD,-20.0f*DEG2RAD,20.0f*DEG2RAD,\n\t\t-20.0f*DEG2RAD,30.0f*DEG2RAD,-5.0f*DEG2RAD,5.0f*DEG2RAD,-20.0f*DEG2RAD,20.0f*DEG2RAD,\n\t};\n\t\n\tpublic static int[] bprnts=\n\t{\n\t\t-1,\n\t\t//0,\n\t\t0,\n\t\t1,\n\t\t2,\n\t\t3,\n\t\t4,\n\t\t0,\n\t\t6,\n\t\t7,\n\t\t8,\n\t\t9,\n\t\t0,\n\t\t11,\n\t\t12,\n\t\t13,\n\t\t14,\n\t\t5,\n\t\t5,\n\t\t5,\n\t\t3,\n\t\t3,\n\t\t5,\n\t\t5,\n\t\t5,\n\t\t5,\n\t\t5,\n\t\t5,\n\t\t5,\n\t\t3,\n\t\t28,\n\t\t29,\n\t\t30,\n\t\t31,\n\t\t31,\n\t\t31,\n\t\t32,\n\t\t32,\n\t\t33,\n\t\t33,\n\t\t3,\n\t\t39,\n\t\t40,\n\t\t41,\n\t\t42,\n\t\t42,\n\t\t42,\n\t\t43,\n\t\t43,\n\t\t44,\n\t\t44,\n\t\t34,\n\t\t50,\n\t\t51,\n\t\t35,\n\t\t53,\n\t\t54,\n\t\t36,\n\t\t56,\n\t\t57,\n\t\t37,\n\t\t59,\n\t\t60,\n\t\t38,\n\t\t62,\n\t\t63,\n\t\t45,\n\t\t65,\n\t\t66,\n\t\t46,\n\t\t68,\n\t\t69,\n\t\t47,\n\t\t71,\n\t\t72,\n\t\t48,\n\t\t74,\n\t\t75,\n\t\t49,\n\t\t77,\n\t\t78,\n\t\t21,\n\t\t21,\n\t\t81,\n\t\t82,\n\t};\n\t\n\tpublic static String[] snames=\n\t{\n\t\t\"joint-pelvistojoint-spine3\",\n\t\t//\"joint-spine3tojoint-pelvis\",\n\t\t\"joint-spine3tojoint-spine2\",\n\t\t\"joint-spine2tojoint-spine1\",\n\t\t\"joint-spine1tojoint-neck\",\n\t\t\"joint-necktojoint-head\",\n\t\t\"joint-headtojoint-head2\",\n\t\t\"joint-pelvistojoint-r-upper-leg\",\n\t\t\"joint-r-upper-legtojoint-r-knee\",\n\t\t\"joint-r-kneetojoint-r-ankle\",\n\t\t\"joint-r-ankletojoint-r-foot-1\",\n\t\t\"joint-r-foot-1tojoint-r-foot-2\",\n\t\t\"joint-pelvistojoint-l-upper-leg\",\n\t\t\"joint-l-upper-legtojoint-l-knee\",\n\t\t\"joint-l-kneetojoint-l-ankle\",\n\t\t\"joint-l-ankletojoint-l-foot-1\",\n\t\t\"joint-l-foot-1tojoint-l-foot-2\",\n\t\t\"joint-head2tojoint-mouth\",\n\t\t\"joint-head2tojoint-l-eye\",\n\t\t\"joint-head2tojoint-r-eye\",\n\t\t\"joint-necktojoint-l-clavicle\",\n\t\t\"joint-necktojoint-r-clavicle\",\n\t\t\"joint-mouthtojoint-jaw\",\n\t\t\"joint-l-eyetojoint-l-eye-target\",\n\t\t\"joint-r-eyetojoint-r-eye-target\",\n\t\t\"joint-l-eyetojoint-l-upperlid\",\n\t\t\"joint-l-eyetojoint-l-lowerlid\",\n\t\t\"joint-r-eyetojoint-r-upperlid\",\n\t\t\"joint-r-eyetojoint-r-lowerlid\",\n\t\t\"joint-r-clavicletojoint-r-shoulder\",\n\t\t\"joint-r-shouldertojoint-r-elbow\",\n\t\t\"joint-r-elbowtojoint-r-hand\",\n\t\t\"joint-r-handtojoint-r-finger-3-1\",\n\t\t\"joint-r-handtojoint-r-hand-3\",\n\t\t\"joint-r-handtojoint-r-hand-2\",\n\t\t\"joint-r-handtojoint-r-finger-1-1\",\n\t\t\"joint-r-hand-3tojoint-r-finger-2-1\",\n\t\t\"joint-r-hand-3tojoint-r-finger-3-1\",\n\t\t\"joint-r-hand-2tojoint-r-finger-4-1\",\n\t\t\"joint-r-hand-2tojoint-r-finger-5-1\",\n\t\t\"joint-l-clavicletojoint-l-shoulder\",\n\t\t\"joint-l-shouldertojoint-l-elbow\",\n\t\t\"joint-l-elbowtojoint-l-hand\",\n\t\t\"joint-l-handtojoint-l-finger-3-1\",\n\t\t\"joint-l-handtojoint-l-hand-3\",\n\t\t\"joint-l-handtojoint-l-hand-2\",\n\t\t\"joint-l-handtojoint-l-finger-1-1\",\n\t\t\"joint-l-hand-3tojoint-l-finger-2-1\",\n\t\t\"joint-l-hand-3tojoint-l-finger-3-1\",\n\t\t\"joint-l-hand-2tojoint-l-finger-4-1\",\n\t\t\"joint-l-hand-2tojoint-l-finger-5-1\",\n\t\t\"joint-r-finger-1-1tojoint-r-finger-1-2\",\n\t\t\"joint-r-finger-1-2tojoint-r-finger-1-3\",\n\t\t\"joint-r-finger-1-3tojoint-r-finger-1-4\",\n\t\t\"joint-r-finger-2-1tojoint-r-finger-2-2\",\n\t\t\"joint-r-finger-2-2tojoint-r-finger-2-3\",\n\t\t\"joint-r-finger-2-3tojoint-r-finger-2-4\",\n\t\t\"joint-r-finger-3-1tojoint-r-finger-3-2\",\n\t\t\"joint-r-finger-3-2tojoint-r-finger-3-3\",\n\t\t\"joint-r-finger-3-3tojoint-r-finger-3-4\",\n\t\t\"joint-r-finger-4-1tojoint-r-finger-4-2\",\n\t\t\"joint-r-finger-4-2tojoint-r-finger-4-3\",\n\t\t\"joint-r-finger-4-3tojoint-r-finger-4-4\",\n\t\t\"joint-r-finger-5-1tojoint-r-finger-5-2\",\n\t\t\"joint-r-finger-5-2tojoint-r-finger-5-3\",\n\t\t\"joint-r-finger-5-3tojoint-r-finger-5-4\",\n\t\t\"joint-l-finger-1-1tojoint-l-finger-1-2\",\n\t\t\"joint-l-finger-1-2tojoint-l-finger-1-3\",\n\t\t\"joint-l-finger-1-3tojoint-l-finger-1-4\",\n\t\t\"joint-l-finger-2-1tojoint-l-finger-2-2\",\n\t\t\"joint-l-finger-2-2tojoint-l-finger-2-3\",\n\t\t\"joint-l-finger-2-3tojoint-l-finger-2-4\",\n\t\t\"joint-l-finger-3-1tojoint-l-finger-3-2\",\n\t\t\"joint-l-finger-3-2tojoint-l-finger-3-3\",\n\t\t\"joint-l-finger-3-3tojoint-l-finger-3-4\",\n\t\t\"joint-l-finger-4-1tojoint-l-finger-4-2\",\n\t\t\"joint-l-finger-4-2tojoint-l-finger-4-3\",\n\t\t\"joint-l-finger-4-3tojoint-l-finger-4-4\",\n\t\t\"joint-l-finger-5-1tojoint-l-finger-5-2\",\n\t\t\"joint-l-finger-5-2tojoint-l-finger-5-3\",\n\t\t\"joint-l-finger-5-3tojoint-l-finger-5-4\",\n\t\t\"joint-jawtojoint-tongue-1\",\n\t\t\"joint-tongue-1tojoint-tongue-2\",\n\t\t\"joint-tongue-2tojoint-tongue-3\",\n\t\t\"joint-tongue-3tojoint-tongue-4\",\n\t};\n\t\n\tpublic static final int BONE_HipstoChest0=0;\n\t//\"Hips=;\n\tpublic static final int BONE_HipstoChest1=1;\n\tpublic static final int BONE_HipstoChest2=2;\n\tpublic static final int BONE_ChesttoNeck=3;\n\tpublic static final int BONE_NecktoHead=4;\n\tpublic static final int BONE_HeadtoHeadend=5;\n\tpublic static final int BONE_Hip_L=6;\n\tpublic static final int BONE_LeftUpLegtoLeftLowLeg=7;\n\tpublic static final int BONE_LeftLowLegtoLeftFoot=8;\n\tpublic static final int BONE_LeftFoottoLeftFootend=9;\n\tpublic static final int BONE_Toe_L=10;\n\tpublic static final int BONE_Hip_R=11;\n\tpublic static final int BONE_RightUpLegtoRightLowLeg=12;\n\tpublic static final int BONE_RightLowLegtoRightFoot=13;\n\tpublic static final int BONE_RightFoottoRightFootend=14;\n\tpublic static final int BONE_Toe_R=15;\n\tpublic static final int BONE_HeadtoMouth=16;\n\tpublic static final int BONE_HeadtoLEye=17;\n\tpublic static final int BONE_HeadtoREye=18;\n\tpublic static final int BONE_Spine3toLClavicle=19;\n\tpublic static final int BONE_Spine3toRClavicle=20;\n\tpublic static final int BONE_Jaw=21;\n\tpublic static final int BONE_Eye_R=22;\n\tpublic static final int BONE_Eye_L=23;\n\tpublic static final int BONE_UpLid_R=24;\n\tpublic static final int BONE_LoLid_R=25;\n\tpublic static final int BONE_UpLid_L=26;\n\tpublic static final int BONE_LoLid_L=27;\n\tpublic static final int BONE_LeftCollartoLeftUpArm=28;\n\tpublic static final int BONE_LeftUpArmtoLeftLowArm=29;\n\tpublic static final int BONE_LeftLowArmtoLeftHand=30;\n\tpublic static final int BONE_LeftHandtoLeftHandend=31;\n\tpublic static final int BONE_Wrist_1_L=32;\n\tpublic static final int BONE_Wrist_2_L=33;\n\tpublic static final int BONE_Palm_1_L=34;\n\tpublic static final int BONE_Palm_2_L=35;\n\tpublic static final int BONE_Palm_3_L=36;\n\tpublic static final int BONE_Palm_4_L=37;\n\tpublic static final int BONE_Palm_5_L=38;\n\tpublic static final int BONE_RightCollartoRightUpArm=39;\n\tpublic static final int BONE_RightUpArmtoRightLowArm=40;\n\tpublic static final int BONE_RightLowArmtoRightHand=41;\n\tpublic static final int BONE_RightHandtoRightHandend=42;\n\tpublic static final int BONE_Wrist_1_R=43;\n\tpublic static final int BONE_Wrist_2_R=44;\n\tpublic static final int BONE_Palm_1_R=45;\n\tpublic static final int BONE_Palm_2_R=46;\n\tpublic static final int BONE_Palm_3_R=47;\n\tpublic static final int BONE_Palm_4_R=48;\n\tpublic static final int BONE_Palm_5_R=49;\n\tpublic static final int BONE_Finger_1_1_L=50;\n\tpublic static final int BONE_Finger_1_2_L=51;\n\tpublic static final int BONE_Finger_1_3_L=52;\n\tpublic static final int BONE_Finger_2_1_L=53;\n\tpublic static final int BONE_Finger_2_2_L=54;\n\tpublic static final int BONE_Finger_2_3_L=55;\n\tpublic static final int BONE_Finger_3_1_L=56;\n\tpublic static final int BONE_Finger_3_2_L=57;\n\tpublic static final int BONE_Finger_3_3_L=58;\n\tpublic static final int BONE_Finger_4_1_L=59;\n\tpublic static final int BONE_Finger_4_2_L=60;\n\tpublic static final int BONE_Finger_4_3_L=61;\n\tpublic static final int BONE_Finger_5_1_L=62;\n\tpublic static final int BONE_Finger_5_2_L=63;\n\tpublic static final int BONE_Finger_5_3_L=64;\n\tpublic static final int BONE_Finger_1_1_R=65;\n\tpublic static final int BONE_Finger_1_2_R=66;\n\tpublic static final int BONE_Finger_1_3_R=67;\n\tpublic static final int BONE_Finger_2_1_R=68;\n\tpublic static final int BONE_Finger_2_2_R=69;\n\tpublic static final int BONE_Finger_2_3_R=70;\n\tpublic static final int BONE_Finger_3_1_R=71;\n\tpublic static final int BONE_Finger_3_2_R=72;\n\tpublic static final int BONE_Finger_3_3_R=73;\n\tpublic static final int BONE_Finger_4_1_R=74;\n\tpublic static final int BONE_Finger_4_2_R=75;\n\tpublic static final int BONE_Finger_4_3_R=76;\n\tpublic static final int BONE_Finger_5_1_R=77;\n\tpublic static final int BONE_Finger_5_2_R=78;\n\tpublic static final int BONE_Finger_5_3_R=79;\n\tpublic static final int BONE_JawtoTongue=80;\n\tpublic static final int BONE_TongueBase=81;\n\tpublic static final int BONE_TongueMid=82;\n\tpublic static final int BONE_TongueTip=83;\n\t\n\t\n\tpublic static String[] names=\n\t{\n\t\t\"HipstoChest0\",\n\t\t//\"Hips\",\n\t\t\"HipstoChest1\",\n\t\t\"HipstoChest2\",\n\t\t\"ChesttoNeck\",\n\t\t\"NecktoHead\",\n\t\t\"HeadtoHeadend\",\n\t\t\"Hip_L\",\n\t\t\"LeftUpLegtoLeftLowLeg\",\n\t\t\"LeftLowLegtoLeftFoot\",\n\t\t\"LeftFoottoLeftFootend\",\n\t\t\"Toe_L\",\n\t\t\"Hip_R\",\n\t\t\"RightUpLegtoRightLowLeg\",\n\t\t\"RightLowLegtoRightFoot\",\n\t\t\"RightFoottoRightFootend\",\n\t\t\"Toe_R\",\n\t\t\"HeadtoMouth\",\n\t\t\"HeadtoLEye\",\n\t\t\"HeadtoREye\",\n\t\t\"Spine3toLClavicle\",\n\t\t\"Spine3toRClavicle\",\n\t\t\"Jaw\",\n\t\t\"Eye_R\",\n\t\t\"Eye_L\",\n\t\t\"UpLid_R\",\n\t\t\"LoLid_R\",\n\t\t\"UpLid_L\",\n\t\t\"LoLid_L\",\n\t\t\"LeftCollartoLeftUpArm\",\n\t\t\"LeftUpArmtoLeftLowArm\",\n\t\t\"LeftLowArmtoLeftHand\",\n\t\t\"LeftHandtoLeftHandend\",\n\t\t\"Wrist-1_L\",\n\t\t\"Wrist-2_L\",\n\t\t\"Palm-1_L\",\n\t\t\"Palm-2_L\",\n\t\t\"Palm-3_L\",\n\t\t\"Palm-4_L\",\n\t\t\"Palm-5_L\",\n\t\t\"RightCollartoRightUpArm\",\n\t\t\"RightUpArmtoRightLowArm\",\n\t\t\"RightLowArmtoRightHand\",\n\t\t\"RightHandtoRightHandend\",\n\t\t\"Wrist-1_R\",\n\t\t\"Wrist-2_R\",\n\t\t\"Palm-1_R\",\n\t\t\"Palm-2_R\",\n\t\t\"Palm-3_R\",\n\t\t\"Palm-4_R\",\n\t\t\"Palm-5_R\",\n\t\t\"Finger-1-1_L\",\n\t\t\"Finger-1-2_L\",\n\t\t\"Finger-1-3_L\",\n\t\t\"Finger-2-1_L\",\n\t\t\"Finger-2-2_L\",\n\t\t\"Finger-2-3_L\",\n\t\t\"Finger-3-1_L\",\n\t\t\"Finger-3-2_L\",\n\t\t\"Finger-3-3_L\",\n\t\t\"Finger-4-1_L\",\n\t\t\"Finger-4-2_L\",\n\t\t\"Finger-4-3_L\",\n\t\t\"Finger-5-1_L\",\n\t\t\"Finger-5-2_L\",\n\t\t\"Finger-5-3_L\",\n\t\t\"Finger-1-1_R\",\n\t\t\"Finger-1-2_R\",\n\t\t\"Finger-1-3_R\",\n\t\t\"Finger-2-1_R\",\n\t\t\"Finger-2-2_R\",\n\t\t\"Finger-2-3_R\",\n\t\t\"Finger-3-1_R\",\n\t\t\"Finger-3-2_R\",\n\t\t\"Finger-3-3_R\",\n\t\t\"Finger-4-1_R\",\n\t\t\"Finger-4-2_R\",\n\t\t\"Finger-4-3_R\",\n\t\t\"Finger-5-1_R\",\n\t\t\"Finger-5-2_R\",\n\t\t\"Finger-5-3_R\",\n\t\t\"JawtoTongue\",\n\t\t\"TongueBase\",\n\t\t\"TongueMid\",\n\t\t\"TongueTip\",\n\t};\n\t\n\tpublic static int[] mirror =\n\t{\n\t\t-1,\n\t\t//\"Hips\",\n\t\t-1,\n\t\t-1,\n\t\t-1,\n\t\t-1,\n\t\t-1,\n\t\tBONE_Hip_R,\n\t\tBONE_RightUpLegtoRightLowLeg,\n\t\tBONE_RightLowLegtoRightFoot,\n\t\tBONE_RightFoottoRightFootend,\n\t\tBONE_Toe_R,\n\t\tBONE_Hip_L,\n\t\tBONE_LeftUpLegtoLeftLowLeg,\n\t\tBONE_LeftLowLegtoLeftFoot,\n\t\tBONE_LeftFoottoLeftFootend,\n\t\tBONE_Toe_L,\n\t\t-1,\n\t\tBONE_HeadtoREye,\n\t\tBONE_HeadtoLEye,\n\t\tBONE_Spine3toRClavicle,\n\t\tBONE_Spine3toLClavicle,\n\t\t-1,\n\t\tBONE_Eye_L,\n\t\tBONE_Eye_R,\n\t\tBONE_UpLid_L,\n\t\tBONE_LoLid_L,\n\t\tBONE_UpLid_R,\n\t\tBONE_LoLid_R,\n\t\tBONE_RightCollartoRightUpArm,\n\t\tBONE_RightUpArmtoRightLowArm,\n\t\tBONE_RightLowArmtoRightHand,\n\t\tBONE_RightHandtoRightHandend,\n\t\tBONE_Wrist_1_R,\n\t\tBONE_Wrist_2_R,\n\t\tBONE_Palm_1_R,\n\t\tBONE_Palm_2_R,\n\t\tBONE_Palm_3_R,\n\t\tBONE_Palm_4_R,\n\t\tBONE_Palm_5_R,\n\t\tBONE_LeftCollartoLeftUpArm,\n\t\tBONE_LeftUpArmtoLeftLowArm,\n\t\tBONE_LeftLowArmtoLeftHand,\n\t\tBONE_LeftHandtoLeftHandend,\n\t\tBONE_Wrist_1_L,\n\t\tBONE_Wrist_2_L,\n\t\tBONE_Palm_1_L,\n\t\tBONE_Palm_2_L,\n\t\tBONE_Palm_3_L,\n\t\tBONE_Palm_4_L,\n\t\tBONE_Palm_5_L,\n\t\tBONE_Finger_1_1_R,\n\t\tBONE_Finger_1_2_R,\n\t\tBONE_Finger_1_3_R,\n\t\tBONE_Finger_2_1_R,\n\t\tBONE_Finger_2_2_R,\n\t\tBONE_Finger_2_3_R,\n\t\tBONE_Finger_3_1_R,\n\t\tBONE_Finger_3_2_R,\n\t\tBONE_Finger_3_3_R,\n\t\tBONE_Finger_4_1_R,\n\t\tBONE_Finger_4_2_R,\n\t\tBONE_Finger_4_3_R,\n\t\tBONE_Finger_5_1_R,\n\t\tBONE_Finger_5_2_R,\n\t\tBONE_Finger_5_3_R,\n\t\tBONE_Finger_1_1_L,\n\t\tBONE_Finger_1_2_L,\n\t\tBONE_Finger_1_3_L,\n\t\tBONE_Finger_2_1_L,\n\t\tBONE_Finger_2_2_L,\n\t\tBONE_Finger_2_3_L,\n\t\tBONE_Finger_3_1_L,\n\t\tBONE_Finger_3_2_L,\n\t\tBONE_Finger_3_3_L,\n\t\tBONE_Finger_4_1_L,\n\t\tBONE_Finger_4_2_L,\n\t\tBONE_Finger_4_3_L,\n\t\tBONE_Finger_5_1_L,\n\t\tBONE_Finger_5_2_L,\n\t\tBONE_Finger_5_3_L,\n\t\t-1,\n\t\t-1,\n\t\t-1,\n\t\t-1,\n\t};\n}" ]
import utils.GeneralMatrixDouble; import utils.GeneralMatrixFloat; import utils.GeneralMatrixInt; import utils.GeneralMatrixObject; import utils.GeneralMatrixString; import utils.Quaternion; import utils.shapes.human.HumanBones;
pbmat.width = 9; pbmat.height = 1; pbmat.setFromSubset(bmats, pbi); pbmat.width = 3; pbmat.height = 3; } //Calc inverse GeneralMatrixDouble.transpose(pbmat, pbmati); //calc the local matrix //calc the local bmat bmatl.width = 3; bmatl.height = 3; GeneralMatrixDouble.mult(bmat, pbmati, bmatl); //Now need to calc the inverse of the localbindmat //and compose to get the relative localmat bmat.width = 9; bmat.height = 1; bmat.setFromSubset(localbindbmats, bi); bmat.width = 3; bmat.height = 3; GeneralMatrixDouble.transpose(bmat, pbmati); GeneralMatrixDouble.mult(bmatl, pbmati, bmat); GeneralMatrixDouble.getEulerYXZ(bmat, euler); //now lets get the props from the params params.setRow(bi+1,euler); for(int li=0;li<3;li++) { int lind = bi*3+3+li; if(params.value[lind]<localboneangleLimits.value[6*bi+li*2]) { float dl = Math.abs(params.value[lind]-localboneangleLimits.value[6*bi+li*2+0]); totalerror += dl; params.value[lind] = localboneangleLimits.value[6*bi+li*2]; } if(params.value[lind]>localboneangleLimits.value[6*bi+li*2+1]) { float dl = Math.abs(params.value[lind]-localboneangleLimits.value[6*bi+li*2+1]); totalerror += dl; params.value[lind] = localboneangleLimits.value[6*bi+li*2+1]; } } } return totalerror; } public static String calcLocalRotationParams( GeneralMatrixInt bones, GeneralMatrixInt boneParents, GeneralMatrixInt boneUpdateOrder, GeneralMatrixFloat bmats, GeneralMatrixFloat localbindbmats, GeneralMatrixFloat localboneangleLimits, GeneralMatrixFloat params, GeneralMatrixString plog ) { float totalerror = 0.0f; params.setDimensions(3, bones.height+1); //Go through the bones and calculate their starting local mats (deformations are relative to this) for(int ubi=0;ubi<bones.height;ubi++) { int bi = ubi; if(boneUpdateOrder!=null) bi = boneUpdateOrder.value[ubi]; int pbi = boneParents.value[bi]; bmat.width = 9; bmat.height = 1; bmat.setFromSubset(bmats, bi); bmat.width = 3; bmat.height = 3; if(pbi==-1) { pbmat.width = 3; pbmat.height = 3; pbmat.setIdentity(); } else { pbmat.width = 9; pbmat.height = 1; pbmat.setFromSubset(bmats, pbi); pbmat.width = 3; pbmat.height = 3; } //Calc inverse GeneralMatrixDouble.transpose(pbmat, pbmati); //calc the local matrix //calc the local bmat bmatl.width = 3; bmatl.height = 3; GeneralMatrixDouble.mult(bmat, pbmati, bmatl); //Now need to calc the inverse of the localbindmat //and compose to get the relative localmat bmat.width = 9; bmat.height = 1; bmat.setFromSubset(localbindbmats, bi); bmat.width = 3; bmat.height = 3; GeneralMatrixDouble.transpose(bmat, pbmati); GeneralMatrixDouble.mult(bmatl, pbmati, bmat); GeneralMatrixDouble.getEulerYXZ(bmat, euler); //now lets get the props from the params params.setRow(bi+1,euler); for(int li=0;li<3;li++) { int lind = bi*3+3+li; if(params.value[lind]<localboneangleLimits.value[6*bi+li*2]) { float dl = Math.abs(params.value[lind]-localboneangleLimits.value[6*bi+li*2+0]); if(dl>0.01f)
plog.value[0] += ""+HumanBones.snames[bi]+":"+li+":"+dl+":"+params.value[lind]/HumanBones.DEG2RAD+"\n";
6
zqingyang521/qingyang
QingYangDemo/src/com/example/qingyangdemo/SettingActivity.java
[ "public class AppManager {\n\n\t// activity的堆栈\n\tprivate static Stack<Activity> activityStack;\n\n\tprivate static AppManager instance;\n\n\t/**\n\t * 单例\n\t */\n\tpublic static AppManager getAppManager() {\n\n\t\tif (instance == null) {\n\t\t\tinstance = new AppManager();\n\t\t}\n\t\treturn instance;\n\n\t}\n\n\t/**\n\t * 添加activity到堆栈\n\t * \n\t * @param activity\n\t */\n\tpublic void addActivity(Activity activity) {\n\n\t\tif (activityStack == null) {\n\t\t\tactivityStack = new Stack<Activity>();\n\t\t}\n\t\tactivityStack.add(activity);\n\t}\n\n\t/**\n\t * 获取当前activity(堆栈中最后一个压入的activity)\n\t * \n\t * @return\n\t */\n\tpublic Activity currentActivity() {\n\t\tActivity activity = activityStack.lastElement();\n\t\treturn activity;\n\t}\n\n\t/**\n\t * 结束当前的activity(堆栈中最后一个压入的activity)\n\t */\n\tpublic void finishActivity() {\n\t\tActivity activity = activityStack.lastElement();\n\n\t\tfinishActivity(activity);\n\t}\n\n\t/**\n\t * 结束指定的activity\n\t */\n\tpublic void finishActivity(Activity activity) {\n\n\t\tif (activity != null) {\n\t\t\tactivityStack.remove(activity);\n\t\t\tactivity.finish();\n\t\t\tactivity = null;\n\t\t}\n\t}\n\n\t/**\n\t * 结束所有的activity\n\t */\n\tpublic void finishAllActivity() {\n\n\t\tfor (int i = 0, size = activityStack.size(); i < size; i++) {\n\t\t\tif (activityStack.get(i) != null) {\n\t\t\t\tactivityStack.get(i).finish();\n\t\t\t}\n\t\t}\n\n\t\tactivityStack.clear();\n\n\t}\n\n\t/**\n\t * 退出应用程序\n\t * \n\t * @param context\n\t */\n\tpublic void AppExit(Context context) {\n\n\t\tfinishAllActivity();\n\n\t\tActivityManager activityManager = (ActivityManager) context\n\t\t\t\t.getSystemService(Context.ACTIVITY_SERVICE);\n\n\t\t// // 2.2之前的rom就用restartPackage之后的就用killBackgroundProcesses\n\t\tif (BaseApplication.isMethodsCompat(Build.VERSION_CODES.FROYO)) {\n\t\t\tactivityManager.killBackgroundProcesses(context.getPackageName());\n\t\t} else {\n\n\t\t\tactivityManager.restartPackage(context.getPackageName());\n\t\t}\n\n\t\tSystem.exit(0);\n\t}\n}", "public class BaseApplication extends Application {\n\n\t// wifi状态 联通状态 移动状态\n\tprivate static int NETTYPE_WIFI = 0x01;\n\tprivate static int NETTYPE_CMWAP = 0x02;\n\tprivate static int NETTYPE_CMNET = 0x03;\n\n\t// 登陆状态\n\tprivate boolean login = false;\n\n\t// 登陆的ID\n\tprivate int loginUnid;\n\n\t@Override\n\tpublic void onCreate() {\n\t\tsuper.onCreate();\n\n\t\t// 注册app异常崩溃处理器\n\t\tThread.setDefaultUncaughtExceptionHandler(AppException\n\t\t\t\t.getAppExceptionHandler());\n\t};\n\n\t/**\n\t * 现在翻转屏是否是横向的\n\t * \n\t * @return\n\t */\n\tpublic boolean isLandscape() {\n\t\tConfiguration config = getResources().getConfiguration();\n\n\t\tif (config.orientation == Configuration.ORIENTATION_PORTRAIT) {\n\t\t\treturn false;\n\t\t} else if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * 是否是平板登陆\n\t * \n\t * @return\n\t */\n\tpublic boolean isTablet() {\n\n\t\treturn getResources().getBoolean(R.bool.isTablet);\n\t}\n\n\t/**\n\t * 检测网络是否可用\n\t * \n\t * @return\n\t */\n\tpublic boolean isNetworkConnected() {\n\t\tConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);\n\t\tNetworkInfo ni = cm.getActiveNetworkInfo();\n\t\treturn ni != null && ni.isConnectedOrConnecting();\n\t}\n\n\t/**\n\t * 获取当前网络类型\n\t * \n\t * @return 0:没有网络 1:wifi网络 2:wap网络 3:net网络\n\t */\n\tpublic int getNetworkType() {\n\t\tint netType = 0;\n\n\t\tConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);\n\n\t\tNetworkInfo ni = cm.getActiveNetworkInfo();\n\n\t\tif (ni == null) {\n\t\t\treturn netType;\n\t\t}\n\n\t\tint nType = ni.getType();\n\n\t\tif (nType == ConnectivityManager.TYPE_MOBILE) {\n\t\t\tString extraInfo = ni.getExtraInfo();\n\t\t\tif (!StringUtil.isEmpty(extraInfo)) {\n\t\t\t\t// 如果小写等于cmnet\n\t\t\t\tif (extraInfo.toLowerCase().equals(\"cmnet\")) {\n\t\t\t\t\tnetType = NETTYPE_CMNET;\n\t\t\t\t} else {\n\t\t\t\t\tnetType = NETTYPE_CMWAP;\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (nType == ConnectivityManager.TYPE_WIFI) {\n\t\t\tnetType = NETTYPE_WIFI;\n\t\t}\n\n\t\treturn netType;\n\t}\n\n\t/**\n\t * 判断当前版本是否兼容目标版本的方法\n\t * \n\t * @param versionCode\n\t * @return\n\t */\n\tpublic static boolean isMethodsCompat(int versionCode) {\n\t\tint currentVersion = Build.VERSION.SDK_INT;\n\t\treturn currentVersion >= versionCode;\n\t}\n\n\t/**\n\t * 获取app安装包信息\n\t * \n\t * @return\n\t */\n\tpublic PackageInfo getPackageInfo() {\n\t\tPackageInfo info = null;\n\n\t\ttry {\n\t\t\tinfo = getPackageManager().getPackageInfo(getPackageName(), 0);\n\t\t} catch (NameNotFoundException e) {\n\t\t\te.printStackTrace(System.err);\n\t\t}\n\n\t\tif (info == null)\n\t\t\tinfo = new PackageInfo();\n\n\t\treturn info;\n\t}\n\n\t/**\n\t * 是否发出提示音\n\t * \n\t * @return\n\t */\n\tpublic boolean isVoice() {\n\t\tString perf_voice = getProperty(AppConfig.CONF_VOICE);\n\n\t\t// 默认是开启提示声音\n\t\tif (StringUtil.isEmpty(perf_voice))\n\t\t\treturn true;\n\t\telse\n\t\t\treturn StringUtil.toBool(perf_voice);\n\n\t}\n\n\t/**\n\t * 设置提示音\n\t * \n\t * @return\n\t */\n\tpublic void setConfigVoice(boolean b) {\n\t\tsetProperty(AppConfig.CONF_VOICE, String.valueOf(b));\n\t}\n\n\t/**\n\t * 设置ip地址\n\t * \n\t * @return\n\t */\n\tpublic void setIpAdress(String ipAdress) {\n\t\tsetProperty(AppConfig.CONF_IP_ADDRESS, ipAdress);\n\t}\n\n\t/**\n\t * 是否检查更新\n\t * \n\t * @return\n\t */\n\tpublic boolean isCheckUp() {\n\t\tString perf_checkup = getProperty(AppConfig.CONF_CHECKUP);\n\n\t\t// 默认是关闭的\n\t\tif (StringUtil.isEmpty(perf_checkup))\n\t\t\treturn false;\n\t\telse\n\t\t\treturn StringUtil.toBool(perf_checkup);\n\t}\n\n\t/**\n\t * 获取ip地址\n\t * \n\t * @return\n\t */\n\tpublic String getIpAdress() {\n\t\tString ip_adress = getProperty(AppConfig.CONF_IP_ADDRESS);\n\n\t\tif (StringUtil.isEmpty(ip_adress))\n\t\t\treturn \"0.0.0.0\";\n\t\telse\n\t\t\treturn ip_adress;\n\t}\n\n\t/**\n\t * 设置是否启动检查更新\n\t * \n\t * @param b\n\t */\n\tpublic void setConfigCheckUp(boolean b) {\n\t\tsetProperty(AppConfig.CONF_CHECKUP, String.valueOf(b));\n\t}\n\n\t/**\n\t * 获取App的唯一标识并保存到配置中\n\t * \n\t * @return\n\t */\n\tpublic String getAppId() {\n\t\tString uniqueId = getProperty(AppConfig.CON_APP_UNIQUEID);\n\n\t\tif (StringUtil.isEmpty(uniqueId)) {\n\t\t\tuniqueId = UUID.randomUUID().toString();\n\t\t\tsetProperty(AppConfig.CON_APP_UNIQUEID, uniqueId);\n\t\t}\n\t\treturn uniqueId;\n\t}\n\n\t/**\n\t * 初始化用户信息\n\t */\n\tpublic void initLoginInfo() {\n\t\tUser user = getLoginInfo();\n\t\tif (user != null && user.getUid() > 0 && user.isRememberMe()) {\n\t\t\tthis.login = true;\n\t\t\tthis.loginUnid = user.getUid();\n\t\t} else {\n\t\t\tthis.layout();\n\t\t}\n\t}\n\n\t/**\n\t * 用户是否登录\n\t * \n\t * @return\n\t */\n\tpublic boolean isLogin() {\n\t\treturn login;\n\t}\n\n\t/**\n\t * 获取登录用户id\n\t * \n\t * @return\n\t */\n\tpublic int getLoginUid() {\n\t\treturn this.loginUnid;\n\t}\n\n\t/**\n\t * 用户注销\n\t */\n\tpublic void layout() {\n\t\tlogin = false;\n\t\tloginUnid = 0;\n\t}\n\n\t/**\n\t * 清除登录信息\n\t */\n\tpublic void cleanLoginInfo() {\n\t\tlayout();\n\t\tremoveProperty(\"user.uid\", \"user.name\", \"user.password\",\n\t\t\t\t\"user.isRememberMe\");\n\t}\n\n\t/**\n\t * 获取登录信息\n\t * \n\t * @return\n\t */\n\tpublic User getLoginInfo() {\n\t\tUser user = new User();\n\t\tuser.setUid(StringUtil.toInt(getProperty(\"user.uid\"), 0));\n\t\tuser.setName(getProperty(\"user.name\"));\n\t\tuser.setRememberMe(StringUtil.toBool(getProperty(\"user.isRememberMe\")));\n\t\tuser.setPassword(getProperty(\"user.password\"));\n\t\treturn user;\n\t}\n\n\t/**\n\t * 保存用户信息\n\t * \n\t * @param user\n\t */\n\tpublic void saveLoginInfo(final User user) {\n\t\tthis.loginUnid = user.getUid();\n\t\tthis.login = true;\n\t\tsetProperties(new Properties() {\n\t\t\t{\n\t\t\t\tsetProperty(\"user.uid\", String.valueOf(user.getUid()));\n\t\t\t\tsetProperty(\"user.name\", user.getName());\n\t\t\t\tsetProperty(\"user.password\", user.getPassword());\n\t\t\t\tsetProperty(\"user.isRememberMe\",\n\t\t\t\t\t\tString.valueOf(user.isRememberMe()));\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic boolean containsProperty(String key) {\n\t\tProperties properties = getProperties();\n\t\treturn properties.containsKey(key);\n\t}\n\n\t/**\n\t * 获取配置集合\n\t * \n\t * @return\n\t */\n\tpublic Properties getProperties() {\n\t\treturn AppConfig.getAppConfig(this).get();\n\t}\n\n\tpublic void setProperties(Properties properties) {\n\t\tAppConfig.getAppConfig(this).set(properties);\n\t}\n\n\tpublic void setProperty(String key, String value) {\n\t\tAppConfig.getAppConfig(this).set(key, value);\n\t}\n\n\tpublic String getProperty(String key) {\n\t\treturn AppConfig.getAppConfig(this).get(key);\n\t}\n\n\tpublic void removeProperty(String... key) {\n\t\tAppConfig.getAppConfig(this).remove(key);\n\t}\n\n\t/**\n\t * 清除缓存\n\t */\n\tpublic void clearAppCache() {\n\t\t// 清除webview缓存\n\t\tFile file = CacheManager.getCacheFileBaseDir();\n\t\tif (file != null && file.exists() && file.isDirectory()) {\n\t\t\tfor (File item : file.listFiles()) {\n\t\t\t\titem.delete();\n\t\t\t}\n\t\t\tfile.delete();\n\t\t}\n\n\t\tdeleteDatabase(\"webview.db\");\n\t\tdeleteDatabase(\"webview.db-shm\");\n\t\tdeleteDatabase(\"webview.db-wal\");\n\t\tdeleteDatabase(\"webviewCache.db\");\n\t\tdeleteDatabase(\"webviewCache.db-shm\");\n\t\tdeleteDatabase(\"webviewCache.db-wal\");\n\n\t\t// 清除数据缓存\n\t\tclearCacheFolder(getFilesDir(), System.currentTimeMillis());\n\t\tclearCacheFolder(getCacheDir(), System.currentTimeMillis());\n\n\t\t// 2.2版本才有将应用缓存转移到sd卡的功能\n\t\tif (isMethodsCompat(android.os.Build.VERSION_CODES.FROYO)) {\n\t\t\tclearCacheFolder(getExternalCacheDir(), System.currentTimeMillis());\n\t\t}\n\t\t// 清楚编辑器保存的临时文件\n\t\tProperties props = getProperties();\n\n\t\tfor (Object key : props.keySet()) {\n\t\t\tString _key = key.toString();\n\t\t\tif (_key.startsWith(\"temp\"))\n\t\t\t\tremoveProperty(_key);\n\t\t}\n\t}\n\n\t/**\n\t * 清除下载缓存\n\t */\n\tpublic void clearDownCache() {\n\t\t// 清除下载缓存\n\t\tFile file = FileUtil.getDirectoryFile(Constant.DOWN_PATH);\n\t\tif (file != null && file.exists() && file.isDirectory()) {\n\t\t\tfor (File item : file.listFiles()) {\n\t\t\t\titem.delete();\n\t\t\t}\n\t\t\tfile.delete();\n\t\t}\n\t}\n\n\t/**\n\t * 清除缓存目录\n\t * \n\t * @param dir\n\t * 目录\n\t * @param curTime\n\t * 当前系统时间\n\t * @return\n\t */\n\tprivate int clearCacheFolder(File dir, long curTime) {\n\t\tint deletedFiles = 0;\n\n\t\tif (dir != null && dir.isDirectory()) {\n\t\t\ttry {\n\t\t\t\tfor (File child : dir.listFiles()) {\n\t\t\t\t\tif (child.isDirectory()) {\n\t\t\t\t\t\tdeletedFiles += clearCacheFolder(child, curTime);\n\t\t\t\t\t}\n\t\t\t\t\t// 如果文件的最后修改时间小于当前系统时间\n\t\t\t\t\tif (child.lastModified() < curTime) {\n\t\t\t\t\t\t// 删除\n\t\t\t\t\t\tif (child.delete()) {\n\t\t\t\t\t\t\tdeletedFiles++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (Exception e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\treturn deletedFiles;\n\t}\n\n\t/**\n\t * 用户登录验证\n\t * \n\t * @param userName\n\t * @param pwd\n\t * @return\n\t * @throws AppException\n\t */\n\tpublic User loginVerify(String userName, String pwd) throws AppException {\n\t\treturn NetClient.login(this, userName, pwd);\n\t}\n}", "public class FileUtil {\n\n\t/**\n\t * 计算目录大小\n\t * \n\t * @param dir\n\t * @return\n\t */\n\tpublic static long getDirSize(File dir) {\n\t\tif (dir == null) {\n\t\t\treturn 0;\n\t\t}\n\t\t// 不是目录\n\t\tif (!dir.isDirectory()) {\n\t\t\treturn 0;\n\t\t}\n\t\tlong dirSize = 0;\n\n\t\tFile[] files = dir.listFiles();\n\n\t\tfor (File file : files) {\n\t\t\tif (file.isFile()) {\n\t\t\t\tdirSize += file.length();\n\t\t\t} else if (file.isDirectory()) {\n\t\t\t\tdirSize += file.length();\n\t\t\t\t// 递归调用\n\t\t\t\tdirSize += getDirSize(file);\n\t\t\t}\n\n\t\t}\n\t\treturn dirSize;\n\t}\n\n\t/**\n\t * 转换文件大小\n\t * \n\t * @param fileS\n\t * @return B/KB/MB/GB\n\t */\n\tpublic static String formatFileSize(long fileS) {\n\n\t\tif (fileS == 0) {\n\t\t\treturn \"0.00B\";\n\t\t}\n\n\t\tDecimalFormat dFormat = new DecimalFormat(\"#.00\");\n\n\t\tString fileSizeString = \"\";\n\n\t\tif (fileS < 1024) {\n\t\t\tfileSizeString = dFormat.format((double) fileS) + \"B\";\n\t\t} else if (fileS < 1048576) {\n\t\t\tfileSizeString = dFormat.format((double) fileS / 1024) + \"KB\";\n\t\t} else if (fileS < 1073741824) {\n\t\t\tfileSizeString = dFormat.format((double) fileS / 1048576) + \"MB\";\n\t\t} else {\n\t\t\tfileSizeString = dFormat.format((double) fileS / 1073741824) + \"GB\";\n\t\t}\n\t\treturn fileSizeString;\n\t}\n\n\t/**\n\t * 文件目录地址\n\t * \n\t * @return\n\t */\n\tpublic static String fileDirectory(String dirPath, String fileName) {\n\t\tString filePath = \"\";\n\n\t\tString storageState = Environment.getExternalStorageState();\n\n\t\tif (storageState.equals(Environment.MEDIA_MOUNTED)) {\n\t\t\tfilePath = Environment.getExternalStorageDirectory()\n\t\t\t\t\t.getAbsolutePath() + dirPath;\n\n\t\t\tFile file = new File(filePath);\n\n\t\t\tif (!file.exists()) {\n\t\t\t\t// 建立一个新的目录\n\t\t\t\tfile.mkdirs();\n\t\t\t}\n\t\t\tfilePath = filePath + fileName;\n\t\t}\n\n\t\treturn filePath;\n\t}\n\n\t/**\n\t * 获取文件目录\n\t * \n\t * @return\n\t */\n\tpublic static File getDirectoryFile(String dirPath) {\n\n\t\tString storageState = Environment.getExternalStorageState();\n\n\t\tFile file = null;\n\n\t\tif (storageState.equals(Environment.MEDIA_MOUNTED)) {\n\t\t\tString filePath = Environment.getExternalStorageDirectory()\n\t\t\t\t\t.getAbsolutePath() + dirPath;\n\n\t\t\tfile = new File(filePath);\n\n\t\t\tif (!file.exists()) {\n\t\t\t\t// 建立一个新的目录\n\t\t\t\tfile.mkdirs();\n\t\t\t}\n\t\t}\n\n\t\treturn file;\n\t}\n\n\t/**\n\t * 检查文件后缀\n\t * \n\t * @param checkItsEnd\n\t * @param fileEndings\n\t * @return\n\t */\n\tprivate static boolean checkEndsWithInStringArray(String checkItsEnd,\n\t\t\tString[] fileEndings) {\n\t\tfor (String aEnd : fileEndings) {\n\t\t\tif (checkItsEnd.endsWith(aEnd))\n\t\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * 根据不同的后缀打开不同的文件\n\t * \n\t * @param fileName\n\t */\n\tpublic static void openFile(Context context, String fileName, File file) {\n\t\tIntent intent;\n\t\tif (checkEndsWithInStringArray(fileName, context.getResources()\n\t\t\t\t.getStringArray(R.array.fileEndingImage))) {\n\t\t\tintent = OpenFiles.getImageFileIntent(file);\n\t\t\tcontext.startActivity(intent);\n\t\t} else if (checkEndsWithInStringArray(fileName, context.getResources()\n\t\t\t\t.getStringArray(R.array.fileEndingWebText))) {\n\t\t\tintent = OpenFiles.getHtmlFileIntent(file);\n\t\t\tcontext.startActivity(intent);\n\t\t} else if (checkEndsWithInStringArray(fileName, context.getResources()\n\t\t\t\t.getStringArray(R.array.fileEndingPackage))) {\n\t\t\tintent = OpenFiles.getApkFileIntent(file);\n\t\t\tcontext.startActivity(intent);\n\n\t\t} else if (checkEndsWithInStringArray(fileName, context.getResources()\n\t\t\t\t.getStringArray(R.array.fileEndingAudio))) {\n\t\t\tintent = OpenFiles.getAudioFileIntent(file);\n\t\t\tcontext.startActivity(intent);\n\t\t} else if (checkEndsWithInStringArray(fileName, context.getResources()\n\t\t\t\t.getStringArray(R.array.fileEndingVideo))) {\n\t\t\tintent = OpenFiles.getVideoFileIntent(file);\n\t\t\tcontext.startActivity(intent);\n\t\t} else if (checkEndsWithInStringArray(fileName, context.getResources()\n\t\t\t\t.getStringArray(R.array.fileEndingText))) {\n\t\t\tintent = OpenFiles.getTextFileIntent(file);\n\t\t\tcontext.startActivity(intent);\n\t\t} else if (checkEndsWithInStringArray(fileName, context.getResources()\n\t\t\t\t.getStringArray(R.array.fileEndingPdf))) {\n\t\t\tintent = OpenFiles.getPdfFileIntent(file);\n\t\t\tcontext.startActivity(intent);\n\t\t} else if (checkEndsWithInStringArray(fileName, context.getResources()\n\t\t\t\t.getStringArray(R.array.fileEndingWord))) {\n\t\t\tintent = OpenFiles.getWordFileIntent(file);\n\t\t\tcontext.startActivity(intent);\n\t\t} else if (checkEndsWithInStringArray(fileName, context.getResources()\n\t\t\t\t.getStringArray(R.array.fileEndingExcel))) {\n\t\t\tintent = OpenFiles.getExcelFileIntent(file);\n\t\t\tcontext.startActivity(intent);\n\t\t} else if (checkEndsWithInStringArray(fileName, context.getResources()\n\t\t\t\t.getStringArray(R.array.fileEndingPPT))) {\n\t\t\tintent = OpenFiles.getPPTFileIntent(file);\n\t\t\tcontext.startActivity(intent);\n\t\t} else {\n\t\t\tUIHelper.ToastMessage(context, R.string.open_file_error);\n\t\t}\n\t}\n\n\t/**\n\t * 根据不同的后缀imageView设置不同的值\n\t * \n\t * @param fileName\n\t */\n\tpublic static void setImage(Context context, String fileName,\n\t\t\tImageView imageView) {\n\t\tif (checkEndsWithInStringArray(fileName, context.getResources()\n\t\t\t\t.getStringArray(R.array.fileEndingImage))) {\n\t\t\timageView.setImageResource(R.drawable.file_icon_picture);\n\t\t} else if (checkEndsWithInStringArray(fileName, context.getResources()\n\t\t\t\t.getStringArray(R.array.fileEndingWebText))) {\n\t\t\timageView.setImageResource(R.drawable.file_icon_txt);\n\t\t} else if (checkEndsWithInStringArray(fileName, context.getResources()\n\t\t\t\t.getStringArray(R.array.fileEndingPackage))) {\n\t\t\timageView.setImageResource(R.drawable.file_icon_rar);\n\t\t} else if (checkEndsWithInStringArray(fileName, context.getResources()\n\t\t\t\t.getStringArray(R.array.fileEndingAudio))) {\n\t\t\timageView.setImageResource(R.drawable.file_icon_mp3);\n\t\t} else if (checkEndsWithInStringArray(fileName, context.getResources()\n\t\t\t\t.getStringArray(R.array.fileEndingVideo))) {\n\t\t\timageView.setImageResource(R.drawable.file_icon_video);\n\t\t} else if (checkEndsWithInStringArray(fileName, context.getResources()\n\t\t\t\t.getStringArray(R.array.fileEndingText))) {\n\t\t\timageView.setImageResource(R.drawable.file_icon_txt);\n\t\t} else if (checkEndsWithInStringArray(fileName, context.getResources()\n\t\t\t\t.getStringArray(R.array.fileEndingPdf))) {\n\t\t\timageView.setImageResource(R.drawable.file_icon_pdf);\n\t\t} else if (checkEndsWithInStringArray(fileName, context.getResources()\n\t\t\t\t.getStringArray(R.array.fileEndingWord))) {\n\t\t\timageView.setImageResource(R.drawable.file_icon_office);\n\t\t} else if (checkEndsWithInStringArray(fileName, context.getResources()\n\t\t\t\t.getStringArray(R.array.fileEndingExcel))) {\n\t\t\timageView.setImageResource(R.drawable.file_icon_office);\n\t\t} else if (checkEndsWithInStringArray(fileName, context.getResources()\n\t\t\t\t.getStringArray(R.array.fileEndingPPT))) {\n\t\t\timageView.setImageResource(R.drawable.file_icon_office);\n\t\t} else {\n\t\t\timageView.setImageResource(R.drawable.file);\n\t\t}\n\t}\n\n\t/**\n\t * \n\t * 返回本地文件列表\n\t * \n\t * @param 本地文件夹路径\n\t * \n\t */\n\tpublic static List<File> getFileListByPath(String path) {\n\n\t\tFile dir = new File(path);\n\n\t\tList<File> folderList = new ArrayList<File>();\n\n\t\tList<File> fileList = new ArrayList<File>();\n\n\t\t// 获取指定盘符下的所有文件列表。(listFiles可以获得指定路径下的所有文件,以数组方式返回)\n\t\tFile[] files = dir.listFiles();\n\t\t// 如果该目录下面为空,则该目录的此方法执行\n\t\tif (files == null) {\n\t\t\treturn folderList;\n\t\t}// 通过循环将所遍历所有文件\n\t\tfor (int i = 0; i < files.length; i++) {\n\n\t\t\tif (!files[i].isHidden()) {\n\n\t\t\t\tif (files[i].isDirectory()) {\n\t\t\t\t\tfolderList.add(files[i]);\n\t\t\t\t}\n\t\t\t\tif (files[i].isFile()) {\n\t\t\t\t\tfileList.add(files[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfolderList.addAll(fileList);\n\n\t\treturn folderList;\n\t}\n}", "public class UIHelper {\n\n\t/**\n\t * 弹出toast消息\n\t * \n\t * @param context\n\t * @param msg\n\t */\n\tpublic static void ToastMessage(Context context, String msg) {\n\t\tToast.makeText(context, msg, Toast.LENGTH_SHORT).show();\n\t}\n\n\tpublic static void ToastMessage(Context context, int msg) {\n\t\tToast.makeText(context, msg, Toast.LENGTH_SHORT).show();\n\t}\n\n\t/**\n\t * 弹出toast消息(自设显示时间)\n\t * \n\t * @param context\n\t * @param msg\n\t * @param time\n\t */\n\tpublic static void ToastMessage(Context context, String msg, int time) {\n\t\tToast.makeText(context, msg, time).show();\n\t}\n\n\t/**\n\t * 显示登录界面\n\t * \n\t * @param context\n\t */\n\tpublic static void showLoginDialog(Context context) {\n\t\tIntent intent = new Intent(context, LoginDialog.class);\n\t\tcontext.startActivity(intent);\n\t}\n\n\t/**\n\t * 发送App错误异常报告\n\t * \n\t * @param context\n\t * @param crashReport\n\t */\n\tpublic static void sendAppCrashReport(final Context context,\n\t\t\tfinal String crashReport) {\n\n\t\tAlertDialog.Builder builder = new AlertDialog.Builder(context);\n\t\tbuilder.setIcon(android.R.drawable.ic_dialog_info);\n\t\tbuilder.setTitle(R.string.app_error);\n\t\tbuilder.setMessage(R.string.app_error_message);\n\t\tbuilder.setPositiveButton(R.string.submit_report,\n\t\t\t\tnew OnClickListener() {\n\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void onClick(DialogInterface dialog, int which) {\n\t\t\t\t\t\tdialog.dismiss();\n\t\t\t\t\t\t// 发送异常报告\n\t\t\t\t\t\tIntent intent = new Intent(Intent.ACTION_SEND);\n\t\t\t\t\t\t// intent.setType(\"text/plain\");// 模拟器\n\t\t\t\t\t\tintent.setType(\"message/rfc822\");// 真机\n\t\t\t\t\t\t// 发送邮件 Intent.EXTRA_CC抄送 Intent.EXTRA_BCC密送者\n\t\t\t\t\t\tintent.putExtra(Intent.EXTRA_EMAIL,\n\t\t\t\t\t\t\t\tnew String[] { \"736909686@qq.com\" });\n\t\t\t\t\t\t// 标题\n\t\t\t\t\t\tintent.putExtra(Intent.EXTRA_SUBJECT,\n\t\t\t\t\t\t\t\t\"清扬android客户端-错误报告\");\n\t\t\t\t\t\t// 内容\n\t\t\t\t\t\tintent.putExtra(Intent.EXTRA_TEXT, crashReport);\n\n\t\t\t\t\t\tcontext.startActivity(Intent.createChooser(intent,\n\t\t\t\t\t\t\t\t\"发送错误报告\"));\n\n\t\t\t\t\t\tAppManager.getAppManager().AppExit(context);\n\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\tbuilder.setNegativeButton(R.string.sure, new OnClickListener() {\n\n\t\t\t@Override\n\t\t\tpublic void onClick(DialogInterface dialog, int which) {\n\t\t\t\tdialog.dismiss();\n\t\t\t\tAppManager.getAppManager().AppExit(context);\n\t\t\t}\n\t\t});\n\n\t\tAlertDialog alertDialog = builder.create();\n\t\talertDialog.setCanceledOnTouchOutside(false);\n\t\talertDialog.setOnDismissListener(new OnDismissListener() {\n\t\t\t@Override\n\t\t\tpublic void onDismiss(DialogInterface dialog) {\n\t\t\t\tAppManager.getAppManager().AppExit(context);\n\t\t\t}\n\t\t});\n\t\talertDialog.show();\n\n\t}\n\n\t/**\n\t * 用户登录或注销\n\t * \n\t * @param activity\n\t */\n\tpublic static void loginOrLogout(Activity activity) {\n\t\tBaseApplication application = (BaseApplication) activity\n\t\t\t\t.getApplication();\n\n\t\tif (application.isLogin()) {\n\t\t\tapplication.layout();\n\t\t\tToastMessage(application, \"已退出登陆\");\n\t\t} else {\n\t\t\tshowLoginDialog(activity);\n\t\t}\n\t}\n\n\t/**\n\t * 清除缓存\n\t * \n\t * @param activity\n\t */\n\tpublic static void clearAppCache(Activity activity) {\n\t\tfinal BaseApplication application = (BaseApplication) activity\n\t\t\t\t.getApplication();\n\n\t\tfinal Handler handler = new Handler() {\n\t\t\tpublic void handleMessage(Message msg) {\n\t\t\t\tif (msg.what == 1) {\n\t\t\t\t\tToastMessage(application, \"缓存清除成功\");\n\t\t\t\t} else {\n\t\t\t\t\tToastMessage(application, \"缓存清除失败\");\n\t\t\t\t}\n\t\t\t};\n\t\t};\n\n\t\tnew Thread(new Runnable() {\n\n\t\t\t@Override\n\t\t\tpublic void run() {\n\t\t\t\tMessage msg = new Message();\n\n\t\t\t\ttry {\n\t\t\t\t\tapplication.clearAppCache();\n\t\t\t\t\tmsg.what = 1;\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\te.printStackTrace();\n\n\t\t\t\t\tmsg.what = -1;\n\t\t\t\t}\n\t\t\t\thandler.sendMessage(msg);\n\t\t\t}\n\t\t}).start();\n\n\t}\n\n\t/**\n\t * 清除下载数据\n\t * \n\t * @param activity\n\t */\n\tpublic static void clearDownCache(Activity activity) {\n\t\tfinal BaseApplication application = (BaseApplication) activity\n\t\t\t\t.getApplication();\n\n\t\tfinal Handler handler = new Handler() {\n\t\t\tpublic void handleMessage(Message msg) {\n\t\t\t\tif (msg.what == 1) {\n\t\t\t\t\tToastMessage(application, \"清除成功\");\n\t\t\t\t} else {\n\t\t\t\t\tToastMessage(application, \"清除失败\");\n\t\t\t\t}\n\t\t\t};\n\t\t};\n\n\t\tnew Thread(new Runnable() {\n\n\t\t\t@Override\n\t\t\tpublic void run() {\n\t\t\t\tMessage msg = new Message();\n\n\t\t\t\ttry {\n\t\t\t\t\tapplication.clearDownCache();\n\t\t\t\t\tmsg.what = 1;\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\te.printStackTrace();\n\n\t\t\t\t\tmsg.what = -1;\n\t\t\t\t}\n\t\t\t\thandler.sendMessage(msg);\n\t\t\t}\n\t\t}).start();\n\n\t}\n\n\t/**\n\t * 显示检查更新页面\n\t * \n\t * @param settingActivity\n\t */\n\tpublic static void showFeedBack(Context context) {\n\t\tIntent intent = new Intent(context, FeedBackDialog.class);\n\t\tcontext.startActivity(intent);\n\t}\n\n\t/**\n\t * 点击返回监听事件\n\t * \n\t * @param activity\n\t * @return\n\t */\n\tpublic static View.OnClickListener finish(final Activity activity) {\n\t\treturn new View.OnClickListener() {\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tactivity.finish();\n\t\t\t}\n\t\t};\n\t}\n}", "public class UpdateManager {\n\n\t// 没有sd卡状态\n\tprivate static final int DOWN_NOSDCARD = 0;\n\t// 更新状态\n\tprivate static final int DOWN_UPDATE = 1;\n\t// 结束状态\n\tprivate static final int DOWN_OVER = 2;\n\n\tprivate static final int DIALOG_TYPE_LATEST = 0;\n\n\tprivate static final int DIALOG_TYPE_FAIL = 1;\n\n\tprivate static UpdateManager updateManager;\n\n\tprivate Context context;\n\n\t// 终止标记\n\tprivate boolean interceptFlag;\n\n\t// 当前版本的名称\n\tprivate String curVersionName = \"\";\n\n\t// 当前版本号\n\tprivate int curVersionCode;\n\n\t// 查询动画\n\tprivate ProgressDialog progressDialog;\n\n\t// 已经是最新或无法获取最新版本的对话框\n\tprivate Dialog latestOrFailDialog;\n\n\t// 服务端获取的更新信息\n\tprivate Update mUpdate;\n\n\t// 返回回来的安装包url\n\tprivate String apkUrl;\n\n\t// 提示语\n\tprivate String updateMsg;\n\n\t// 通知对话框\n\tprivate Dialog noticeDialog;\n\n\t// 下载对话框\n\tprivate Dialog downloadDialog;\n\n\t// 下载进度条\n\tprivate ProgressBar mProgressBar;\n\n\t// 下载详细文本\n\tprivate TextView mProgressText;\n\n\t// 下载线程\n\tprivate Thread downLoadThread;\n\n\t// 下载路径\n\tprivate String savePath;\n\n\t// apk文件路径\n\tprivate String apkFilePath;\n\n\t// 临时文件路径\n\tprivate String tempFilePath;\n\n\t// 进度值\n\tprivate int progress;\n\n\t// 下载文件的大小\n\tprivate String apkFileSize;\n\n\t// 已下载文件的大小\n\tprivate String tmpFileSize;\n\n\tprivate Handler mHandler = new Handler() {\n\t\tpublic void handleMessage(Message msg) {\n\t\t\tswitch (msg.what) {\n\t\t\tcase DOWN_UPDATE:\n\t\t\t\tmProgressBar.setProgress(progress);\n\t\t\t\tmProgressText.setText(tmpFileSize + \"/\" + apkFileSize);\n\t\t\t\tbreak;\n\n\t\t\tcase DOWN_OVER:\n\t\t\t\tdownloadDialog.dismiss();\n\t\t\t\tdownloadDialog = null;\n\t\t\t\tinstallApk();\n\t\t\t\tbreak;\n\t\t\tcase DOWN_NOSDCARD:\n\t\t\t\tdownloadDialog.dismiss();\n\t\t\t\tdownloadDialog = null;\n\t\t\t\tUIHelper.ToastMessage(context, \"无法下载安装文件,请检查SD卡是否挂载\", 3000);\n\t\t\t}\n\t\t};\n\t};\n\n\tpublic static UpdateManager getUpdateManager() {\n\t\tif (updateManager == null) {\n\t\t\tupdateManager = new UpdateManager();\n\t\t}\n\t\tupdateManager.interceptFlag = false;\n\t\treturn updateManager;\n\t}\n\n\t/**\n\t * 获取当前客户端的版本信息\n\t */\n\tprivate void getCurrentVersion() {\n\t\ttry {\n\t\t\tPackageInfo info = context.getPackageManager().getPackageInfo(\n\t\t\t\t\tcontext.getPackageName(), 0);\n\t\t\tcurVersionName = info.versionName;\n\t\t\tcurVersionCode = info.versionCode;\n\t\t} catch (NameNotFoundException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\t/**\n\t * 检查app更新\n\t * \n\t * @param context\n\t * @param isShowMsg\n\t * 是否显示查询dialog\n\t */\n\tpublic void checkAppUpdate(final Context context, final boolean isShowMsg) {\n\t\tthis.context = context;\n\t\tgetCurrentVersion();\n\t\tif (isShowMsg) {\n\t\t\tif (progressDialog == null) {\n\t\t\t\tprogressDialog = ProgressDialog.show(context, null,\n\t\t\t\t\t\t\"正在检测,请稍后...\", true, true);\n\t\t\t} else if (progressDialog.isShowing()\n\t\t\t\t\t|| (latestOrFailDialog != null && latestOrFailDialog\n\t\t\t\t\t\t\t.isShowing())) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tfinal Handler handler = new Handler() {\n\t\t\t@Override\n\t\t\tpublic void handleMessage(Message msg) {\n\t\t\t\t// 进度条对话框不显示\n\t\t\t\tif (progressDialog != null && !progressDialog.isShowing()) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (isShowMsg && progressDialog != null) {\n\t\t\t\t\tprogressDialog.dismiss();\n\t\t\t\t\tprogressDialog = null;\n\t\t\t\t}\n\n\t\t\t\tif (msg.what == 1) {\n\t\t\t\t\tmUpdate = (Update) msg.obj;\n\n\t\t\t\t\tif (mUpdate != null) {\n\t\t\t\t\t\tif (curVersionCode < mUpdate.getVersionCode()) {\n\t\t\t\t\t\t\tapkUrl = mUpdate.getDownloadUrl();\n\t\t\t\t\t\t\tupdateMsg = mUpdate.getUpdateLog();\n\t\t\t\t\t\t\tshowNoticeDialog();\n\t\t\t\t\t\t} else if (isShowMsg) {\n\t\t\t\t\t\t\tshowLatestOrFailDialog(DIALOG_TYPE_FAIL);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\tnew Thread(new Runnable() {\n\n\t\t\t@Override\n\t\t\tpublic void run() {\n\t\t\t\tMessage msg = new Message();\n\n\t\t\t\ttry {\n\t\t\t\t\tUpdate update = NetClient\n\t\t\t\t\t\t\t.checkVersion((BaseApplication) context\n\t\t\t\t\t\t\t\t\t.getApplicationContext());\n\n\t\t\t\t\tmsg.what = 1;\n\n\t\t\t\t\tmsg.obj = update;\n\n\t\t\t\t\thandler.sendMessage(msg);\n\n\t\t\t\t} catch (AppException e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\n\t\t\t}\n\t\t}).start();\n\t}\n\n\t/**\n\t * 显示已经最新或者无法获取版本信息的对话框\n\t * \n\t * @param dialogTypeFail\n\t */\n\tprotected void showLatestOrFailDialog(int dialogType) {\n\t\tif (latestOrFailDialog != null) {\n\t\t\tlatestOrFailDialog.dismiss();\n\t\t\tlatestOrFailDialog = null;\n\t\t}\n\n\t\tAlertDialog.Builder builder = new AlertDialog.Builder(context);\n\n\t\tbuilder.setTitle(\"系统提示\");\n\n\t\tif (dialogType == DIALOG_TYPE_FAIL) {\n\t\t\tbuilder.setMessage(\"无法获取版本更新信息\");\n\t\t} else if (dialogType == DIALOG_TYPE_LATEST) {\n\t\t\tbuilder.setMessage(\"您已经是最新版本\");\n\t\t}\n\n\t\tbuilder.setPositiveButton(\"确定\", null);\n\t\tlatestOrFailDialog = builder.create();\n\t\tlatestOrFailDialog.show();\n\t}\n\n\t/**\n\t * 显示版本更新通知对话框\n\t */\n\tprivate void showNoticeDialog() {\n\t\tAlertDialog.Builder builder = new AlertDialog.Builder(context);\n\n\t\tbuilder.setTitle(\"软件版本更新\");\n\n\t\tbuilder.setMessage(updateMsg);\n\n\t\tbuilder.setPositiveButton(\"立即更新\", new OnClickListener() {\n\n\t\t\t@Override\n\t\t\tpublic void onClick(DialogInterface dialog, int which) {\n\t\t\t\tdialog.dismiss();\n\t\t\t\tshowDownloadDialog();\n\t\t\t}\n\t\t});\n\n\t\tbuilder.setNegativeButton(\"以后再说\", new OnClickListener() {\n\n\t\t\t@Override\n\t\t\tpublic void onClick(DialogInterface dialog, int which) {\n\t\t\t\tdialog.dismiss();\n\t\t\t}\n\t\t});\n\n\t\tnoticeDialog = builder.create();\n\n\t\tnoticeDialog.show();\n\n\t}\n\n\t/**\n\t * 显示下载对话框\n\t */\n\tprotected void showDownloadDialog() {\n\t\tAlertDialog.Builder builder = new AlertDialog.Builder(context);\n\t\tbuilder.setTitle(\"正在下载新版本\");\n\n\t\tfinal LayoutInflater inflater = LayoutInflater.from(context);\n\n\t\tView v = inflater.inflate(R.layout.update_progress, null);\n\n\t\tmProgressBar = (ProgressBar) v.findViewById(R.id.update_progress);\n\n\t\tmProgressText = (TextView) v.findViewById(R.id.update_progress_text);\n\n\t\tbuilder.setView(v);\n\n\t\tbuilder.setNegativeButton(\"取消\", new OnClickListener() {\n\t\t\t@Override\n\t\t\tpublic void onClick(DialogInterface dialog, int which) {\n\t\t\t\tdialog.dismiss();\n\t\t\t\tinterceptFlag = true;\n\t\t\t}\n\t\t});\n\n\t\tbuilder.setOnCancelListener(new OnCancelListener() {\n\t\t\t@Override\n\t\t\tpublic void onCancel(DialogInterface dialog) {\n\t\t\t\tdialog.dismiss();\n\t\t\t\tinterceptFlag = true;\n\t\t\t}\n\t\t});\n\n\t\tdownloadDialog = builder.create();\n\n\t\tdownloadDialog.setCanceledOnTouchOutside(false);\n\n\t\tdownloadDialog.show();\n\n\t\tdownloadApk();\n\t}\n\n\tprivate Runnable downApkRunnbale = new Runnable() {\n\n\t\t@Override\n\t\tpublic void run() {\n\n\t\t\ttry {\n\n\t\t\t\tString apkName = mUpdate.getVersionName() + \".apk\";\n\n\t\t\t\tString tmpName = mUpdate.getVersionName() + \".tmp\";\n\n\t\t\t\t// 判断是否挂载了SD卡\n\t\t\t\tString storageState = Environment.getExternalStorageState();\n\n\t\t\t\tif (storageState.equals(Environment.MEDIA_MOUNTED)) {\n\t\t\t\t\tsavePath = Environment.getExternalStorageDirectory()\n\t\t\t\t\t\t\t.getAbsolutePath() + \"/qingyang/Update\";\n\t\t\t\t\tFile file = new File(savePath);\n\t\t\t\t\tif (!file.exists()) {\n\t\t\t\t\t\tfile.mkdir();\n\t\t\t\t\t}\n\n\t\t\t\t\tapkFilePath = savePath + \"/\" + apkName;\n\n\t\t\t\t\ttempFilePath = savePath + \"/\" + tmpName;\n\t\t\t\t}\n\n\t\t\t\tif (apkFilePath == null || apkFilePath.equals(\"\")) {\n\t\t\t\t\tmHandler.sendEmptyMessage(DOWN_NOSDCARD);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tFile apkFile = new File(apkFilePath);\n\n\t\t\t\t// 如果已经存在更新文件\n\t\t\t\tif (apkFile.exists()) {\n\t\t\t\t\tdownloadDialog.dismiss();\n\t\t\t\t\tdownloadDialog = null;\n\t\t\t\t\tinstallApk();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tFile tmpFile = new File(tempFilePath);\n\n\t\t\t\tFileOutputStream fos = new FileOutputStream(tmpFile);\n\n\t\t\t\tURL url = new URL(apkUrl);\n\n\t\t\t\tHttpURLConnection conn = (HttpURLConnection) url\n\t\t\t\t\t\t.openConnection();\n\n\t\t\t\tconn.connect();\n\n\t\t\t\tint length = conn.getContentLength();\n\n\t\t\t\tInputStream is = conn.getInputStream();\n\n\t\t\t\tDecimalFormat df = new DecimalFormat(\"0.00\");\n\n\t\t\t\tapkFileSize = df.format((float) length / 1024 / 1024) + \"MB\";\n\n\t\t\t\tint count = 0;\n\n\t\t\t\tbyte buf[] = new byte[1024];\n\n\t\t\t\tdo {\n\t\t\t\t\tint numread = is.read(buf);\n\n\t\t\t\t\tcount += numread;\n\t\t\t\t\t// 当先下载文件大小\n\t\t\t\t\ttmpFileSize = df.format((float) count / 1024 / 1024) + \"MB\";\n\n\t\t\t\t\t// 当前进度值\n\t\t\t\t\tprogress = (int) (((float) count / length) * 100);\n\n\t\t\t\t\t// 更新进度\n\t\t\t\t\tmHandler.sendEmptyMessage(DOWN_UPDATE);\n\n\t\t\t\t\tif (numread <= 0) {\n\t\t\t\t\t\t// 下载完成-奖临时下载文件装成APK文件\n\t\t\t\t\t\tif (tmpFile.renameTo(apkFile)) {\n\t\t\t\t\t\t\t// 通知安装\n\t\t\t\t\t\t\tmHandler.sendEmptyMessage(DOWN_OVER);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tfos.write(buf, 0, numread);\n\t\t\t\t} while (!interceptFlag);// 点击取消就停止下载\n\n\t\t\t\tfos.close();\n\t\t\t\tis.close();\n\t\t\t} catch (Exception e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\n\t\t}\n\n\t};\n\n\t/**\n\t * 下载apk\n\t */\n\tprivate void downloadApk() {\n\t\tdownLoadThread = new Thread(downApkRunnbale);\n\t\tdownLoadThread.start();\n\t}\n\n\t/**\n\t * 安装apk\n\t */\n\tprivate void installApk() {\n\t\tFile apkFile = new File(apkFilePath);\n\n\t\tif (!apkFile.exists()) {\n\t\t\treturn;\n\t\t}\n\t\tIntent i = new Intent(Intent.ACTION_VIEW);\n\t\ti.setDataAndType(Uri.parse(\"file://\" + apkFile.toString()),\n\t\t\t\t\"application/vnd.android.package-archive\");\n\t\tcontext.startActivity(i);\n\t}\n}", "public class Constant {\n\n\t// 下载地址\n\tpublic final static String DOWN_PATH = \"/qingyang/down/\";\n\n\t// 记录错误信息地址\n\tpublic final static String LOG_PATH = \"/qingyang/Log/\";\n\n\t// 记录错误信息的名称\n\tpublic final static String LOG_NAME = \"errorlog.txt\";\n}", "public class IpSetDialog extends BaseActivity {\n\n\tpublic final static String IS_STRAT_MAIN = \"isStartMain\";\n\n\tprivate ImageButton closeButton;\n\n\tprivate EditText edit1, edit2, edit3, edit4;\n\n\tprivate Button submitButton;\n\n\tprivate BaseApplication application;\n\n\tprivate boolean isStartMain;\n\n\t@Override\n\tprotected void onCreate(Bundle savedInstanceState) {\n\t\tsuper.onCreate(savedInstanceState);\n\t\tsetContentView(R.layout.ipset_dialog);\n\n\t\tapplication = (BaseApplication) getApplication();\n\n\t\tisStartMain = getIntent().getExtras().getBoolean(IS_STRAT_MAIN);\n\n\t\tinitView();\n\t}\n\n\tprivate void initView() {\n\t\tcloseButton = (ImageButton) findViewById(R.id.ipset_close_button);\n\n\t\tedit1 = (EditText) findViewById(R.id.local_gw_edit_1);\n\n\t\tedit2 = (EditText) findViewById(R.id.local_gw_edit_2);\n\n\t\tedit3 = (EditText) findViewById(R.id.local_gw_edit_3);\n\n\t\tedit4 = (EditText) findViewById(R.id.local_gw_edit_4);\n\n\t\tsubmitButton = (Button) findViewById(R.id.ipset_submit);\n\n\t\tcloseButton.setOnClickListener(UIHelper.finish(this));\n\n\t\tString[] ip = application.getIpAdress().toString().replace(\".\", \",\")\n\t\t\t\t.split(\",\");\n\n\t\tedit1.setText(ip[0]);\n\n\t\tedit2.setText(ip[1]);\n\n\t\tedit3.setText(ip[2]);\n\n\t\tedit4.setText(ip[3]);\n\n\t\tsubmitButton.setOnClickListener(new OnClickListener() {\n\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\n\t\t\t\tif (StringUtil.isEmpty(edit1.getText().toString())\n\t\t\t\t\t\t|| StringUtil.isEmpty(edit2.getText().toString())\n\t\t\t\t\t\t|| StringUtil.isEmpty(edit3.getText().toString())\n\t\t\t\t\t\t|| StringUtil.isEmpty(edit4.getText().toString())) {\n\t\t\t\t\tUIHelper.ToastMessage(IpSetDialog.this,\n\t\t\t\t\t\t\tR.string.ip_set_error);\n\t\t\t\t}\n\n\t\t\t\tString ipadress = edit1.getText().toString() + \".\"\n\t\t\t\t\t\t+ edit2.getText().toString() + \".\"\n\t\t\t\t\t\t+ edit3.getText().toString() + \".\"\n\t\t\t\t\t\t+ edit4.getText().toString();\n\n\t\t\t\tapplication.setIpAdress(ipadress);\n\n\t\t\t\tif (isStartMain) {\n\t\t\t\t\tstartActivity(MainActivity.class);\n\t\t\t\t}\n\n\t\t\t\tfinish();\n\t\t\t}\n\t\t});\n\t}\n\n\t@Override\n\tprotected void onDestroy() {\n\t\tAppManager.getAppManager().finishActivity(this);\n\t\tsuper.onDestroy();\n\t}\n}" ]
import java.io.File; import com.example.qingyangdemo.base.AppManager; import com.example.qingyangdemo.base.BaseApplication; import com.example.qingyangdemo.common.FileUtil; import com.example.qingyangdemo.common.UIHelper; import com.example.qingyangdemo.common.UpdateManager; import com.example.qingyangdemo.net.Constant; import com.example.qingyangdemo.ui.IpSetDialog; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; import android.preference.PreferenceManager; import android.view.View; import android.view.ViewGroup; import android.widget.ListView;
package com.example.qingyangdemo; /** * 系统设置类 * * @author 赵庆洋 * */ public class SettingActivity extends PreferenceActivity { private SharedPreferences mPreferences; private BaseApplication myApplication; // 设置Ip private Preference ipset; // 账户 private Preference account; // 清除缓存 private Preference cache; // 清除已下载数据 private Preference down; // 是否启动应用检查更新 private CheckBoxPreference checkup; // 是否开启提示声音 private CheckBoxPreference voice; // 检查更新 private Preference update; // 意见反馈 private Preference feedback; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 添加Activity到堆栈 AppManager.getAppManager().addActivity(this); myApplication = (BaseApplication) getApplication(); // 设置显示Preferences addPreferencesFromResource(R.xml.preferences); // 获得SharedPreferences mPreferences = PreferenceManager.getDefaultSharedPreferences(this); ListView localListView = getListView(); localListView.setBackgroundColor(0); localListView.setCacheColorHint(0); ((ViewGroup) localListView.getParent()).removeView(localListView); ViewGroup localViewGroup = (ViewGroup) getLayoutInflater().inflate( R.layout.setting_activity, null); ((ViewGroup) localViewGroup.findViewById(R.id.setting_content)) .addView(localListView, -1, -1); setContentView(localViewGroup); initView(); } private void initView() { // 登陆/注销 account = findPreference("account"); if (myApplication.isLogin()) { account.setTitle(R.string.main_menu_logout); } else { account.setTitle(R.string.main_menu_login); } account.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) {
UIHelper.loginOrLogout(SettingActivity.this);
3
jhy/jsoup
src/test/java/org/jsoup/parser/HtmlParserTest.java
[ "public class Jsoup {\n private Jsoup() {}\n\n /**\n Parse HTML into a Document. The parser will make a sensible, balanced document tree out of any HTML.\n\n @param html HTML to parse\n @param baseUri The URL where the HTML was retrieved from. Used to resolve relative URLs to absolute URLs, that occur\n before the HTML declares a {@code <base href>} tag.\n @return sane HTML\n */\n public static Document parse(String html, String baseUri) {\n return Parser.parse(html, baseUri);\n }\n\n /**\n Parse HTML into a Document, using the provided Parser. You can provide an alternate parser, such as a simple XML\n (non-HTML) parser.\n\n @param html HTML to parse\n @param baseUri The URL where the HTML was retrieved from. Used to resolve relative URLs to absolute URLs, that occur\n before the HTML declares a {@code <base href>} tag.\n @param parser alternate {@link Parser#xmlParser() parser} to use.\n @return sane HTML\n */\n public static Document parse(String html, String baseUri, Parser parser) {\n return parser.parseInput(html, baseUri);\n }\n\n /**\n Parse HTML into a Document, using the provided Parser. You can provide an alternate parser, such as a simple XML\n (non-HTML) parser. As no base URI is specified, absolute URL resolution, if required, relies on the HTML including\n a {@code <base href>} tag.\n\n @param html HTML to parse\n before the HTML declares a {@code <base href>} tag.\n @param parser alternate {@link Parser#xmlParser() parser} to use.\n @return sane HTML\n */\n public static Document parse(String html, Parser parser) {\n return parser.parseInput(html, \"\");\n }\n\n /**\n Parse HTML into a Document. As no base URI is specified, absolute URL resolution, if required, relies on the HTML\n including a {@code <base href>} tag.\n\n @param html HTML to parse\n @return sane HTML\n\n @see #parse(String, String)\n */\n public static Document parse(String html) {\n return Parser.parse(html, \"\");\n }\n\n /**\n * Creates a new {@link Connection} (session), with the defined request URL. Use to fetch and parse a HTML page.\n * <p>\n * Use examples:\n * <ul>\n * <li><code>Document doc = Jsoup.connect(\"http://example.com\").userAgent(\"Mozilla\").data(\"name\", \"jsoup\").get();</code></li>\n * <li><code>Document doc = Jsoup.connect(\"http://example.com\").cookie(\"auth\", \"token\").post();</code></li>\n * </ul>\n * @param url URL to connect to. The protocol must be {@code http} or {@code https}.\n * @return the connection. You can add data, cookies, and headers; set the user-agent, referrer, method; and then execute.\n * @see #newSession()\n * @see Connection#newRequest()\n */\n public static Connection connect(String url) {\n return HttpConnection.connect(url);\n }\n\n /**\n Creates a new {@link Connection} to use as a session. Connection settings (user-agent, timeouts, URL, etc), and\n cookies will be maintained for the session. Use examples:\n<pre><code>\nConnection session = Jsoup.newSession()\n .timeout(20 * 1000)\n .userAgent(\"FooBar 2000\");\n\nDocument doc1 = session.newRequest()\n .url(\"https://jsoup.org/\").data(\"ref\", \"example\")\n .get();\nDocument doc2 = session.newRequest()\n .url(\"https://en.wikipedia.org/wiki/Main_Page\")\n .get();\nConnection con3 = session.newRequest();\n</code></pre>\n\n <p>For multi-threaded requests, it is safe to use this session between threads, but take care to call {@link\n Connection#newRequest()} per request and not share that instance between threads when executing or parsing.</p>\n\n @return a connection\n @since 1.14.1\n */\n public static Connection newSession() {\n return new HttpConnection();\n }\n\n /**\n Parse the contents of a file as HTML.\n\n @param file file to load HTML from. Supports gzipped files (ending in .z or .gz).\n @param charsetName (optional) character set of file contents. Set to {@code null} to determine from {@code http-equiv} meta tag, if\n present, or fall back to {@code UTF-8} (which is often safe to do).\n @param baseUri The URL where the HTML was retrieved from, to resolve relative links against.\n @return sane HTML\n\n @throws IOException if the file could not be found, or read, or if the charsetName is invalid.\n */\n public static Document parse(File file, @Nullable String charsetName, String baseUri) throws IOException {\n return DataUtil.load(file, charsetName, baseUri);\n }\n\n /**\n Parse the contents of a file as HTML. The location of the file is used as the base URI to qualify relative URLs.\n\n @param file file to load HTML from. Supports gzipped files (ending in .z or .gz).\n @param charsetName (optional) character set of file contents. Set to {@code null} to determine from {@code http-equiv} meta tag, if\n present, or fall back to {@code UTF-8} (which is often safe to do).\n @return sane HTML\n\n @throws IOException if the file could not be found, or read, or if the charsetName is invalid.\n @see #parse(File, String, String) parse(file, charset, baseUri)\n */\n public static Document parse(File file, @Nullable String charsetName) throws IOException {\n return DataUtil.load(file, charsetName, file.getAbsolutePath());\n }\n\n /**\n Parse the contents of a file as HTML. The location of the file is used as the base URI to qualify relative URLs.\n The charset used to read the file will be determined by the byte-order-mark (BOM), or a {@code <meta charset>} tag,\n or if neither is present, will be {@code UTF-8}.\n\n <p>This is the equivalent of calling {@link #parse(File, String) parse(file, null)}</p>\n\n @param file the file to load HTML from. Supports gzipped files (ending in .z or .gz).\n @return sane HTML\n @throws IOException if the file could not be found or read.\n @see #parse(File, String, String) parse(file, charset, baseUri)\n @since 1.15.1\n */\n public static Document parse(File file) throws IOException {\n return DataUtil.load(file, null, file.getAbsolutePath());\n }\n\n /**\n Parse the contents of a file as HTML.\n\n @param file file to load HTML from. Supports gzipped files (ending in .z or .gz).\n @param charsetName (optional) character set of file contents. Set to {@code null} to determine from {@code http-equiv} meta tag, if\n present, or fall back to {@code UTF-8} (which is often safe to do).\n @param baseUri The URL where the HTML was retrieved from, to resolve relative links against.\n @param parser alternate {@link Parser#xmlParser() parser} to use.\n @return sane HTML\n\n @throws IOException if the file could not be found, or read, or if the charsetName is invalid.\n @since 1.14.2\n */\n public static Document parse(File file, @Nullable String charsetName, String baseUri, Parser parser) throws IOException {\n return DataUtil.load(file, charsetName, baseUri, parser);\n }\n\n /**\n Read an input stream, and parse it to a Document.\n\n @param in input stream to read. Make sure to close it after parsing.\n @param charsetName (optional) character set of file contents. Set to {@code null} to determine from {@code http-equiv} meta tag, if\n present, or fall back to {@code UTF-8} (which is often safe to do).\n @param baseUri The URL where the HTML was retrieved from, to resolve relative links against.\n @return sane HTML\n\n @throws IOException if the file could not be found, or read, or if the charsetName is invalid.\n */\n public static Document parse(InputStream in, @Nullable String charsetName, String baseUri) throws IOException {\n return DataUtil.load(in, charsetName, baseUri);\n }\n\n /**\n Read an input stream, and parse it to a Document. You can provide an alternate parser, such as a simple XML\n (non-HTML) parser.\n\n @param in input stream to read. Make sure to close it after parsing.\n @param charsetName (optional) character set of file contents. Set to {@code null} to determine from {@code http-equiv} meta tag, if\n present, or fall back to {@code UTF-8} (which is often safe to do).\n @param baseUri The URL where the HTML was retrieved from, to resolve relative links against.\n @param parser alternate {@link Parser#xmlParser() parser} to use.\n @return sane HTML\n\n @throws IOException if the file could not be found, or read, or if the charsetName is invalid.\n */\n public static Document parse(InputStream in, @Nullable String charsetName, String baseUri, Parser parser) throws IOException {\n return DataUtil.load(in, charsetName, baseUri, parser);\n }\n\n /**\n Parse a fragment of HTML, with the assumption that it forms the {@code body} of the HTML.\n\n @param bodyHtml body HTML fragment\n @param baseUri URL to resolve relative URLs against.\n @return sane HTML document\n\n @see Document#body()\n */\n public static Document parseBodyFragment(String bodyHtml, String baseUri) {\n return Parser.parseBodyFragment(bodyHtml, baseUri);\n }\n\n /**\n Parse a fragment of HTML, with the assumption that it forms the {@code body} of the HTML.\n\n @param bodyHtml body HTML fragment\n @return sane HTML document\n\n @see Document#body()\n */\n public static Document parseBodyFragment(String bodyHtml) {\n return Parser.parseBodyFragment(bodyHtml, \"\");\n }\n\n /**\n Fetch a URL, and parse it as HTML. Provided for compatibility; in most cases use {@link #connect(String)} instead.\n <p>\n The encoding character set is determined by the content-type header or http-equiv meta tag, or falls back to {@code UTF-8}.\n\n @param url URL to fetch (with a GET). The protocol must be {@code http} or {@code https}.\n @param timeoutMillis Connection and read timeout, in milliseconds. If exceeded, IOException is thrown.\n @return The parsed HTML.\n\n @throws java.net.MalformedURLException if the request URL is not a HTTP or HTTPS URL, or is otherwise malformed\n @throws HttpStatusException if the response is not OK and HTTP response errors are not ignored\n @throws UnsupportedMimeTypeException if the response mime type is not supported and those errors are not ignored\n @throws java.net.SocketTimeoutException if the connection times out\n @throws IOException if a connection or read error occurs\n\n @see #connect(String)\n */\n public static Document parse(URL url, int timeoutMillis) throws IOException {\n Connection con = HttpConnection.connect(url);\n con.timeout(timeoutMillis);\n return con.get();\n }\n\n /**\n Get safe HTML from untrusted input HTML, by parsing input HTML and filtering it through an allow-list of safe\n tags and attributes.\n\n @param bodyHtml input untrusted HTML (body fragment)\n @param baseUri URL to resolve relative URLs against\n @param safelist list of permitted HTML elements\n @return safe HTML (body fragment)\n\n @see Cleaner#clean(Document)\n */\n public static String clean(String bodyHtml, String baseUri, Safelist safelist) {\n Document dirty = parseBodyFragment(bodyHtml, baseUri);\n Cleaner cleaner = new Cleaner(safelist);\n Document clean = cleaner.clean(dirty);\n return clean.body().html();\n }\n\n /**\n Get safe HTML from untrusted input HTML, by parsing input HTML and filtering it through a safe-list of permitted\n tags and attributes.\n\n <p>Note that as this method does not take a base href URL to resolve attributes with relative URLs against, those\n URLs will be removed, unless the input HTML contains a {@code <base href> tag}. If you wish to preserve those, use\n the {@link Jsoup#clean(String html, String baseHref, Safelist)} method instead, and enable\n {@link Safelist#preserveRelativeLinks(boolean)}.</p>\n\n @param bodyHtml input untrusted HTML (body fragment)\n @param safelist list of permitted HTML elements\n @return safe HTML (body fragment)\n @see Cleaner#clean(Document)\n */\n public static String clean(String bodyHtml, Safelist safelist) {\n return clean(bodyHtml, \"\", safelist);\n }\n\n /**\n * Get safe HTML from untrusted input HTML, by parsing input HTML and filtering it through a safe-list of\n * permitted tags and attributes.\n * <p>The HTML is treated as a body fragment; it's expected the cleaned HTML will be used within the body of an\n * existing document. If you want to clean full documents, use {@link Cleaner#clean(Document)} instead, and add\n * structural tags (<code>html, head, body</code> etc) to the safelist.\n *\n * @param bodyHtml input untrusted HTML (body fragment)\n * @param baseUri URL to resolve relative URLs against\n * @param safelist list of permitted HTML elements\n * @param outputSettings document output settings; use to control pretty-printing and entity escape modes\n * @return safe HTML (body fragment)\n * @see Cleaner#clean(Document)\n */\n public static String clean(String bodyHtml, String baseUri, Safelist safelist, Document.OutputSettings outputSettings) {\n Document dirty = parseBodyFragment(bodyHtml, baseUri);\n Cleaner cleaner = new Cleaner(safelist);\n Document clean = cleaner.clean(dirty);\n clean.outputSettings(outputSettings);\n return clean.body().html();\n }\n\n /**\n Test if the input body HTML has only tags and attributes allowed by the Safelist. Useful for form validation.\n <p>The input HTML should still be run through the cleaner to set up enforced attributes, and to tidy the output.\n <p>Assumes the HTML is a body fragment (i.e. will be used in an existing HTML document body.)\n @param bodyHtml HTML to test\n @param safelist safelist to test against\n @return true if no tags or attributes were removed; false otherwise\n @see #clean(String, Safelist)\n */\n public static boolean isValid(String bodyHtml, Safelist safelist) {\n return new Cleaner(safelist).isValidBodyHtml(bodyHtml);\n }\n}", "public class TextUtil {\n static Pattern stripper = Pattern.compile(\"\\\\r?\\\\n\\\\s*\");\n static Pattern stripLines = Pattern.compile(\"\\\\r?\\\\n?\");\n static Pattern spaceCollapse = Pattern.compile(\"\\\\s{2,}\");\n static Pattern tagSpaceCollapse = Pattern.compile(\">\\\\s+<\");\n static Pattern stripCRs = Pattern.compile(\"\\\\r*\");\n\n public static String stripNewlines(String text) {\n return stripper.matcher(text).replaceAll(\"\");\n }\n\n public static String normalizeSpaces(String text) {\n text = stripLines.matcher(text).replaceAll(\"\");\n text = stripper.matcher(text).replaceAll(\"\");\n text = spaceCollapse.matcher(text).replaceAll(\" \");\n text = tagSpaceCollapse.matcher(text).replaceAll(\"><\");\n return text;\n }\n\n public static String stripCRs(String text) {\n return stripCRs.matcher(text).replaceAll(\"\");\n }\n}", "public class ParseTest {\n\n @Test\n public void testSmhBizArticle() throws IOException {\n File in = getFile(\"/htmltests/smh-biz-article-1.html.gz\");\n Document doc = Jsoup.parse(in, \"UTF-8\",\n \"http://www.smh.com.au/business/the-boards-next-fear-the-female-quota-20100106-lteq.html\");\n assertEquals(\"The board’s next fear: the female quota\",\n doc.title()); // note that the apos in the source is a literal ’ (8217), not escaped or '\n assertEquals(\"en\", doc.select(\"html\").attr(\"xml:lang\"));\n\n Elements articleBody = doc.select(\".articleBody > *\");\n assertEquals(17, articleBody.size());\n // todo: more tests!\n\n }\n\n @Test\n public void testNewsHomepage() throws IOException {\n File in = getFile(\"/htmltests/news-com-au-home.html.gz\");\n Document doc = Jsoup.parse(in, \"UTF-8\", \"http://www.news.com.au/\");\n assertEquals(\"News.com.au | News from Australia and around the world online | NewsComAu\", doc.title());\n assertEquals(\"Brace yourself for Metro meltdown\", doc.select(\".id1225817868581 h4\").text().trim());\n\n Element a = doc.select(\"a[href=/entertainment/horoscopes]\").first();\n assertEquals(\"/entertainment/horoscopes\", a.attr(\"href\"));\n assertEquals(\"http://www.news.com.au/entertainment/horoscopes\", a.attr(\"abs:href\"));\n\n Element hs = doc.select(\"a[href*=naughty-corners-are-a-bad-idea]\").first();\n assertEquals(\n \"http://www.heraldsun.com.au/news/naughty-corners-are-a-bad-idea-for-kids/story-e6frf7jo-1225817899003\",\n hs.attr(\"href\"));\n assertEquals(hs.attr(\"href\"), hs.attr(\"abs:href\"));\n }\n\n @Test\n public void testGoogleSearchIpod() throws IOException {\n File in = getFile(\"/htmltests/google-ipod.html.gz\");\n Document doc = Jsoup.parse(in, \"UTF-8\", \"http://www.google.com/search?hl=en&q=ipod&aq=f&oq=&aqi=g10\");\n assertEquals(\"ipod - Google Search\", doc.title());\n Elements results = doc.select(\"h3.r > a\");\n assertEquals(12, results.size());\n assertEquals(\n \"http://news.google.com/news?hl=en&q=ipod&um=1&ie=UTF-8&ei=uYlKS4SbBoGg6gPf-5XXCw&sa=X&oi=news_group&ct=title&resnum=1&ved=0CCIQsQQwAA\",\n results.get(0).attr(\"href\"));\n assertEquals(\"http://www.apple.com/itunes/\",\n results.get(1).attr(\"href\"));\n }\n\n @Test\n public void testYahooJp() throws IOException {\n File in = getFile(\"/htmltests/yahoo-jp.html.gz\");\n Document doc = Jsoup.parse(in, \"UTF-8\", \"http://www.yahoo.co.jp/index.html\"); // http charset is utf-8.\n assertEquals(\"Yahoo! JAPAN\", doc.title());\n Element a = doc.select(\"a[href=t/2322m2]\").first();\n assertEquals(\"http://www.yahoo.co.jp/_ylh=X3oDMTB0NWxnaGxsBF9TAzIwNzcyOTYyNjUEdGlkAzEyBHRtcGwDZ2Ex/t/2322m2\",\n a.attr(\"abs:href\")); // session put into <base>\n assertEquals(\"全国、人気の駅ランキング\", a.text());\n }\n\n @Test\n public void testBaidu() throws IOException {\n // tests <meta http-equiv=\"Content-Type\" content=\"text/html;charset=gb2312\">\n File in = getFile(\"/htmltests/baidu-cn-home.html\");\n Document doc = Jsoup.parse(in, null,\n \"http://www.baidu.com/\"); // http charset is gb2312, but NOT specifying it, to test http-equiv parse\n Element submit = doc.select(\"#su\").first();\n assertEquals(\"百度一下\", submit.attr(\"value\"));\n\n // test from attribute match\n submit = doc.select(\"input[value=百度一下]\").first();\n assertEquals(\"su\", submit.id());\n Element newsLink = doc.select(\"a:contains(新)\").first();\n assertEquals(\"http://news.baidu.com\", newsLink.absUrl(\"href\"));\n\n // check auto-detect from meta\n assertEquals(\"GB2312\", doc.outputSettings().charset().displayName());\n assertEquals(\"<title>百度一下,你就知道 </title>\", doc.select(\"title\").outerHtml());\n\n doc.outputSettings().charset(\"ascii\");\n assertEquals(\"<title>&#x767e;&#x5ea6;&#x4e00;&#x4e0b;&#xff0c;&#x4f60;&#x5c31;&#x77e5;&#x9053; </title>\",\n doc.select(\"title\").outerHtml());\n }\n\n @Test\n public void testBaiduVariant() throws IOException {\n // tests <meta charset> when preceded by another <meta>\n File in = getFile(\"/htmltests/baidu-variant.html\");\n Document doc = Jsoup.parse(in, null,\n \"http://www.baidu.com/\"); // http charset is gb2312, but NOT specifying it, to test http-equiv parse\n // check auto-detect from meta\n assertEquals(\"GB2312\", doc.outputSettings().charset().displayName());\n assertEquals(\"<title>百度一下,你就知道</title>\", doc.select(\"title\").outerHtml());\n }\n\n @Test\n public void testHtml5Charset() throws IOException {\n // test that <meta charset=\"gb2312\"> works\n File in = getFile(\"/htmltests/meta-charset-1.html\");\n Document doc = Jsoup.parse(in, null, \"http://example.com/\"); //gb2312, has html5 <meta charset>\n assertEquals(\"新\", doc.text());\n assertEquals(\"GB2312\", doc.outputSettings().charset().displayName());\n\n // double check, no charset, falls back to utf8 which is incorrect\n in = getFile(\"/htmltests/meta-charset-2.html\"); //\n doc = Jsoup.parse(in, null, \"http://example.com\"); // gb2312, no charset\n assertEquals(\"UTF-8\", doc.outputSettings().charset().displayName());\n assertNotEquals(\"新\", doc.text());\n\n // confirm fallback to utf8\n in = getFile(\"/htmltests/meta-charset-3.html\");\n doc = Jsoup.parse(in, null, \"http://example.com/\"); // utf8, no charset\n assertEquals(\"UTF-8\", doc.outputSettings().charset().displayName());\n assertEquals(\"新\", doc.text());\n }\n\n @Test\n public void testBrokenHtml5CharsetWithASingleDoubleQuote() throws IOException {\n InputStream in = inputStreamFrom(\"<html>\\n\" +\n \"<head><meta charset=UTF-8\\\"></head>\\n\" +\n \"<body></body>\\n\" +\n \"</html>\");\n Document doc = Jsoup.parse(in, null, \"http://example.com/\");\n assertEquals(\"UTF-8\", doc.outputSettings().charset().displayName());\n }\n\n @Test\n public void testNytArticle() throws IOException {\n // has tags like <nyt_text>\n File in = getFile(\"/htmltests/nyt-article-1.html.gz\");\n Document doc = Jsoup.parse(in, null, \"http://www.nytimes.com/2010/07/26/business/global/26bp.html?hp\");\n\n Element headline = doc.select(\"nyt_headline[version=1.0]\").first();\n assertEquals(\"As BP Lays Out Future, It Will Not Include Hayward\", headline.text());\n }\n\n @Test\n public void testYahooArticle() throws IOException {\n File in = getFile(\"/htmltests/yahoo-article-1.html.gz\");\n Document doc = Jsoup.parse(in, \"UTF-8\", \"http://news.yahoo.com/s/nm/20100831/bs_nm/us_gm_china\");\n Element p = doc.select(\"p:contains(Volt will be sold in the United States)\").first();\n assertEquals(\"In July, GM said its electric Chevrolet Volt will be sold in the United States at $41,000 -- $8,000 more than its nearest competitor, the Nissan Leaf.\", p.text());\n }\n\n @Test\n public void testLowercaseUtf8Charset() throws IOException {\n File in = getFile(\"/htmltests/lowercase-charset-test.html\");\n Document doc = Jsoup.parse(in, null);\n\n Element form = doc.select(\"#form\").first();\n assertEquals(2, form.children().size());\n assertEquals(\"UTF-8\", doc.outputSettings().charset().name());\n }\n\n @Test\n public void testXwiki() throws IOException {\n // https://github.com/jhy/jsoup/issues/1324\n // this tests that when in CharacterReader we hit a buffer while marked, we preserve the mark when buffered up and can rewind\n File in = getFile(\"/htmltests/xwiki-1324.html.gz\");\n Document doc = Jsoup.parse(in, null, \"https://localhost/\");\n assertEquals(\"XWiki Jetty HSQLDB 12.1-SNAPSHOT\", doc.select(\"#xwikiplatformversion\").text());\n\n // was getting busted at =userdirectory, because it hit the bufferup point but the mark was then lost. so\n // updated to preserve the mark.\n String wantHtml = \"<a class=\\\"list-group-item\\\" data-id=\\\"userdirectory\\\" href=\\\"/xwiki/bin/admin/XWiki/XWikiPreferences?editor=globaladmin&amp;section=userdirectory\\\" title=\\\"Customize the user directory live table.\\\">User Directory</a>\";\n assertEquals(wantHtml, doc.select(\"[data-id=userdirectory]\").outerHtml());\n }\n\n @Test\n public void testXwikiExpanded() throws IOException {\n // https://github.com/jhy/jsoup/issues/1324\n // this tests that if there is a huge illegal character reference, we can get through a buffer and rewind, and still catch that it's an invalid refence,\n // and the parse tree is correct.\n File in = getFile(\"/htmltests/xwiki-edit.html.gz\");\n Parser parser = Parser.htmlParser();\n Document doc = Jsoup.parse(new GZIPInputStream(new FileInputStream(in)), \"UTF-8\", \"https://localhost/\", parser.setTrackErrors(100));\n ParseErrorList errors = parser.getErrors();\n\n assertEquals(\"XWiki Jetty HSQLDB 12.1-SNAPSHOT\", doc.select(\"#xwikiplatformversion\").text());\n assertEquals(0, errors.size()); // not an invalid reference because did not look legit\n\n // was getting busted at =userdirectory, because it hit the bufferup point but the mark was then lost. so\n // updated to preserve the mark.\n String wantHtml = \"<a class=\\\"list-group-item\\\" data-id=\\\"userdirectory\\\" href=\\\"/xwiki/bin/admin/XWiki/XWikiPreferences?editor=globaladmin&amp;RIGHTHERERIGHTHERERIGHTHERERIGHTHERE\";\n assertTrue(doc.select(\"[data-id=userdirectory]\").outerHtml().startsWith(wantHtml));\n }\n\n @Test public void testWikiExpandedFromString() throws IOException {\n File in = getFile(\"/htmltests/xwiki-edit.html.gz\");\n String html = getFileAsString(in);\n Document doc = Jsoup.parse(html);\n assertEquals(\"XWiki Jetty HSQLDB 12.1-SNAPSHOT\", doc.select(\"#xwikiplatformversion\").text());\n String wantHtml = \"<a class=\\\"list-group-item\\\" data-id=\\\"userdirectory\\\" href=\\\"/xwiki/bin/admin/XWiki/XWikiPreferences?editor=globaladmin&amp;RIGHTHERERIGHTHERERIGHTHERERIGHTHERE\";\n assertTrue(doc.select(\"[data-id=userdirectory]\").outerHtml().startsWith(wantHtml));\n }\n\n @Test public void testWikiFromString() throws IOException {\n File in = getFile(\"/htmltests/xwiki-1324.html.gz\");\n String html = getFileAsString(in);\n Document doc = Jsoup.parse(html);\n assertEquals(\"XWiki Jetty HSQLDB 12.1-SNAPSHOT\", doc.select(\"#xwikiplatformversion\").text());\n String wantHtml = \"<a class=\\\"list-group-item\\\" data-id=\\\"userdirectory\\\" href=\\\"/xwiki/bin/admin/XWiki/XWikiPreferences?editor=globaladmin&amp;section=userdirectory\\\" title=\\\"Customize the user directory live table.\\\">User Directory</a>\";\n assertEquals(wantHtml, doc.select(\"[data-id=userdirectory]\").outerHtml());\n }\n\n @Test public void testFileParseNoCharsetMethod() throws IOException {\n File in = getFile(\"/htmltests/xwiki-1324.html.gz\");\n Document doc = Jsoup.parse(in);\n assertEquals(\"XWiki Jetty HSQLDB 12.1-SNAPSHOT\", doc.select(\"#xwikiplatformversion\").text());\n }\n\n\n public static File getFile(String resourceName) {\n try {\n URL resource = ParseTest.class.getResource(resourceName);\n return resource != null ? new File(resource.toURI()) : new File(\"/404\");\n } catch (URISyntaxException e) {\n throw new IllegalStateException(e);\n }\n }\n\n public static InputStream inputStreamFrom(String s) {\n return new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8));\n }\n\n public static String getFileAsString(File file) throws IOException {\n byte[] bytes;\n if (file.getName().endsWith(\".gz\")) {\n InputStream stream = new GZIPInputStream(new FileInputStream(file));\n ByteBuffer byteBuffer = DataUtil.readToByteBuffer(stream, 0);\n bytes = byteBuffer.array();\n } else {\n bytes = Files.readAllBytes(file.toPath());\n }\n return new String(bytes);\n }\n\n}", "public final class StringUtil {\n // memoised padding up to 21 (blocks 0 to 20 spaces)\n static final String[] padding = {\"\", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \",\n \" \", \" \", \" \", \" \", \" \", \" \", \" \",\n \" \", \" \", \" \", \" \", \" \"};\n\n /**\n * Join a collection of strings by a separator\n * @param strings collection of string objects\n * @param sep string to place between strings\n * @return joined string\n */\n public static String join(Collection<?> strings, String sep) {\n return join(strings.iterator(), sep);\n }\n\n /**\n * Join a collection of strings by a separator\n * @param strings iterator of string objects\n * @param sep string to place between strings\n * @return joined string\n */\n public static String join(Iterator<?> strings, String sep) {\n if (!strings.hasNext())\n return \"\";\n\n String start = strings.next().toString();\n if (!strings.hasNext()) // only one, avoid builder\n return start;\n\n StringJoiner j = new StringJoiner(sep);\n j.add(start);\n while (strings.hasNext()) {\n j.add(strings.next());\n }\n return j.complete();\n }\n\n /**\n * Join an array of strings by a separator\n * @param strings collection of string objects\n * @param sep string to place between strings\n * @return joined string\n */\n public static String join(String[] strings, String sep) {\n return join(Arrays.asList(strings), sep);\n }\n\n /**\n A StringJoiner allows incremental / filtered joining of a set of stringable objects.\n @since 1.14.1\n */\n public static class StringJoiner {\n @Nullable StringBuilder sb = borrowBuilder(); // sets null on builder release so can't accidentally be reused\n final String separator;\n boolean first = true;\n\n /**\n Create a new joiner, that uses the specified separator. MUST call {@link #complete()} or will leak a thread\n local string builder.\n\n @param separator the token to insert between strings\n */\n public StringJoiner(String separator) {\n this.separator = separator;\n }\n\n /**\n Add another item to the joiner, will be separated\n */\n public StringJoiner add(Object stringy) {\n Validate.notNull(sb); // don't reuse\n if (!first)\n sb.append(separator);\n sb.append(stringy);\n first = false;\n return this;\n }\n\n /**\n Append content to the current item; not separated\n */\n public StringJoiner append(Object stringy) {\n Validate.notNull(sb); // don't reuse\n sb.append(stringy);\n return this;\n }\n\n /**\n Return the joined string, and release the builder back to the pool. This joiner cannot be reused.\n */\n public String complete() {\n String string = releaseBuilder(sb);\n sb = null;\n return string;\n }\n }\n\n /**\n * Returns space padding (up to the default max of 30). Use {@link #padding(int, int)} to specify a different limit.\n * @param width amount of padding desired\n * @return string of spaces * width\n * @see #padding(int, int) \n */\n public static String padding(int width) {\n return padding(width, 30);\n }\n\n /**\n * Returns space padding, up to a max of maxPaddingWidth.\n * @param width amount of padding desired\n * @param maxPaddingWidth maximum padding to apply. Set to {@code -1} for unlimited.\n * @return string of spaces * width\n */\n public static String padding(int width, int maxPaddingWidth) {\n Validate.isTrue(width >= 0, \"width must be >= 0\");\n Validate.isTrue(maxPaddingWidth >= -1);\n if (maxPaddingWidth != -1)\n width = Math.min(width, maxPaddingWidth);\n if (width < padding.length)\n return padding[width]; \n char[] out = new char[width];\n for (int i = 0; i < width; i++)\n out[i] = ' ';\n return String.valueOf(out);\n }\n\n /**\n * Tests if a string is blank: null, empty, or only whitespace (\" \", \\r\\n, \\t, etc)\n * @param string string to test\n * @return if string is blank\n */\n public static boolean isBlank(final String string) {\n if (string == null || string.length() == 0)\n return true;\n\n int l = string.length();\n for (int i = 0; i < l; i++) {\n if (!StringUtil.isWhitespace(string.codePointAt(i)))\n return false;\n }\n return true;\n }\n\n /**\n Tests if a string starts with a newline character\n @param string string to test\n @return if its first character is a newline\n */\n public static boolean startsWithNewline(final String string) {\n if (string == null || string.length() == 0)\n return false;\n return string.charAt(0) == '\\n';\n }\n\n /**\n * Tests if a string is numeric, i.e. contains only digit characters\n * @param string string to test\n * @return true if only digit chars, false if empty or null or contains non-digit chars\n */\n public static boolean isNumeric(String string) {\n if (string == null || string.length() == 0)\n return false;\n\n int l = string.length();\n for (int i = 0; i < l; i++) {\n if (!Character.isDigit(string.codePointAt(i)))\n return false;\n }\n return true;\n }\n\n /**\n * Tests if a code point is \"whitespace\" as defined in the HTML spec. Used for output HTML.\n * @param c code point to test\n * @return true if code point is whitespace, false otherwise\n * @see #isActuallyWhitespace(int)\n */\n public static boolean isWhitespace(int c){\n return c == ' ' || c == '\\t' || c == '\\n' || c == '\\f' || c == '\\r';\n }\n\n /**\n * Tests if a code point is \"whitespace\" as defined by what it looks like. Used for Element.text etc.\n * @param c code point to test\n * @return true if code point is whitespace, false otherwise\n */\n public static boolean isActuallyWhitespace(int c){\n return c == ' ' || c == '\\t' || c == '\\n' || c == '\\f' || c == '\\r' || c == 160;\n // 160 is &nbsp; (non-breaking space). Not in the spec but expected.\n }\n\n public static boolean isInvisibleChar(int c) {\n return c == 8203 || c == 173; // zero width sp, soft hyphen\n // previously also included zw non join, zw join - but removing those breaks semantic meaning of text\n }\n\n /**\n * Normalise the whitespace within this string; multiple spaces collapse to a single, and all whitespace characters\n * (e.g. newline, tab) convert to a simple space.\n * @param string content to normalise\n * @return normalised string\n */\n public static String normaliseWhitespace(String string) {\n StringBuilder sb = StringUtil.borrowBuilder();\n appendNormalisedWhitespace(sb, string, false);\n return StringUtil.releaseBuilder(sb);\n }\n\n /**\n * After normalizing the whitespace within a string, appends it to a string builder.\n * @param accum builder to append to\n * @param string string to normalize whitespace within\n * @param stripLeading set to true if you wish to remove any leading whitespace\n */\n public static void appendNormalisedWhitespace(StringBuilder accum, String string, boolean stripLeading) {\n boolean lastWasWhite = false;\n boolean reachedNonWhite = false;\n\n int len = string.length();\n int c;\n for (int i = 0; i < len; i+= Character.charCount(c)) {\n c = string.codePointAt(i);\n if (isActuallyWhitespace(c)) {\n if ((stripLeading && !reachedNonWhite) || lastWasWhite)\n continue;\n accum.append(' ');\n lastWasWhite = true;\n }\n else if (!isInvisibleChar(c)) {\n accum.appendCodePoint(c);\n lastWasWhite = false;\n reachedNonWhite = true;\n }\n }\n }\n\n public static boolean in(final String needle, final String... haystack) {\n final int len = haystack.length;\n for (int i = 0; i < len; i++) {\n if (haystack[i].equals(needle))\n return true;\n }\n return false;\n }\n\n public static boolean inSorted(String needle, String[] haystack) {\n return Arrays.binarySearch(haystack, needle) >= 0;\n }\n\n /**\n Tests that a String contains only ASCII characters.\n @param string scanned string\n @return true if all characters are in range 0 - 127\n */\n public static boolean isAscii(String string) {\n Validate.notNull(string);\n for (int i = 0; i < string.length(); i++) {\n int c = string.charAt(i);\n if (c > 127) { // ascii range\n return false;\n }\n }\n return true;\n }\n\n private static final Pattern extraDotSegmentsPattern = Pattern.compile(\"^/((\\\\.{1,2}/)+)\");\n /**\n * Create a new absolute URL, from a provided existing absolute URL and a relative URL component.\n * @param base the existing absolute base URL\n * @param relUrl the relative URL to resolve. (If it's already absolute, it will be returned)\n * @return the resolved absolute URL\n * @throws MalformedURLException if an error occurred generating the URL\n */\n public static URL resolve(URL base, String relUrl) throws MalformedURLException {\n // workaround: java resolves '//path/file + ?foo' to '//path/?foo', not '//path/file?foo' as desired\n if (relUrl.startsWith(\"?\"))\n relUrl = base.getPath() + relUrl;\n // workaround: //example.com + ./foo = //example.com/./foo, not //example.com/foo\n URL url = new URL(base, relUrl);\n String fixedFile = extraDotSegmentsPattern.matcher(url.getFile()).replaceFirst(\"/\");\n if (url.getRef() != null) {\n fixedFile = fixedFile + \"#\" + url.getRef();\n }\n return new URL(url.getProtocol(), url.getHost(), url.getPort(), fixedFile);\n }\n\n /**\n * Create a new absolute URL, from a provided existing absolute URL and a relative URL component.\n * @param baseUrl the existing absolute base URL\n * @param relUrl the relative URL to resolve. (If it's already absolute, it will be returned)\n * @return an absolute URL if one was able to be generated, or the empty string if not\n */\n public static String resolve(final String baseUrl, final String relUrl) {\n try {\n URL base;\n try {\n base = new URL(baseUrl);\n } catch (MalformedURLException e) {\n // the base is unsuitable, but the attribute/rel may be abs on its own, so try that\n URL abs = new URL(relUrl);\n return abs.toExternalForm();\n }\n return resolve(base, relUrl).toExternalForm();\n } catch (MalformedURLException e) {\n // it may still be valid, just that Java doesn't have a registered stream handler for it, e.g. tel\n // we test here vs at start to normalize supported URLs (e.g. HTTP -> http)\n return validUriScheme.matcher(relUrl).find() ? relUrl : \"\";\n }\n }\n private static final Pattern validUriScheme = Pattern.compile(\"^[a-zA-Z][a-zA-Z0-9+-.]*:\");\n\n private static final ThreadLocal<Stack<StringBuilder>> threadLocalBuilders = new ThreadLocal<Stack<StringBuilder>>() {\n @Override\n protected Stack<StringBuilder> initialValue() {\n return new Stack<>();\n }\n };\n\n /**\n * Maintains cached StringBuilders in a flyweight pattern, to minimize new StringBuilder GCs. The StringBuilder is\n * prevented from growing too large.\n * <p>\n * Care must be taken to release the builder once its work has been completed, with {@link #releaseBuilder}\n * @return an empty StringBuilder\n */\n public static StringBuilder borrowBuilder() {\n Stack<StringBuilder> builders = threadLocalBuilders.get();\n return builders.empty() ?\n new StringBuilder(MaxCachedBuilderSize) :\n builders.pop();\n }\n\n /**\n * Release a borrowed builder. Care must be taken not to use the builder after it has been returned, as its\n * contents may be changed by this method, or by a concurrent thread.\n * @param sb the StringBuilder to release.\n * @return the string value of the released String Builder (as an incentive to release it!).\n */\n public static String releaseBuilder(StringBuilder sb) {\n Validate.notNull(sb);\n String string = sb.toString();\n\n if (sb.length() > MaxCachedBuilderSize)\n sb = new StringBuilder(MaxCachedBuilderSize); // make sure it hasn't grown too big\n else\n sb.delete(0, sb.length()); // make sure it's emptied on release\n\n Stack<StringBuilder> builders = threadLocalBuilders.get();\n builders.push(sb);\n\n while (builders.size() > MaxIdleBuilders) {\n builders.pop();\n }\n return string;\n }\n\n private static final int MaxCachedBuilderSize = 8 * 1024;\n private static final int MaxIdleBuilders = 8;\n}", "public class Safelist {\n private Set<TagName> tagNames; // tags allowed, lower case. e.g. [p, br, span]\n private Map<TagName, Set<AttributeKey>> attributes; // tag -> attribute[]. allowed attributes [href] for a tag.\n private Map<TagName, Map<AttributeKey, AttributeValue>> enforcedAttributes; // always set these attribute values\n private Map<TagName, Map<AttributeKey, Set<Protocol>>> protocols; // allowed URL protocols for attributes\n private boolean preserveRelativeLinks; // option to preserve relative links\n\n /**\n This safelist allows only text nodes: all HTML will be stripped.\n\n @return safelist\n */\n public static Safelist none() {\n return new Safelist();\n }\n\n /**\n This safelist allows only simple text formatting: <code>b, em, i, strong, u</code>. All other HTML (tags and\n attributes) will be removed.\n\n @return safelist\n */\n public static Safelist simpleText() {\n return new Safelist()\n .addTags(\"b\", \"em\", \"i\", \"strong\", \"u\")\n ;\n }\n\n /**\n <p>\n This safelist allows a fuller range of text nodes: <code>a, b, blockquote, br, cite, code, dd, dl, dt, em, i, li,\n ol, p, pre, q, small, span, strike, strong, sub, sup, u, ul</code>, and appropriate attributes.\n </p>\n <p>\n Links (<code>a</code> elements) can point to <code>http, https, ftp, mailto</code>, and have an enforced\n <code>rel=nofollow</code> attribute.\n </p>\n <p>\n Does not allow images.\n </p>\n\n @return safelist\n */\n public static Safelist basic() {\n return new Safelist()\n .addTags(\n \"a\", \"b\", \"blockquote\", \"br\", \"cite\", \"code\", \"dd\", \"dl\", \"dt\", \"em\",\n \"i\", \"li\", \"ol\", \"p\", \"pre\", \"q\", \"small\", \"span\", \"strike\", \"strong\", \"sub\",\n \"sup\", \"u\", \"ul\")\n\n .addAttributes(\"a\", \"href\")\n .addAttributes(\"blockquote\", \"cite\")\n .addAttributes(\"q\", \"cite\")\n\n .addProtocols(\"a\", \"href\", \"ftp\", \"http\", \"https\", \"mailto\")\n .addProtocols(\"blockquote\", \"cite\", \"http\", \"https\")\n .addProtocols(\"cite\", \"cite\", \"http\", \"https\")\n\n .addEnforcedAttribute(\"a\", \"rel\", \"nofollow\")\n ;\n\n }\n\n /**\n This safelist allows the same text tags as {@link #basic}, and also allows <code>img</code> tags, with appropriate\n attributes, with <code>src</code> pointing to <code>http</code> or <code>https</code>.\n\n @return safelist\n */\n public static Safelist basicWithImages() {\n return basic()\n .addTags(\"img\")\n .addAttributes(\"img\", \"align\", \"alt\", \"height\", \"src\", \"title\", \"width\")\n .addProtocols(\"img\", \"src\", \"http\", \"https\")\n ;\n }\n\n /**\n This safelist allows a full range of text and structural body HTML: <code>a, b, blockquote, br, caption, cite,\n code, col, colgroup, dd, div, dl, dt, em, h1, h2, h3, h4, h5, h6, i, img, li, ol, p, pre, q, small, span, strike, strong, sub,\n sup, table, tbody, td, tfoot, th, thead, tr, u, ul</code>\n <p>\n Links do not have an enforced <code>rel=nofollow</code> attribute, but you can add that if desired.\n </p>\n\n @return safelist\n */\n public static Safelist relaxed() {\n return new Safelist()\n .addTags(\n \"a\", \"b\", \"blockquote\", \"br\", \"caption\", \"cite\", \"code\", \"col\",\n \"colgroup\", \"dd\", \"div\", \"dl\", \"dt\", \"em\", \"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\",\n \"i\", \"img\", \"li\", \"ol\", \"p\", \"pre\", \"q\", \"small\", \"span\", \"strike\", \"strong\",\n \"sub\", \"sup\", \"table\", \"tbody\", \"td\", \"tfoot\", \"th\", \"thead\", \"tr\", \"u\",\n \"ul\")\n\n .addAttributes(\"a\", \"href\", \"title\")\n .addAttributes(\"blockquote\", \"cite\")\n .addAttributes(\"col\", \"span\", \"width\")\n .addAttributes(\"colgroup\", \"span\", \"width\")\n .addAttributes(\"img\", \"align\", \"alt\", \"height\", \"src\", \"title\", \"width\")\n .addAttributes(\"ol\", \"start\", \"type\")\n .addAttributes(\"q\", \"cite\")\n .addAttributes(\"table\", \"summary\", \"width\")\n .addAttributes(\"td\", \"abbr\", \"axis\", \"colspan\", \"rowspan\", \"width\")\n .addAttributes(\n \"th\", \"abbr\", \"axis\", \"colspan\", \"rowspan\", \"scope\",\n \"width\")\n .addAttributes(\"ul\", \"type\")\n\n .addProtocols(\"a\", \"href\", \"ftp\", \"http\", \"https\", \"mailto\")\n .addProtocols(\"blockquote\", \"cite\", \"http\", \"https\")\n .addProtocols(\"cite\", \"cite\", \"http\", \"https\")\n .addProtocols(\"img\", \"src\", \"http\", \"https\")\n .addProtocols(\"q\", \"cite\", \"http\", \"https\")\n ;\n }\n\n /**\n Create a new, empty safelist. Generally it will be better to start with a default prepared safelist instead.\n\n @see #basic()\n @see #basicWithImages()\n @see #simpleText()\n @see #relaxed()\n */\n public Safelist() {\n tagNames = new HashSet<>();\n attributes = new HashMap<>();\n enforcedAttributes = new HashMap<>();\n protocols = new HashMap<>();\n preserveRelativeLinks = false;\n }\n\n /**\n Deep copy an existing Safelist to a new Safelist.\n @param copy the Safelist to copy\n */\n public Safelist(Safelist copy) {\n this();\n tagNames.addAll(copy.tagNames);\n attributes.putAll(copy.attributes);\n enforcedAttributes.putAll(copy.enforcedAttributes);\n protocols.putAll(copy.protocols);\n preserveRelativeLinks = copy.preserveRelativeLinks;\n }\n\n /**\n Add a list of allowed elements to a safelist. (If a tag is not allowed, it will be removed from the HTML.)\n\n @param tags tag names to allow\n @return this (for chaining)\n */\n public Safelist addTags(String... tags) {\n Validate.notNull(tags);\n\n for (String tagName : tags) {\n Validate.notEmpty(tagName);\n tagNames.add(TagName.valueOf(tagName));\n }\n return this;\n }\n\n /**\n Remove a list of allowed elements from a safelist. (If a tag is not allowed, it will be removed from the HTML.)\n\n @param tags tag names to disallow\n @return this (for chaining)\n */\n public Safelist removeTags(String... tags) {\n Validate.notNull(tags);\n\n for(String tag: tags) {\n Validate.notEmpty(tag);\n TagName tagName = TagName.valueOf(tag);\n\n if(tagNames.remove(tagName)) { // Only look in sub-maps if tag was allowed\n attributes.remove(tagName);\n enforcedAttributes.remove(tagName);\n protocols.remove(tagName);\n }\n }\n return this;\n }\n\n /**\n Add a list of allowed attributes to a tag. (If an attribute is not allowed on an element, it will be removed.)\n <p>\n E.g.: <code>addAttributes(\"a\", \"href\", \"class\")</code> allows <code>href</code> and <code>class</code> attributes\n on <code>a</code> tags.\n </p>\n <p>\n To make an attribute valid for <b>all tags</b>, use the pseudo tag <code>:all</code>, e.g.\n <code>addAttributes(\":all\", \"class\")</code>.\n </p>\n\n @param tag The tag the attributes are for. The tag will be added to the allowed tag list if necessary.\n @param attributes List of valid attributes for the tag\n @return this (for chaining)\n */\n public Safelist addAttributes(String tag, String... attributes) {\n Validate.notEmpty(tag);\n Validate.notNull(attributes);\n Validate.isTrue(attributes.length > 0, \"No attribute names supplied.\");\n\n TagName tagName = TagName.valueOf(tag);\n tagNames.add(tagName);\n Set<AttributeKey> attributeSet = new HashSet<>();\n for (String key : attributes) {\n Validate.notEmpty(key);\n attributeSet.add(AttributeKey.valueOf(key));\n }\n if (this.attributes.containsKey(tagName)) {\n Set<AttributeKey> currentSet = this.attributes.get(tagName);\n currentSet.addAll(attributeSet);\n } else {\n this.attributes.put(tagName, attributeSet);\n }\n return this;\n }\n\n /**\n Remove a list of allowed attributes from a tag. (If an attribute is not allowed on an element, it will be removed.)\n <p>\n E.g.: <code>removeAttributes(\"a\", \"href\", \"class\")</code> disallows <code>href</code> and <code>class</code>\n attributes on <code>a</code> tags.\n </p>\n <p>\n To make an attribute invalid for <b>all tags</b>, use the pseudo tag <code>:all</code>, e.g.\n <code>removeAttributes(\":all\", \"class\")</code>.\n </p>\n\n @param tag The tag the attributes are for.\n @param attributes List of invalid attributes for the tag\n @return this (for chaining)\n */\n public Safelist removeAttributes(String tag, String... attributes) {\n Validate.notEmpty(tag);\n Validate.notNull(attributes);\n Validate.isTrue(attributes.length > 0, \"No attribute names supplied.\");\n\n TagName tagName = TagName.valueOf(tag);\n Set<AttributeKey> attributeSet = new HashSet<>();\n for (String key : attributes) {\n Validate.notEmpty(key);\n attributeSet.add(AttributeKey.valueOf(key));\n }\n if(tagNames.contains(tagName) && this.attributes.containsKey(tagName)) { // Only look in sub-maps if tag was allowed\n Set<AttributeKey> currentSet = this.attributes.get(tagName);\n currentSet.removeAll(attributeSet);\n\n if(currentSet.isEmpty()) // Remove tag from attribute map if no attributes are allowed for tag\n this.attributes.remove(tagName);\n }\n if(tag.equals(\":all\")) // Attribute needs to be removed from all individually set tags\n for(TagName name: this.attributes.keySet()) {\n Set<AttributeKey> currentSet = this.attributes.get(name);\n currentSet.removeAll(attributeSet);\n\n if(currentSet.isEmpty()) // Remove tag from attribute map if no attributes are allowed for tag\n this.attributes.remove(name);\n }\n return this;\n }\n\n /**\n Add an enforced attribute to a tag. An enforced attribute will always be added to the element. If the element\n already has the attribute set, it will be overridden with this value.\n <p>\n E.g.: <code>addEnforcedAttribute(\"a\", \"rel\", \"nofollow\")</code> will make all <code>a</code> tags output as\n <code>&lt;a href=\"...\" rel=\"nofollow\"&gt;</code>\n </p>\n\n @param tag The tag the enforced attribute is for. The tag will be added to the allowed tag list if necessary.\n @param attribute The attribute name\n @param value The enforced attribute value\n @return this (for chaining)\n */\n public Safelist addEnforcedAttribute(String tag, String attribute, String value) {\n Validate.notEmpty(tag);\n Validate.notEmpty(attribute);\n Validate.notEmpty(value);\n\n TagName tagName = TagName.valueOf(tag);\n tagNames.add(tagName);\n AttributeKey attrKey = AttributeKey.valueOf(attribute);\n AttributeValue attrVal = AttributeValue.valueOf(value);\n\n if (enforcedAttributes.containsKey(tagName)) {\n enforcedAttributes.get(tagName).put(attrKey, attrVal);\n } else {\n Map<AttributeKey, AttributeValue> attrMap = new HashMap<>();\n attrMap.put(attrKey, attrVal);\n enforcedAttributes.put(tagName, attrMap);\n }\n return this;\n }\n\n /**\n Remove a previously configured enforced attribute from a tag.\n\n @param tag The tag the enforced attribute is for.\n @param attribute The attribute name\n @return this (for chaining)\n */\n public Safelist removeEnforcedAttribute(String tag, String attribute) {\n Validate.notEmpty(tag);\n Validate.notEmpty(attribute);\n\n TagName tagName = TagName.valueOf(tag);\n if(tagNames.contains(tagName) && enforcedAttributes.containsKey(tagName)) {\n AttributeKey attrKey = AttributeKey.valueOf(attribute);\n Map<AttributeKey, AttributeValue> attrMap = enforcedAttributes.get(tagName);\n attrMap.remove(attrKey);\n\n if(attrMap.isEmpty()) // Remove tag from enforced attribute map if no enforced attributes are present\n enforcedAttributes.remove(tagName);\n }\n return this;\n }\n\n /**\n * Configure this Safelist to preserve relative links in an element's URL attribute, or convert them to absolute\n * links. By default, this is <b>false</b>: URLs will be made absolute (e.g. start with an allowed protocol, like\n * e.g. {@code http://}.\n * <p>\n * Note that when handling relative links, the input document must have an appropriate {@code base URI} set when\n * parsing, so that the link's protocol can be confirmed. Regardless of the setting of the {@code preserve relative\n * links} option, the link must be resolvable against the base URI to an allowed protocol; otherwise the attribute\n * will be removed.\n * </p>\n *\n * @param preserve {@code true} to allow relative links, {@code false} (default) to deny\n * @return this Safelist, for chaining.\n * @see #addProtocols\n */\n public Safelist preserveRelativeLinks(boolean preserve) {\n preserveRelativeLinks = preserve;\n return this;\n }\n\n /**\n Add allowed URL protocols for an element's URL attribute. This restricts the possible values of the attribute to\n URLs with the defined protocol.\n <p>\n E.g.: <code>addProtocols(\"a\", \"href\", \"ftp\", \"http\", \"https\")</code>\n </p>\n <p>\n To allow a link to an in-page URL anchor (i.e. <code>&lt;a href=\"#anchor\"&gt;</code>, add a <code>#</code>:<br>\n E.g.: <code>addProtocols(\"a\", \"href\", \"#\")</code>\n </p>\n\n @param tag Tag the URL protocol is for\n @param attribute Attribute name\n @param protocols List of valid protocols\n @return this, for chaining\n */\n public Safelist addProtocols(String tag, String attribute, String... protocols) {\n Validate.notEmpty(tag);\n Validate.notEmpty(attribute);\n Validate.notNull(protocols);\n\n TagName tagName = TagName.valueOf(tag);\n AttributeKey attrKey = AttributeKey.valueOf(attribute);\n Map<AttributeKey, Set<Protocol>> attrMap;\n Set<Protocol> protSet;\n\n if (this.protocols.containsKey(tagName)) {\n attrMap = this.protocols.get(tagName);\n } else {\n attrMap = new HashMap<>();\n this.protocols.put(tagName, attrMap);\n }\n if (attrMap.containsKey(attrKey)) {\n protSet = attrMap.get(attrKey);\n } else {\n protSet = new HashSet<>();\n attrMap.put(attrKey, protSet);\n }\n for (String protocol : protocols) {\n Validate.notEmpty(protocol);\n Protocol prot = Protocol.valueOf(protocol);\n protSet.add(prot);\n }\n return this;\n }\n\n /**\n Remove allowed URL protocols for an element's URL attribute. If you remove all protocols for an attribute, that\n attribute will allow any protocol.\n <p>\n E.g.: <code>removeProtocols(\"a\", \"href\", \"ftp\")</code>\n </p>\n\n @param tag Tag the URL protocol is for\n @param attribute Attribute name\n @param removeProtocols List of invalid protocols\n @return this, for chaining\n */\n public Safelist removeProtocols(String tag, String attribute, String... removeProtocols) {\n Validate.notEmpty(tag);\n Validate.notEmpty(attribute);\n Validate.notNull(removeProtocols);\n\n TagName tagName = TagName.valueOf(tag);\n AttributeKey attr = AttributeKey.valueOf(attribute);\n\n // make sure that what we're removing actually exists; otherwise can open the tag to any data and that can\n // be surprising\n Validate.isTrue(protocols.containsKey(tagName), \"Cannot remove a protocol that is not set.\");\n Map<AttributeKey, Set<Protocol>> tagProtocols = protocols.get(tagName);\n Validate.isTrue(tagProtocols.containsKey(attr), \"Cannot remove a protocol that is not set.\");\n\n Set<Protocol> attrProtocols = tagProtocols.get(attr);\n for (String protocol : removeProtocols) {\n Validate.notEmpty(protocol);\n attrProtocols.remove(Protocol.valueOf(protocol));\n }\n\n if (attrProtocols.isEmpty()) { // Remove protocol set if empty\n tagProtocols.remove(attr);\n if (tagProtocols.isEmpty()) // Remove entry for tag if empty\n protocols.remove(tagName);\n }\n return this;\n }\n\n /**\n * Test if the supplied tag is allowed by this safelist\n * @param tag test tag\n * @return true if allowed\n */\n protected boolean isSafeTag(String tag) {\n return tagNames.contains(TagName.valueOf(tag));\n }\n\n /**\n * Test if the supplied attribute is allowed by this safelist for this tag\n * @param tagName tag to consider allowing the attribute in\n * @param el element under test, to confirm protocol\n * @param attr attribute under test\n * @return true if allowed\n */\n protected boolean isSafeAttribute(String tagName, Element el, Attribute attr) {\n TagName tag = TagName.valueOf(tagName);\n AttributeKey key = AttributeKey.valueOf(attr.getKey());\n\n Set<AttributeKey> okSet = attributes.get(tag);\n if (okSet != null && okSet.contains(key)) {\n if (protocols.containsKey(tag)) {\n Map<AttributeKey, Set<Protocol>> attrProts = protocols.get(tag);\n // ok if not defined protocol; otherwise test\n return !attrProts.containsKey(key) || testValidProtocol(el, attr, attrProts.get(key));\n } else { // attribute found, no protocols defined, so OK\n return true;\n }\n }\n // might be an enforced attribute?\n Map<AttributeKey, AttributeValue> enforcedSet = enforcedAttributes.get(tag);\n if (enforcedSet != null) {\n Attributes expect = getEnforcedAttributes(tagName);\n String attrKey = attr.getKey();\n if (expect.hasKeyIgnoreCase(attrKey)) {\n return expect.getIgnoreCase(attrKey).equals(attr.getValue());\n }\n }\n // no attributes defined for tag, try :all tag\n return !tagName.equals(\":all\") && isSafeAttribute(\":all\", el, attr);\n }\n\n private boolean testValidProtocol(Element el, Attribute attr, Set<Protocol> protocols) {\n // try to resolve relative urls to abs, and optionally update the attribute so output html has abs.\n // rels without a baseuri get removed\n String value = el.absUrl(attr.getKey());\n if (value.length() == 0)\n value = attr.getValue(); // if it could not be made abs, run as-is to allow custom unknown protocols\n if (!preserveRelativeLinks)\n attr.setValue(value);\n \n for (Protocol protocol : protocols) {\n String prot = protocol.toString();\n\n if (prot.equals(\"#\")) { // allows anchor links\n if (isValidAnchor(value)) {\n return true;\n } else {\n continue;\n }\n }\n\n prot += \":\";\n\n if (lowerCase(value).startsWith(prot)) {\n return true;\n }\n }\n return false;\n }\n\n private boolean isValidAnchor(String value) {\n return value.startsWith(\"#\") && !value.matches(\".*\\\\s.*\");\n }\n\n Attributes getEnforcedAttributes(String tagName) {\n Attributes attrs = new Attributes();\n TagName tag = TagName.valueOf(tagName);\n if (enforcedAttributes.containsKey(tag)) {\n Map<AttributeKey, AttributeValue> keyVals = enforcedAttributes.get(tag);\n for (Map.Entry<AttributeKey, AttributeValue> entry : keyVals.entrySet()) {\n attrs.put(entry.getKey().toString(), entry.getValue().toString());\n }\n }\n return attrs;\n }\n \n // named types for config. All just hold strings, but here for my sanity.\n\n static class TagName extends TypedValue {\n TagName(String value) {\n super(value);\n }\n\n static TagName valueOf(String value) {\n return new TagName(value);\n }\n }\n\n static class AttributeKey extends TypedValue {\n AttributeKey(String value) {\n super(value);\n }\n\n static AttributeKey valueOf(String value) {\n return new AttributeKey(value);\n }\n }\n\n static class AttributeValue extends TypedValue {\n AttributeValue(String value) {\n super(value);\n }\n\n static AttributeValue valueOf(String value) {\n return new AttributeValue(value);\n }\n }\n\n static class Protocol extends TypedValue {\n Protocol(String value) {\n super(value);\n }\n\n static Protocol valueOf(String value) {\n return new Protocol(value);\n }\n }\n\n abstract static class TypedValue {\n private String value;\n\n TypedValue(String value) {\n Validate.notNull(value);\n this.value = value;\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((value == null) ? 0 : value.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) return true;\n if (obj == null) return false;\n if (getClass() != obj.getClass()) return false;\n TypedValue other = (TypedValue) obj;\n if (value == null) {\n return other.value == null;\n } else return value.equals(other.value);\n }\n\n @Override\n public String toString() {\n return value;\n }\n }\n}", "public class Elements extends ArrayList<Element> {\n public Elements() {\n }\n\n public Elements(int initialCapacity) {\n super(initialCapacity);\n }\n\n public Elements(Collection<Element> elements) {\n super(elements);\n }\n \n public Elements(List<Element> elements) {\n super(elements);\n }\n \n public Elements(Element... elements) {\n \tsuper(Arrays.asList(elements));\n }\n\n /**\n * Creates a deep copy of these elements.\n * @return a deep copy\n */\n @Override\n\tpublic Elements clone() {\n Elements clone = new Elements(size());\n\n for(Element e : this)\n \t\tclone.add(e.clone());\n \t\n \treturn clone;\n\t}\n\n\t// attribute methods\n /**\n Get an attribute value from the first matched element that has the attribute.\n @param attributeKey The attribute key.\n @return The attribute value from the first matched element that has the attribute.. If no elements were matched (isEmpty() == true),\n or if the no elements have the attribute, returns empty string.\n @see #hasAttr(String)\n */\n public String attr(String attributeKey) {\n for (Element element : this) {\n if (element.hasAttr(attributeKey))\n return element.attr(attributeKey);\n }\n return \"\";\n }\n\n /**\n Checks if any of the matched elements have this attribute defined.\n @param attributeKey attribute key\n @return true if any of the elements have the attribute; false if none do.\n */\n public boolean hasAttr(String attributeKey) {\n for (Element element : this) {\n if (element.hasAttr(attributeKey))\n return true;\n }\n return false;\n }\n\n /**\n * Get the attribute value for each of the matched elements. If an element does not have this attribute, no value is\n * included in the result set for that element.\n * @param attributeKey the attribute name to return values for. You can add the {@code abs:} prefix to the key to\n * get absolute URLs from relative URLs, e.g.: {@code doc.select(\"a\").eachAttr(\"abs:href\")} .\n * @return a list of each element's attribute value for the attribute\n */\n public List<String> eachAttr(String attributeKey) {\n List<String> attrs = new ArrayList<>(size());\n for (Element element : this) {\n if (element.hasAttr(attributeKey))\n attrs.add(element.attr(attributeKey));\n }\n return attrs;\n }\n\n /**\n * Set an attribute on all matched elements.\n * @param attributeKey attribute key\n * @param attributeValue attribute value\n * @return this\n */\n public Elements attr(String attributeKey, String attributeValue) {\n for (Element element : this) {\n element.attr(attributeKey, attributeValue);\n }\n return this;\n }\n\n /**\n * Remove an attribute from every matched element.\n * @param attributeKey The attribute to remove.\n * @return this (for chaining)\n */\n public Elements removeAttr(String attributeKey) {\n for (Element element : this) {\n element.removeAttr(attributeKey);\n }\n return this;\n }\n\n /**\n Add the class name to every matched element's {@code class} attribute.\n @param className class name to add\n @return this\n */\n public Elements addClass(String className) {\n for (Element element : this) {\n element.addClass(className);\n }\n return this;\n }\n\n /**\n Remove the class name from every matched element's {@code class} attribute, if present.\n @param className class name to remove\n @return this\n */\n public Elements removeClass(String className) {\n for (Element element : this) {\n element.removeClass(className);\n }\n return this;\n }\n\n /**\n Toggle the class name on every matched element's {@code class} attribute.\n @param className class name to add if missing, or remove if present, from every element.\n @return this\n */\n public Elements toggleClass(String className) {\n for (Element element : this) {\n element.toggleClass(className);\n }\n return this;\n }\n\n /**\n Determine if any of the matched elements have this class name set in their {@code class} attribute.\n @param className class name to check for\n @return true if any do, false if none do\n */\n public boolean hasClass(String className) {\n for (Element element : this) {\n if (element.hasClass(className))\n return true;\n }\n return false;\n }\n \n /**\n * Get the form element's value of the first matched element.\n * @return The form element's value, or empty if not set.\n * @see Element#val()\n */\n public String val() {\n if (size() > 0)\n //noinspection ConstantConditions\n return first().val(); // first() != null as size() > 0\n else\n return \"\";\n }\n \n /**\n * Set the form element's value in each of the matched elements.\n * @param value The value to set into each matched element\n * @return this (for chaining)\n */\n public Elements val(String value) {\n for (Element element : this)\n element.val(value);\n return this;\n }\n \n /**\n * Get the combined text of all the matched elements.\n * <p>\n * Note that it is possible to get repeats if the matched elements contain both parent elements and their own\n * children, as the Element.text() method returns the combined text of a parent and all its children.\n * @return string of all text: unescaped and no HTML.\n * @see Element#text()\n * @see #eachText()\n */\n public String text() {\n StringBuilder sb = StringUtil.borrowBuilder();\n for (Element element : this) {\n if (sb.length() != 0)\n sb.append(\" \");\n sb.append(element.text());\n }\n return StringUtil.releaseBuilder(sb);\n }\n\n /**\n Test if any matched Element has any text content, that is not just whitespace.\n @return true if any element has non-blank text content.\n @see Element#hasText()\n */\n public boolean hasText() {\n for (Element element: this) {\n if (element.hasText())\n return true;\n }\n return false;\n }\n\n /**\n * Get the text content of each of the matched elements. If an element has no text, then it is not included in the\n * result.\n * @return A list of each matched element's text content.\n * @see Element#text()\n * @see Element#hasText()\n * @see #text()\n */\n public List<String> eachText() {\n ArrayList<String> texts = new ArrayList<>(size());\n for (Element el: this) {\n if (el.hasText())\n texts.add(el.text());\n }\n return texts;\n }\n \n /**\n * Get the combined inner HTML of all matched elements.\n * @return string of all element's inner HTML.\n * @see #text()\n * @see #outerHtml()\n */\n public String html() {\n StringBuilder sb = StringUtil.borrowBuilder();\n for (Element element : this) {\n if (sb.length() != 0)\n sb.append(\"\\n\");\n sb.append(element.html());\n }\n return StringUtil.releaseBuilder(sb);\n }\n \n /**\n * Get the combined outer HTML of all matched elements.\n * @return string of all element's outer HTML.\n * @see #text()\n * @see #html()\n */\n public String outerHtml() {\n StringBuilder sb = StringUtil.borrowBuilder();\n for (Element element : this) {\n if (sb.length() != 0)\n sb.append(\"\\n\");\n sb.append(element.outerHtml());\n }\n return StringUtil.releaseBuilder(sb);\n }\n\n /**\n * Get the combined outer HTML of all matched elements. Alias of {@link #outerHtml()}.\n * @return string of all element's outer HTML.\n * @see #text()\n * @see #html()\n */\n @Override\n public String toString() {\n return outerHtml();\n }\n\n /**\n * Update (rename) the tag name of each matched element. For example, to change each {@code <i>} to a {@code <em>}, do\n * {@code doc.select(\"i\").tagName(\"em\");}\n *\n * @param tagName the new tag name\n * @return this, for chaining\n * @see Element#tagName(String)\n */\n public Elements tagName(String tagName) {\n for (Element element : this) {\n element.tagName(tagName);\n }\n return this;\n }\n \n /**\n * Set the inner HTML of each matched element.\n * @param html HTML to parse and set into each matched element.\n * @return this, for chaining\n * @see Element#html(String)\n */\n public Elements html(String html) {\n for (Element element : this) {\n element.html(html);\n }\n return this;\n }\n \n /**\n * Add the supplied HTML to the start of each matched element's inner HTML.\n * @param html HTML to add inside each element, before the existing HTML\n * @return this, for chaining\n * @see Element#prepend(String)\n */\n public Elements prepend(String html) {\n for (Element element : this) {\n element.prepend(html);\n }\n return this;\n }\n \n /**\n * Add the supplied HTML to the end of each matched element's inner HTML.\n * @param html HTML to add inside each element, after the existing HTML\n * @return this, for chaining\n * @see Element#append(String)\n */\n public Elements append(String html) {\n for (Element element : this) {\n element.append(html);\n }\n return this;\n }\n \n /**\n * Insert the supplied HTML before each matched element's outer HTML.\n * @param html HTML to insert before each element\n * @return this, for chaining\n * @see Element#before(String)\n */\n public Elements before(String html) {\n for (Element element : this) {\n element.before(html);\n }\n return this;\n }\n \n /**\n * Insert the supplied HTML after each matched element's outer HTML.\n * @param html HTML to insert after each element\n * @return this, for chaining\n * @see Element#after(String)\n */\n public Elements after(String html) {\n for (Element element : this) {\n element.after(html);\n }\n return this;\n }\n\n /**\n Wrap the supplied HTML around each matched elements. For example, with HTML\n {@code <p><b>This</b> is <b>Jsoup</b></p>},\n <code>doc.select(\"b\").wrap(\"&lt;i&gt;&lt;/i&gt;\");</code>\n becomes {@code <p><i><b>This</b></i> is <i><b>jsoup</b></i></p>}\n @param html HTML to wrap around each element, e.g. {@code <div class=\"head\"></div>}. Can be arbitrarily deep.\n @return this (for chaining)\n @see Element#wrap\n */\n public Elements wrap(String html) {\n Validate.notEmpty(html);\n for (Element element : this) {\n element.wrap(html);\n }\n return this;\n }\n\n /**\n * Removes the matched elements from the DOM, and moves their children up into their parents. This has the effect of\n * dropping the elements but keeping their children.\n * <p>\n * This is useful for e.g removing unwanted formatting elements but keeping their contents.\n * </p>\n * \n * E.g. with HTML: <p>{@code <div><font>One</font> <font><a href=\"/\">Two</a></font></div>}</p>\n * <p>{@code doc.select(\"font\").unwrap();}</p>\n * <p>HTML = {@code <div>One <a href=\"/\">Two</a></div>}</p>\n *\n * @return this (for chaining)\n * @see Node#unwrap\n */\n public Elements unwrap() {\n for (Element element : this) {\n element.unwrap();\n }\n return this;\n }\n\n /**\n * Empty (remove all child nodes from) each matched element. This is similar to setting the inner HTML of each\n * element to nothing.\n * <p>\n * E.g. HTML: {@code <div><p>Hello <b>there</b></p> <p>now</p></div>}<br>\n * <code>doc.select(\"p\").empty();</code><br>\n * HTML = {@code <div><p></p> <p></p></div>}\n * @return this, for chaining\n * @see Element#empty()\n * @see #remove()\n */\n public Elements empty() {\n for (Element element : this) {\n element.empty();\n }\n return this;\n }\n\n /**\n * Remove each matched element from the DOM. This is similar to setting the outer HTML of each element to nothing.\n * <p>\n * E.g. HTML: {@code <div><p>Hello</p> <p>there</p> <img /></div>}<br>\n * <code>doc.select(\"p\").remove();</code><br>\n * HTML = {@code <div> <img /></div>}\n * <p>\n * Note that this method should not be used to clean user-submitted HTML; rather, use {@link org.jsoup.safety.Cleaner} to clean HTML.\n * @return this, for chaining\n * @see Element#empty()\n * @see #empty()\n */\n public Elements remove() {\n for (Element element : this) {\n element.remove();\n }\n return this;\n }\n \n // filters\n \n /**\n * Find matching elements within this element list.\n * @param query A {@link Selector} query\n * @return the filtered list of elements, or an empty list if none match.\n */\n public Elements select(String query) {\n return Selector.select(query, this);\n }\n\n /**\n * Remove elements from this list that match the {@link Selector} query.\n * <p>\n * E.g. HTML: {@code <div class=logo>One</div> <div>Two</div>}<br>\n * <code>Elements divs = doc.select(\"div\").not(\".logo\");</code><br>\n * Result: {@code divs: [<div>Two</div>]}\n * <p>\n * @param query the selector query whose results should be removed from these elements\n * @return a new elements list that contains only the filtered results\n */\n public Elements not(String query) {\n Elements out = Selector.select(query, this);\n return Selector.filterOut(this, out);\n }\n \n /**\n * Get the <i>nth</i> matched element as an Elements object.\n * <p>\n * See also {@link #get(int)} to retrieve an Element.\n * @param index the (zero-based) index of the element in the list to retain\n * @return Elements containing only the specified element, or, if that element did not exist, an empty list.\n */\n public Elements eq(int index) {\n return size() > index ? new Elements(get(index)) : new Elements();\n }\n \n /**\n * Test if any of the matched elements match the supplied query.\n * @param query A selector\n * @return true if at least one element in the list matches the query.\n */\n public boolean is(String query) {\n Evaluator eval = QueryParser.parse(query);\n for (Element e : this) {\n if (e.is(eval))\n return true;\n }\n return false;\n }\n\n /**\n * Get the immediate next element sibling of each element in this list.\n * @return next element siblings.\n */\n public Elements next() {\n return siblings(null, true, false);\n }\n\n /**\n * Get the immediate next element sibling of each element in this list, filtered by the query.\n * @param query CSS query to match siblings against\n * @return next element siblings.\n */\n public Elements next(String query) {\n return siblings(query, true, false);\n }\n\n /**\n * Get each of the following element siblings of each element in this list.\n * @return all following element siblings.\n */\n public Elements nextAll() {\n return siblings(null, true, true);\n }\n\n /**\n * Get each of the following element siblings of each element in this list, that match the query.\n * @param query CSS query to match siblings against\n * @return all following element siblings.\n */\n public Elements nextAll(String query) {\n return siblings(query, true, true);\n }\n\n /**\n * Get the immediate previous element sibling of each element in this list.\n * @return previous element siblings.\n */\n public Elements prev() {\n return siblings(null, false, false);\n }\n\n /**\n * Get the immediate previous element sibling of each element in this list, filtered by the query.\n * @param query CSS query to match siblings against\n * @return previous element siblings.\n */\n public Elements prev(String query) {\n return siblings(query, false, false);\n }\n\n /**\n * Get each of the previous element siblings of each element in this list.\n * @return all previous element siblings.\n */\n public Elements prevAll() {\n return siblings(null, false, true);\n }\n\n /**\n * Get each of the previous element siblings of each element in this list, that match the query.\n * @param query CSS query to match siblings against\n * @return all previous element siblings.\n */\n public Elements prevAll(String query) {\n return siblings(query, false, true);\n }\n\n private Elements siblings(@Nullable String query, boolean next, boolean all) {\n Elements els = new Elements();\n Evaluator eval = query != null? QueryParser.parse(query) : null;\n for (Element e : this) {\n do {\n Element sib = next ? e.nextElementSibling() : e.previousElementSibling();\n if (sib == null) break;\n if (eval == null)\n els.add(sib);\n else if (sib.is(eval))\n els.add(sib);\n e = sib;\n } while (all);\n }\n return els;\n }\n\n /**\n * Get all of the parents and ancestor elements of the matched elements.\n * @return all of the parents and ancestor elements of the matched elements\n */\n public Elements parents() {\n HashSet<Element> combo = new LinkedHashSet<>();\n for (Element e: this) {\n combo.addAll(e.parents());\n }\n return new Elements(combo);\n }\n\n // list-like methods\n /**\n Get the first matched element.\n @return The first matched element, or <code>null</code> if contents is empty.\n */\n public @Nullable Element first() {\n return isEmpty() ? null : get(0);\n }\n\n /**\n Get the last matched element.\n @return The last matched element, or <code>null</code> if contents is empty.\n */\n public @Nullable Element last() {\n return isEmpty() ? null : get(size() - 1);\n }\n\n /**\n * Perform a depth-first traversal on each of the selected elements.\n * @param nodeVisitor the visitor callbacks to perform on each node\n * @return this, for chaining\n */\n public Elements traverse(NodeVisitor nodeVisitor) {\n NodeTraversor.traverse(nodeVisitor, this);\n return this;\n }\n\n /**\n * Perform a depth-first filtering on each of the selected elements.\n * @param nodeFilter the filter callbacks to perform on each node\n * @return this, for chaining\n */\n public Elements filter(NodeFilter nodeFilter) {\n NodeTraversor.filter(nodeFilter, this);\n return this;\n }\n\n /**\n * Get the {@link FormElement} forms from the selected elements, if any.\n * @return a list of {@link FormElement}s pulled from the matched elements. The list will be empty if the elements contain\n * no forms.\n */\n public List<FormElement> forms() {\n ArrayList<FormElement> forms = new ArrayList<>();\n for (Element el: this)\n if (el instanceof FormElement)\n forms.add((FormElement) el);\n return forms;\n }\n\n /**\n * Get {@link Comment} nodes that are direct child nodes of the selected elements.\n * @return Comment nodes, or an empty list if none.\n */\n public List<Comment> comments() {\n return childNodesOfType(Comment.class);\n }\n\n /**\n * Get {@link TextNode} nodes that are direct child nodes of the selected elements.\n * @return TextNode nodes, or an empty list if none.\n */\n public List<TextNode> textNodes() {\n return childNodesOfType(TextNode.class);\n }\n\n /**\n * Get {@link DataNode} nodes that are direct child nodes of the selected elements. DataNode nodes contain the\n * content of tags such as {@code script}, {@code style} etc and are distinct from {@link TextNode}s.\n * @return Comment nodes, or an empty list if none.\n */\n public List<DataNode> dataNodes() {\n return childNodesOfType(DataNode.class);\n }\n\n private <T extends Node> List<T> childNodesOfType(Class<T> tClass) {\n ArrayList<T> nodes = new ArrayList<>();\n for (Element el: this) {\n for (int i = 0; i < el.childNodeSize(); i++) {\n Node node = el.childNode(i);\n if (tClass.isInstance(node))\n nodes.add(tClass.cast(node));\n }\n }\n return nodes;\n }\n\n}", "public static final ParseSettings preserveCase;" ]
import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.integration.ParseTest; import org.jsoup.internal.StringUtil; import org.jsoup.nodes.*; import org.jsoup.safety.Safelist; import org.jsoup.select.Elements; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.util.List; import static org.jsoup.parser.ParseSettings.preserveCase; import static org.junit.jupiter.api.Assertions.*;
@Test public void handlesJavadocFont() { String h = "<TD BGCOLOR=\"#EEEEFF\" CLASS=\"NavBarCell1\"> <A HREF=\"deprecated-list.html\"><FONT CLASS=\"NavBarFont1\"><B>Deprecated</B></FONT></A>&nbsp;</TD>"; Document doc = Jsoup.parse(h); Element a = doc.select("a").first(); assertEquals("Deprecated", a.text()); assertEquals("font", a.child(0).tagName()); assertEquals("b", a.child(0).child(0).tagName()); } @Test public void handlesBaseWithoutHref() { String h = "<head><base target='_blank'></head><body><a href=/foo>Test</a></body>"; Document doc = Jsoup.parse(h, "http://example.com/"); Element a = doc.select("a").first(); assertEquals("/foo", a.attr("href")); assertEquals("http://example.com/foo", a.attr("abs:href")); } @Test public void normalisesDocument() { String h = "<!doctype html>One<html>Two<head>Three<link></head>Four<body>Five </body>Six </html>Seven "; Document doc = Jsoup.parse(h); assertEquals("<!doctype html><html><head></head><body>OneTwoThree<link>FourFive Six Seven </body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void normalisesEmptyDocument() { Document doc = Jsoup.parse(""); assertEquals("<html><head></head><body></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void normalisesHeadlessBody() { Document doc = Jsoup.parse("<html><body><span class=\"foo\">bar</span>"); assertEquals("<html><head></head><body><span class=\"foo\">bar</span></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void normalisedBodyAfterContent() { Document doc = Jsoup.parse("<font face=Arial><body class=name><div>One</div></body></font>"); assertEquals("<html><head></head><body class=\"name\"><font face=\"Arial\"><div>One</div></font></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void findsCharsetInMalformedMeta() { String h = "<meta http-equiv=Content-Type content=text/html; charset=gb2312>"; // example cited for reason of html5's <meta charset> element Document doc = Jsoup.parse(h); assertEquals("gb2312", doc.select("meta").attr("charset")); } @Test public void testHgroup() { // jsoup used to not allow hgroup in h{n}, but that's not in spec, and browsers are OK Document doc = Jsoup.parse("<h1>Hello <h2>There <hgroup><h1>Another<h2>headline</hgroup> <hgroup><h1>More</h1><p>stuff</p></hgroup>"); assertEquals("<h1>Hello </h1><h2>There <hgroup><h1>Another</h1><h2>headline</h2></hgroup> <hgroup><h1>More</h1><p>stuff</p></hgroup></h2>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testRelaxedTags() { Document doc = Jsoup.parse("<abc_def id=1>Hello</abc_def> <abc-def>There</abc-def>"); assertEquals("<abc_def id=\"1\">Hello</abc_def> <abc-def>There</abc-def>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testHeaderContents() { // h* tags (h1 .. h9) in browsers can handle any internal content other than other h*. which is not per any // spec, which defines them as containing phrasing content only. so, reality over theory. Document doc = Jsoup.parse("<h1>Hello <div>There</div> now</h1> <h2>More <h3>Content</h3></h2>"); assertEquals("<h1>Hello <div>There</div> now</h1> <h2>More </h2><h3>Content</h3>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testSpanContents() { // like h1 tags, the spec says SPAN is phrasing only, but browsers and publisher treat span as a block tag Document doc = Jsoup.parse("<span>Hello <div>there</div> <span>now</span></span>"); assertEquals("<span>Hello <div>there</div> <span>now</span></span>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testNoImagesInNoScriptInHead() { // jsoup used to allow, but against spec if parsing with noscript Document doc = Jsoup.parse("<html><head><noscript><img src='foo'></noscript></head><body><p>Hello</p></body></html>"); assertEquals("<html><head><noscript>&lt;img src=\"foo\"&gt;</noscript></head><body><p>Hello</p></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void testUnclosedNoscriptInHead() { // Was getting "EOF" in html output, because the #anythingElse handler was calling an undefined toString, so used object.toString. String[] strings = {"<noscript>", "<noscript>One"}; for (String html : strings) { Document doc = Jsoup.parse(html); assertEquals(html + "</noscript>", TextUtil.stripNewlines(doc.head().html())); } } @Test public void testAFlowContents() { // html5 has <a> as either phrasing or block Document doc = Jsoup.parse("<a>Hello <div>there</div> <span>now</span></a>"); assertEquals("<a>Hello <div>there</div> <span>now</span></a>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testFontFlowContents() { // html5 has no definition of <font>; often used as flow Document doc = Jsoup.parse("<font>Hello <div>there</div> <span>now</span></font>"); assertEquals("<font>Hello <div>there</div> <span>now</span></font>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesMisnestedTagsBI() { // whatwg: <b><i></b></i> String h = "<p>1<b>2<i>3</b>4</i>5</p>"; Document doc = Jsoup.parse(h); assertEquals("<p>1<b>2<i>3</i></b><i>4</i>5</p>", doc.body().html()); // adoption agency on </b>, reconstruction of formatters on 4. } @Test public void handlesMisnestedTagsBP() { // whatwg: <b><p></b></p> String h = "<b>1<p>2</b>3</p>"; Document doc = Jsoup.parse(h); assertEquals("<b>1</b>\n<p><b>2</b>3</p>", doc.body().html()); } @Test public void handlesMisnestedAInDivs() { String h = "<a href='#1'><div><div><a href='#2'>child</a></div</div></a>"; String w = "<a href=\"#1\"></a> <div> <a href=\"#1\"></a> <div> <a href=\"#1\"></a><a href=\"#2\">child</a> </div> </div>"; Document doc = Jsoup.parse(h); assertEquals(
StringUtil.normaliseWhitespace(w),
3
gamblore/AndroidPunk
sample/AndroidPunkTest/src/com/gamblore/androidpunk/entities/Ogmo.java
[ "public class Entity extends Tweener {\n\n\tprivate static final String TAG = \"Entity\";\n\t\n /**\n * If the Entity should render.\n */\n public boolean visible = true;\n\n /**\n * If the Entity should respond to collision checks.\n */\n public boolean collidable = true;\n\n /**\n * X position of the Entity in the World.\n */\n //public int x = 0;\n\n /**\n * Y position of the Entity in the World.\n */\n //public int y = 0;\n\n /**\n * Width of the Entity's hitbox.\n */\n public int width;\n\n /**\n * Height of the Entity's hitbox.\n */\n public int height;\n\n /**\n * X origin of the Entity's hitbox.\n */\n public int originX;\n\n /**\n * Y origin of the Entity's hitbox.\n */\n public int originY;\n\n /**\n * The BitmapData target to draw the Entity to. Leave as null to render to the current screen buffer (default).\n */\n public Bitmap renderTarget;\n \n // Entity information.\n private World mWorld;\n protected boolean mAdded;\n protected String mType = \"\";\n private String mName;\n private int mLayer = 0;\n protected Entity mUpdatePrev;\n protected Entity mUpdateNext;\n protected Entity mRenderPrev;\n protected Entity mRenderNext;\n protected Entity mTypePrev;\n protected Entity mTypeNext;\n \n // Collision information.\n private final Mask HITBOX = new Mask();\n private Mask mMask;\n private float mX;\n private float mY;\n private float mMoveX;\n private float mMoveY;\n \n // Rendering information.\n private Graphic mGraphic;\n private Point mPoint = FP.point;\n private Point mCamera = FP.point2;\n \n \n public Entity() {\n this(0,0, null, null);\n }\n public Entity(int x, int y) {\n this(x, y, null, null);\n }\n public Entity(int x, int y, Graphic graphic) {\n this(x, y, graphic, null);\n }\n \n public Entity(int x, int y, Graphic graphic, Mask mask) {\n this.x = x;\n this.y = y;\n if (graphic != null) { \n mGraphic = graphic;\n mGraphic.mAssign.assigned(this);\n }\n if (mask != null) {\n mMask = mask;\n }\n HITBOX.assignTo(this);\n \n }\n \n public String toString() {\n \treturn String.format(\"%s: %s xy<%d, %d> origin<%d, %d> wh<%d, %d>\", getClass().getName(), mType, x, y, originX, originY, width, height);\n }\n \n /**\n\t * Override this, called when the Entity is added to a World.\n\t */\n\tpublic void added() {\n\n\t}\n\t\n\t/**\n\t * Override this, called when the Entity is removed from a World.\n\t */\n\tpublic void removed() {\n\n\t}\n\t\n\t/**\n\t * Updates the Entity.\n\t */\n\tpublic void update() { \n\n\t}\n\t\n\t/**\n\t * Renders the Entity. If you override this for special behaviour,\n\t * remember to call super.render() to render the Entity's graphic.\n\t */\n\tpublic void render() { \n\t\tif (mGraphic != null && mGraphic.visible) {\n\t\t\tif (mGraphic.relative) {\n\t\t\t\tmPoint.x = x;\n\t\t\t\tmPoint.y = y;\n\t\t\t}\n\t\t\telse \n\t\t\t\tmPoint.x = mPoint.y = 0;\n\t\t\tmCamera.x = FP.camera.x;\n\t\t\tmCamera.y = FP.camera.y;\n\t\t\t//TODO replace this with GL10 gl\n\t\t\tmGraphic.render(OpenGLSystem.getGL(), mPoint, mCamera);\n\t\t\t//Log.d(TAG, \"Entity rendered to \" + FP.buffer.toString());\n\t\t}\n\t}\n\t\n\t/**\n\t * Checks for a collision against an Entity type.\n\t * @param\ttype\t\tThe Entity type to check for.\n\t * @param\tx\t\t\tVirtual x position to place this Entity.\n\t * @param\ty\t\t\tVirtual y position to place this Entity.\n\t * @return\tThe first Entity collided with, or null if none were collided.\n\t */\n\tpublic Entity collide(String type, int x, int y) {\n\t\tif (mWorld == null) \n\t\t\treturn null;\n\n\t\tEntity e = mWorld.mTypeFirst.get(type);\n\t\tif (!collidable || e == null) \n\t\t\treturn null;\n\n\t\tmX = this.x; mY = this.y;\n\t\tthis.x = x; this.y = y;\n\n\t\tif (mMask == null) {\n\t\t\twhile (e != null) {\n\t\t\t\tif (x - originX + width > e.x - e.originX\n\t\t\t\t&& y - originY + height > e.y - e.originY\n\t\t\t\t&& x - originX < e.x - e.originX + e.width\n\t\t\t\t&& y - originY < e.y - e.originY + e.height\n\t\t\t\t&& e.collidable && e != this)\n\t\t\t\t{\n\t\t\t\t\tif (e.mMask == null || e.mMask.collide(HITBOX))\n\t\t\t\t\t{\n\t\t\t\t\t\tthis.x = (int)mX; this.y = (int)mY;\n\t\t\t\t\t\treturn e;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\te = e.mTypeNext;\n\t\t\t}\n\t\t\tthis.x = (int)mX; this.y = (int)mY;\n\t\t\treturn null;\n\t\t}\n\n\t\twhile (e != null) {\n\t\t\tif (x - originX + width > e.x - e.originX\n\t\t\t&& y - originY + height > e.y - e.originY\n\t\t\t&& x - originX < e.x - e.originX + e.width\n\t\t\t&& y - originY < e.y - e.originY + e.height\n\t\t\t&& e.collidable && e != this) {\n\t\t\t\tif (mMask.collide(e.mMask != null ? e.mMask : e.HITBOX)) {\n\t\t\t\t\tthis.x = (int)mX; this.y = (int)mY;\n\t\t\t\t\treturn e;\n\t\t\t\t}\n\t\t\t}\n\t\t\te = e.mTypeNext;\n\t\t}\n\t\tthis.x = (int)mX; this.y = (int)mY;\n\t\treturn null;\n\t}\n\t\n\t/**\n\t * Checks for collision against multiple Entity types.\n\t * @param\ttypes\t\tAn Array or Vector of Entity types to check for.\n\t * @param\tx\t\t\tVirtual x position to place this Entity.\n\t * @param\ty\t\t\tVirtual y position to place this Entity.\n\t * @return\tThe first Entity collided with, or null if none were collided.\n\t */\n\tpublic Entity collideTypes(Vector<String> types, int x, int y) {\n\t\tif (mWorld == null)\n\t\t\treturn null;\n\t\tEntity e;\n\t\tfor (int i = 0; i < types.size(); i++) {\n\t\t\tif ((e = collide(types.get(i), x, y)) != null) \n\t\t\t\treturn e;\n\t\t}\n\t\treturn null;\n\t}\n\t\n\t/**\n\t * Checks if this Entity collides with a specific Entity.\n\t * @param\te\t\tThe Entity to collide against.\n\t * @param\tx\t\tVirtual x position to place this Entity.\n\t * @param\ty\t\tVirtual y position to place this Entity.\n\t * @return\tThe Entity if they overlap, or null if they don't.\n\t */\n\tpublic Entity collideWith(Entity e, int x, int y) {\n\t\tmX = this.x; mY = this.y;\n\t\tthis.x = x; this.y = y;\n\n\t\tif (x - originX + width > e.x - e.originX\n\t\t&& y - originY + height > e.y - e.originY\n\t\t&& x - originX < e.x - e.originX + e.width\n\t\t&& y - originY < e.y - e.originY + e.height\n\t\t&& collidable && e.collidable)\n\t\t{\n\t\t\tif (mMask == null) {\n\t\t\t\tif (e.mMask == null || e.mMask.collide(HITBOX)) {\n\t\t\t\t\tthis.x = (int)mX; this.y = (int)mY;\n\t\t\t\t\treturn e;\n\t\t\t\t}\n\t\t\t\tthis.x = (int)mX; this.y = (int)mY;\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (mMask.collide(e.mMask != null ? e.mMask : e.HITBOX))\n\t\t\t{\n\t\t\t\tthis.x = (int)mX; this.y = (int)mY;\n\t\t\t\treturn e;\n\t\t\t}\n\t\t}\n\t\tthis.x = (int)mX; this.y = (int)mY;\n\t\treturn null;\n\t}\n\t\n\t/**\n\t * Checks if this Entity overlaps the specified rectangle.\n\t * @param\tx\t\t\tVirtual x position to place this Entity.\n\t * @param\ty\t\t\tVirtual y position to place this Entity.\n\t * @param\trX\t\t\tX position of the rectangle.\n\t * @param\trY\t\t\tY position of the rectangle.\n\t * @param\trWidth\t\tWidth of the rectangle.\n\t * @param\trHeight\t\tHeight of the rectangle.\n\t * @return\tIf they overlap.\n\t */\n\tpublic boolean collideRect(int x, int y, int rX, int rY, int rWidth, int rHeight) {\n\t\tif (x - originX + width >= rX && y - originY + height >= rY\n\t\t&& x - originX <= rX + rWidth && y - originY <= rY + rHeight) {\n\t\t\tif (mMask == null) \n\t\t\t\treturn true;\n\t\t\tmX = this.x; mY = this.y;\n\t\t\tthis.x = x; this.y = y;\n\t\t\tFP.entity.x = rX;\n\t\t\tFP.entity.y = rY;\n\t\t\tFP.entity.width = rWidth;\n\t\t\tFP.entity.height = rHeight;\n\t\t\tif (mMask.collide(FP.entity.HITBOX)) {\n\t\t\t\tthis.x = (int)mX; this.y = (int)mY;\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tthis.x = (int)mX; this.y = (int)mY;\n\t\t\treturn false;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\t/**\n\t * Checks if this Entity overlaps the specified position.\n\t * @param\tx\t\t\tVirtual x position to place this Entity.\n\t * @param\ty\t\t\tVirtual y position to place this Entity.\n\t * @param\tpX\t\t\tX position.\n\t * @param\tpY\t\t\tY position.\n\t * @return\tIf the Entity intersects with the position.\n\t */\n\tpublic boolean collidePoint(int x, int y, int pX, int pY) {\n\t\tif (pX >= x - originX && pY >= y - originY\n\t\t&& pX < x - originX + width && pY < y - originY + height) {\n\t\t\tif (mMask == null) \n\t\t\t\treturn true;\n\t\t\tmX = this.x; mY = this.y;\n\t\t\tthis.x = x; this.y = y;\n\t\t\tFP.entity.x = pX;\n\t\t\tFP.entity.y = pY;\n\t\t\tFP.entity.width = 1;\n\t\t\tFP.entity.height = 1;\n\t\t\tif (mMask.collide(FP.entity.HITBOX)) {\n\t\t\t\tthis.x = (int)mX; this.y = (int)mY;\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tthis.x = (int)mX; this.y = (int)mY;\n\t\t\treturn false;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\t/**\n\t * Populates an array with all collided Entities of a type.\n\t * @param\ttype\t\tThe Entity type to check for.\n\t * @param\tx\t\t\tVirtual x position to place this Entity.\n\t * @param\ty\t\t\tVirtual y position to place this Entity.\n\t * @param\tarray\t\tThe Array or Vector object to populate.\n\t * @return\tThe array, populated with all collided Entities.\n\t */\n\tpublic void collideInto(String type, int x, int y, Vector<Entity> array) {\n\t\tif (mWorld == null) \n\t\t\treturn;\n\n\t\tEntity e = mWorld.mTypeFirst.get(type);\n\t\tif (!collidable || e == null) \n\t\t\treturn;\n\n\t\tmX = this.x; mY = this.y;\n\t\tthis.x = x; this.y = y;\n\n\t\tif (mMask == null){\n\t\t\twhile (e != null){\n\t\t\t\tif (x - originX + width > e.x - e.originX\n\t\t\t\t&& y - originY + height > e.y - e.originY\n\t\t\t\t&& x - originX < e.x - e.originX + e.width\n\t\t\t\t&& y - originY < e.y - e.originY + e.height\n\t\t\t\t&& e.collidable && e != this)\n\t\t\t\t{\n\t\t\t\t\tif (e.mMask == null || e.mMask.collide(HITBOX))\n\t\t\t\t\t\tarray.add(e);\n\t\t\t\t}\n\t\t\t\te = e.mTypeNext;\n\t\t\t}\n\t\t\tthis.x = (int)mX; this.y = (int)mY;\n\t\t\treturn;\n\t\t}\n\n\t\twhile (e != null) {\n\t\t\tif (x - originX + width > e.x - e.originX\n\t\t\t&& y - originY + height > e.y - e.originY\n\t\t\t&& x - originX < e.x - e.originX + e.width\n\t\t\t&& y - originY < e.y - e.originY + e.height\n\t\t\t&& e.collidable && e != this)\n\t\t\t{\n\t\t\t\tif (mMask.collide(e.mMask != null ? e.mMask : e.HITBOX)) \n\t\t\t\t\tarray.add(e);\n\t\t\t}\n\t\t\te = e.mTypeNext;\n\t\t}\n\t\tthis.x = (int)mX; this.y = (int)mY;\n\t\treturn;\n\t}\n\t\n\t/**\n\t * Populates an array with all collided Entities of multiple types.\n\t * @param\ttypes\t\tAn array of Entity types to check for.\n\t * @param\tx\t\t\tVirtual x position to place this Entity.\n\t * @param\ty\t\t\tVirtual y position to place this Entity.\n\t * @param\tarray\t\tThe Array or Vector object to populate.\n\t * @return\tThe array, populated with all collided Entities.\n\t */\n\tpublic void collideTypesInto(Vector<String> types, int x, int y, Vector<Entity> array) {\n\t\tif (mWorld == null) \n\t\t\treturn;\n\t\tfor (int i = 0; i < types.size(); i++) {\n\t\t\tcollideInto(types.get(i), x, y, array);\n\t\t}\n\t}\n\t\n\t/**\n\t * If the Entity collides with the camera rectangle.\n\t */\n\tpublic boolean onCamera() {\n\t\treturn collideRect(x, y, FP.camera.x, FP.camera.y, FP.width, FP.height);\n\t}\n\t\n\t/**\n\t * The World object this Entity has been added to.\n\t */\n\tpublic World getWorld() {\n\t\treturn mWorld;\n\t}\n\t\n\t/**\n\t * The World object this Entity has been added to.\n\t */\n\tpublic void setWorld(World w) {\n\t\tmWorld = w;\n\t}\n\t\n\t/**\n\t * Half the Entity's width.\n\t */\n\tpublic float getHalfWidth() { return width / 2; }\n\n\t/**\n\t * Half the Entity's height.\n\t */\n\tpublic float getHalfHeight() { return height / 2; }\n\t\n\t/**\n\t * The center x position of the Entity's hitbox.\n\t */\n\tpublic float getCenterX() { return x - originX + width / 2; }\n\n\t/**\n\t * The center y position of the Entity's hitbox.\n\t */\n\tpublic float getCenterY() { return y - originY + height / 2; }\n\t\n\t/**\n\t * The leftmost position of the Entity's hitbox.\n\t */\n\tpublic int getLeft() { return x - originX; }\n\n\t/**\n\t * The rightmost position of the Entity's hitbox.\n\t */\n\tpublic int getRight() { return x - originX + width; }\n\t\n\t/**\n\t * The topmost position of the Entity's hitbox.\n\t */\n\tpublic int getTop() { return y - originY; }\n\n\t/**\n\t * The bottommost position of the Entity's hitbox.\n\t */\n\tpublic int getBottom() { return y - originY + height; }\n\t\n\t/**\n\t * The rendering layer of this Entity. Higher layers are rendered first.\n\t */\n\tpublic int getLayer() { return mLayer; }\n\tpublic void setLayer(int value) {\n\t\tif (mLayer == value) \n\t\t\treturn;\n\t\tif (!mAdded) {\n\t\t\tmLayer = value;\n\t\t\treturn;\n\t\t}\n\t\tmWorld.removeRender(this);\n\t\tmLayer = value;\n\t\tmWorld.addRender(this);\n\t}\n\t\n\t/**\n\t * The collision type, used for collision checking.\n\t */\n\tpublic String getType() { return mType; }\n\tpublic void setType(String value) {\n\t\tif (mType.equals(value))\n\t\t\treturn;\n\t\tif (!mAdded)\n\t\t{\n\t\t\tmType = value;\n\t\t\treturn;\n\t\t}\n\t\tif (!\"\".equals(mType)) \n\t\t\tmWorld.removeType(this);\n\t\tmType = value;\n\t\tif (!\"\".equals(value)) \n\t\t\tmWorld.addType(this);\n\t}\n\t\n\t/**\n\t * An optional Mask component, used for specialized collision. If this is\n\t * not assigned, collision checks will use the Entity's hitbox by default.\n\t */\n\tpublic Mask getMask() { return mMask; }\n\tpublic void setMask(Mask value) {\n\t\tif (mMask == value) \n\t\t\treturn;\n\t\tif (mMask != null) \n\t\t\tmMask.assignTo(null);\n\t\tmMask = value;\n\t\tif (value != null) \n\t\t\tmMask.assignTo(this);\n\t}\n\t\n\tpublic Graphic getGraphic() { return mGraphic; }\n public void setGraphic(Graphic g) {\n \tif (g != null) { \n mGraphic = g;\n mGraphic.mAssign.assigned(this);\n mGraphic.active = true;\n }\n }\n \n public Graphic addGraphic(Graphic g) {\n \tGraphic graphic = getGraphic();\n \tif (graphic instanceof GraphicList) {\n \t\t((GraphicList)graphic).add(g);\t\n \t} else {\n \t\tGraphicList list = new GraphicList();\n \t\tif (graphic != null) {\n \t\t\tlist.add(graphic);\n \t\t}\n \t\tsetGraphic(list);\n \t}\n \treturn g;\n }\n\n /**\n\t * Sets the Entity's hitbox properties.\n\t * @param\twidth\t\tWidth of the hitbox.\n\t * @param\theight\t\tHeight of the hitbox.\n\t */\n public void setHitbox(int width, int height) {\n \tsetHitbox(width, height, 0, 0);\n }\n \n\t/**\n\t * Sets the Entity's hitbox properties.\n\t * @param\twidth\t\tWidth of the hitbox.\n\t * @param\theight\t\tHeight of the hitbox.\n\t * @param\toriginX\t\tX origin of the hitbox.\n\t * @param\toriginY\t\tY origin of the hitbox.\n\t */\n\tpublic void setHitbox(int width, int height, int originX, int originY) {\n\t\tthis.width = width;\n\t\tthis.height = height;\n\t\tthis.originX = originX;\n\t\tthis.originY = originY;\n\t}\n\t\n\t/**\n\t * Sets the Entity's hitbox to match that of the provided object.\n\t * @param\to\t\tThe object defining the hitbox (eg. an Image or Rectangle).\n\t */\n\tpublic void setHitboxTo(Rect r) {\n\t\tsetHitbox(r.width(), r.height(), -r.left, -r.top);\n\t}\n\t\n\t/**\n\t * Sets the origin of the Entity.\n\t * @param\tx\t\tX origin.\n\t * @param\ty\t\tY origin.\n\t */\n\tpublic void setOrigin(int x , int y) {\n\t\toriginX = x;\n\t\toriginY = y;\n\t}\n\t\n\t/**\n\t * Center's the Entity's origin (half width & height).\n\t */\n\tpublic void centerOrigin() {\n\t\toriginX = width / 2;\n\t\toriginY = height / 2;\n\t}\n\t\n\tpublic double distanceFrom(Entity e) {\n\t\treturn distanceFrom(e, false);\n\t}\n\t/**\n\t * Calculates the distance from another Entity.\n\t * @param\te\t\t\t\tThe other Entity.\n\t * @param\tuseHitboxes\t\tIf hitboxes should be used to determine the distance. If not, the Entities' x/y positions are used.\n\t * @return\tThe distance.\n\t */\n\tpublic double distanceFrom(Entity e, boolean useHitboxes) {\n\t\tif (!useHitboxes) \n\t\t\treturn Math.sqrt((x - e.x) * (x - e.x) + (y - e.y) * (y - e.y));\n\t\treturn FP.distanceRects(x - originX, y - originY, width, height, e.x - e.originX, e.y - e.originY, e.width, e.height);\n\t}\n\t\n\tpublic double distanceToPoint(int px, int py) {\n\t\treturn distanceToPoint(px, py, false);\n\t}\n\t/**\n\t * Calculates the distance from this Entity to the point.\n\t * @param\tpx\t\t\t\tX position.\n\t * @param\tpy\t\t\t\tY position.\n\t * @param\tuseHitboxes\t\tIf hitboxes should be used to determine the distance. If not, the Entities' x/y positions are used.\n\t * @return\tThe distance.\n\t */\n\tpublic double distanceToPoint(int px, int py, boolean useHitbox) {\n\t\tif (!useHitbox) \n\t\t\treturn Math.sqrt((x - px) * (x - px) + (y - py) * (y - py));\n\t\treturn FP.distanceRectPoint(px, py, x - originX, y - originY, width, height);\n\t}\n\t\n\t/**\n\t * Calculates the distance from this Entity to the rectangle.\n\t * @param\trx\t\t\tX position of the rectangle.\n\t * @param\try\t\t\tY position of the rectangle.\n\t * @param\trwidth\t\tWidth of the rectangle.\n\t * @param\trheight\t\tHeight of the rectangle.\n\t * @return\tThe distance.\n\t */\n\tpublic double distanceToRect(int rx, int ry, int rwidth, int rheight) {\n\t\treturn FP.distanceRects(rx, ry, rwidth, rheight, x - originX, y - originY, width, height);\n\t}\n\t\n\tpublic void moveBy(int x, int y) {\n\t\tmoveBy(x,y, null, false);\n\t}\n\t/**\n\t * Moves the Entity by the amount, retaining integer values for its x and y.\n\t * @param\tx\t\t\tHorizontal offset.\n\t * @param\ty\t\t\tVertical offset.\n\t * @param\tsolidType\tAn optional collision type to stop flush against upon collision.\n\t * @param\tsweep\t\tIf sweeping should be used (prevents fast-moving objects from going through solidType).\n\t */\n\tpublic void moveBy(int x, int y, String solidType, boolean sweep) {\n\t\tmMoveX += x;\n\t\tmMoveY += y;\n\t\tx = Math.round(mMoveX);\n\t\ty = Math.round(mMoveY);\n\t\tmMoveX -= x;\n\t\tmMoveY -= y;\n\t\tif (solidType != null) {\n\t\t\tint sign;\n\t\t\tEntity e;\n\t\t\tif (x != 0) {\n\t\t\t\tif (collidable && (sweep || collide(solidType, this.x + x, this.y) != null)) {\n\t\t\t\t\tsign = x > 0 ? 1 : -1;\n\t\t\t\t\twhile (x != 0) {\n\t\t\t\t\t\tif ((e = collide(solidType, this.x + sign, this.y)) != null) {\n\t\t\t\t\t\t\tmoveCollideX(e);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tthis.x += sign;\n\t\t\t\t\t\t\tx -= sign;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse \n\t\t\t\t\tthis.x += x;\n\t\t\t}\n\t\t\tif (y != 0) {\n\t\t\t\tif (collidable && (sweep || collide(solidType, this.x, this.y + y) != null)) {\n\t\t\t\t\tsign = y > 0 ? 1 : -1;\n\t\t\t\t\twhile (y != 0) {\n\t\t\t\t\t\tif ((e = collide(solidType, this.x, this.y + sign)) != null) {\n\t\t\t\t\t\t\tmoveCollideY(e);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tthis.y += sign;\n\t\t\t\t\t\t\ty -= sign;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse \n\t\t\t\t\tthis.y += y;\n\t\t\t}\n\t\t} else {\n\t\t\tthis.x += x;\n\t\t\tthis.y += y;\n\t\t}\n\t}\n\t\n\tpublic void moveTo(int x, int y) {\n\t\tmoveTo(x,y,null,false);\n\t}\n\t/**\n\t * Moves the Entity to the position, retaining integer values for its x and y.\n\t * @param\tx\t\t\tX position.\n\t * @param\ty\t\t\tY position.\n\t * @param\tsolidType\tAn optional collision type to stop flush against upon collision.\n\t * @param\tsweep\t\tIf sweeping should be used (prevents fast-moving objects from going through solidType).\n\t */\n\tpublic void moveTo(int x, int y, String solidType, boolean sweep) {\n\t\tmoveBy(x - this.x, y - this.y, solidType, sweep);\n\t}\n\t\n\tpublic void moveTowards(int x, int y, int amount) {\n\t\tmoveTowards(x, y, amount, null, false);\n\t}\n\t/**\n\t * Moves towards the target position, retaining integer values for its x and y.\n\t * @param\tx\t\t\tX target.\n\t * @param\ty\t\t\tY target.\n\t * @param\tamount\t\tAmount to move.\n\t * @param\tsolidType\tAn optional collision type to stop flush against upon collision.\n\t * @param\tsweep\t\tIf sweeping should be used (prevents fast-moving objects from going through solidType).\n\t */\n\tpublic void moveTowards(int x, int y, int amount, String solidType, boolean sweep) {\n\t\tmPoint.x = x - this.x;\n\t\tmPoint.y = y - this.y;\n\t\tdouble len = PointF.length(mPoint.x, mPoint.y);\n\t\tmPoint.x /= len;\n\t\tmPoint.y /= len;\n\t\tmoveBy(mPoint.x, mPoint.y, solidType, sweep);\n\t}\n\t\n\t/**\n\t * When you collide with an Entity on the x-axis with moveTo() or moveBy().\n\t * @param\te\t\tThe Entity you collided with.\n\t */\n\tpublic void moveCollideX(Entity e) {\n\n\t}\n\t\n\t/**\n\t * When you collide with an Entity on the y-axis with moveTo() or moveBy().\n\t * @param\te\t\tThe Entity you collided with.\n\t */\n\tpublic void moveCollideY(Entity e) {\n\n\t}\n\t\n\tpublic void clampHorizontal(int left, int right) {\n\t\tclampHorizontal(left, right, 0);\n\t}\n\t/**\n\t * Clamps the Entity's hitbox on the x-axis.\n\t * @param\tleft\t\tLeft bounds.\n\t * @param\tright\t\tRight bounds.\n\t * @param\tpadding\t\tOptional padding on the clamp.\n\t */\n\tpublic void clampHorizontal(int left, int right, int padding) {\n\t\tif (x - originX < left + padding)\n\t\t\tx = left + originX + padding;\n\t\tif (x - originX + width > right - padding)\n\t\t\tx = right - width + originX - padding;\n\t}\n\t\n\tpublic void clampVertical(int top, int bottom) {\n\t\tclampVertical(top, bottom, 0);\n\t}\n\t/**\n\t * Clamps the Entity's hitbox on the y axis.\n\t * @param\ttop\t\t\tMin bounds.\n\t * @param\tbottom\t\tMax bounds.\n\t * @param\tpadding\t\tOptional padding on the clamp.\n\t */\n\tpublic void clampVertical(int top, int bottom, int padding) {\n\t\tif (y - originY < top + padding)\n\t\t\ty = top + originY + padding;\n\t\tif (y - originY + height > bottom - padding)\n\t\t\ty = bottom - height + originY - padding;\n\t}\n}", "public class FP {\n\n\tprivate static final String TAG = \"FP\";\n\t\n /**\n * The FlashPunk major version.\n */\n public static final String VERSION = \"1.6\";\n \n /**\n * The default Typeface to use.\n */\n public static Typeface typeface = Typeface.DEFAULT;\n \n /**\n * Width of the game.\n */\n public static int width;\n \n /**\n * Height of the game.\n */\n public static int height;\n \n /**\n * Width of the display that is being rendered to.\n */\n public static int displayWidth;\n \n /**\n * Height of the display that is being rendered to.\n */\n public static int displayHeight;\n \n /**\n * Half width of the game.\n */\n public static float halfWidth;\n \n /**\n * Half height of the game.\n */\n public static float halfHeight;\n \n /**\n * Global scale of the game graphics.\n */\n public static float scale = 1.0f;\n \n /**\n * If the game is running at a fixed framerate.\n */\n public static boolean fixed;\n \n /**\n * If times should be given in frames (as opposed to seconds).\n * Default is true in fixed timestep mode and false in variable timestep mode.\n */\n public static boolean timeInFrames;\n \n /**\n * The framerate of the stage.\n */\n public static float frameRate;\n \n /**\n * The framerate assigned to the stage.\n */\n public static float assignedFrameRate = 60;\n \n /**\n * Time elapsed since the last frame (in seconds).\n */\n public static float elapsed;\n \n /**\n * Timescale applied to FP.elapsed.\n */\n public static float rate = 1;\n \n /**\n * The Screen object, use to transform or offset the Screen.\n */\n public static Screen screen;\n \n /**\n * Turn on debug display\n */\n public static boolean debug = false;\n \n /**\n * The current screen buffer, drawn to in the render loop.\n */\n public static Bitmap buffer;\n \n /**\n * The background screen buffer, ready to draw to screen.\n */\n public static Bitmap backBuffer;\n \n /**\n * A rectangle representing the target size of the screen.\n */\n public static Rect bounds;\n \n /**\n * Point used to determine drawing offset in the render loop.\n */\n public static Point camera = new Point();\n \n /**\n * Global Tweener for tweening values across multiple worlds.\n */\n public static Tweener tweener = new Tweener();\n \n /**\n * If the game currently has input focus or not. Note: may not be correct initially.\n */\n public static boolean focused = true;\n \n /**\n * Used in graphics drawing to see if there is a faster way to blit.\n */\n public static boolean supportsVBOs = false;\n \n /**\n * Callback to be used when the back button is pressed.\n */\n public static OnBackCallback onBack = PunkActivity.DEFAULT_ON_BACK;\n \n /**\n * The PunkActivity that is currently running. Used to finalize from the engine.\n */\n public static PunkActivity activity;\n /**\n * Used in graphics drawing to see if there is a the fastest way to blit.\n */\n public static boolean supportsDrawTexture = false;\n \n private static final float HSV[] = new float[3];\n \n // World information.\n protected static World mWorld;\n protected static World mGoto;\n\n // Console information.\n protected static Console mConsole;\n\n // Time information.\n protected static long mTime;\n public static long updateTime;\n public static long renderTime;\n public static long gameTime;\n public static long javaTime;\n\n // Pseudo-random number generation (the seed is set in Engine's constructor).\n private static long mSeed;\n private static long mGetSeed;\n\n // Volume control.\n private static float mVolume = 1.0f;\n private static float mPan = 0.0f;\n\n // Used for rad-to-deg and deg-to-rad conversion.\n public static final float DEG = (float)(-180.0 / Math.PI);\n public static final float RAD = (float)(Math.PI / -180.0);\n\n // Global Flash objects.\n public static Engine engine;\n\n // Global objects used for rendering, collision, etc.\n public static final Point point = new Point();\n public static final Point point2 = new Point();\n public static final Point zero = new Point();\n public static final Rect rect = new Rect();\n public static final Matrix matrix = new Matrix();\n public static final Paint paint = new Paint();\n public static final Canvas canvas = new Canvas();\n public static Entity entity;\n \n public static Resources resources;\n public static Context context;\n\n\tpublic static boolean debugOpenGL = false;\n \n public static final float MATRIX_VALUES[] = new float[9];\n \n // Hash for caching FP.getBitmap()\n private static final HashMap<Integer, Bitmap> CACHED_BITMAPS = new HashMap<Integer, Bitmap>();\n \n /**\n * Resize the screen.\n * @param width New width.\n * @param height New height.\n */\n public static void resize(int width, int height) {\n FP.width = width;\n FP.height = height;\n FP.halfWidth = width/2;\n FP.halfHeight = height/2;\n FP.bounds.right = width;\n FP.bounds.bottom = height;\n FP.screen.resize();\n }\n \n public static float dip(float dip) { \n\t\treturn TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, resources.getDisplayMetrics());\n\t}\n \n public static World getWorld() {\n return mWorld;\n }\n \n /**\n * The currently active World object. When you set this, the World is flagged\n * to switch, but won't actually do so until the end of the current frame.\n */\n public static void setWorld(World world) {\n if (mWorld != null && mWorld.equals(world))\n return;\n mGoto = world;\n }\n \n /**\n * Sets the camera position.\n * @param x X position.\n * @param y Y position.\n */\n public static void setCamera(int x, int y) {\n camera.x = x;\n camera.y = y;\n }\n \n /**\n * Resets the camera position.\n */\n public static void resetCamera() {\n camera.x = camera.y = 0;\n }\n \n /**\n * Global volume factor for all sounds, a value from 0 to 1.\n */\n public static float getVolume() {\n \treturn mVolume;\n }\n \n /**\n * Global volume factor for all sounds, a value from 0 to 1.\n */\n public static void setVolume(float value) {\n if (value < 0) \n value = 0;\n if (mVolume == value) \n return;\n \n Sfx.setMasterVolume(mVolume = value);\n }\n \n /**\n * Global panning factor for all sounds, a value from -1 to 1.\n */\n public static float getPan() {\n return mPan; \n }\n \n /**\n * Global panning factor for all sounds, a value from -1 to 1.\n */\n public static void setPan(float value)\n {\n if (value < -1) \n value = -1;\n if (value > 1) \n value = 1;\n if (mPan == value)\n return;\n \n Sfx.setMasterPan(mPan = value);\n }\n \n /**\n * Randomly chooses and returns one of the provided values.\n * @param objs The Objects you want to randomly choose from. Can be ints, Numbers, Points, etc.\n * @return A randomly chosen one of the provided parameters.\n */\n public static Object choose(Object... objs) {\n Random r = new Random();\n \n return objs[r.nextInt(objs.length)];\n }\n \n /**\n * Finds the sign of the provided value.\n * @param value The Number to evaluate.\n * @return 1 if value > 0, -1 if value < 0, and 0 when value == 0.\n */\n public static int sign(float value)\n {\n return value < 0 ? -1 : (value > 0 ? 1 : 0);\n }\n \n public static int sign(int value)\n {\n return value < 0 ? -1 : (value > 0 ? 1 : 0);\n }\n \n /**\n * Approaches the value towards the target, by the specified amount, without overshooting the target.\n * @param value The starting value.\n * @param target The target that you want value to approach.\n * @param amount How much you want the value to approach target by.\n * @return The new value.\n */\n public static float approach(float value, float target, float amount) {\n return value < target ? (target < value + amount ? target : value + amount) : (target > value - amount ? target : value - amount);\n }\n\n /**\n * Linear interpolation between two values.\n * @param a First value.\n * @param b Second value.\n * @param t Interpolation factor.\n * @return When t=0, returns a. When t=1, returns b. When t=0.5, will return halfway between a and b. Etc.\n */\n public static float lerp(float a, float b, float t) {\n return a + (b - a) * t;\n }\n \n /**\n * Linear interpolation between two colors.\n * @param fromColor First color.\n * @param toColor Second color.\n * @param t Interpolation value. Clamped to the range [0, 1].\n * return RGB component-interpolated color value.\n */\n public static int colorLerp(int fromColor, int toColor, float t) {\n if (t <= 0) { return fromColor; }\n if (t >= 1) { return toColor; }\n int a = Color.alpha(fromColor);\n int r = Color.red(fromColor);\n int g = Color.green(fromColor);\n int b = Color.blue(fromColor);\n \n int dA = Color.alpha(toColor) - a;\n int dR = Color.red(toColor) - r;\n int dG = Color.green(toColor) - g;\n int dB = Color.blue(toColor) -b;\n\n a += dA * t;\n r += dR * t;\n g += dG * t;\n b += dB * t;\n return Color.argb(a, r, g, b);\n }\n \n /**\n * Steps the object towards a point.\n * @param object Object to move (must have an x and y property).\n * @param x X position to step towards.\n * @param y Y position to step towards.\n * @param distance The distance to step (will not overshoot target).\n */\n public static void stepTowards(Positionable object, int x, int y, float distance) {\n point.x = x - object.x;\n point.y = y - object.y;\n double len = PointF.length(point.x, point.y);\n if (len <= distance)\n {\n object.x = x;\n object.y = y;\n return;\n }\n float deltax = (float)(point.x / len) * distance;\n float deltay = (float)(point.y / len) * distance;\n object.x = object.x + FP.sign(deltax) * Math.round(Math.abs(deltax));\n object.y = object.y + FP.sign(deltay) * Math.round(Math.abs(deltay));\n }\n \n /**\n * Anchors the object to a position.\n * @param object The object to anchor.\n * @param anchor The anchor object.\n * @param distance The max distance object can be anchored to the anchor.\n */\n public static void anchorTo(Positionable object, Positionable anchor, float distance)\n {\n point.x = object.x - anchor.x;\n point.y = object.y - anchor.y;\n double len = PointF.length(point.x, point.y);\n if (len > distance) {\n point.x /= len;\n point.y /= len;\n }\n object.x = anchor.x + point.x;\n object.y = anchor.y + point.y;\n }\n \n /**\n * Finds the angle (in degrees) from point 1 to point 2.\n * @param x1 The first x-position.\n * @param y1 The first y-position.\n * @param x2 The second x-position.\n * @param y2 The second y-position.\n * @return The angle from (x1, y1) to (x2, y2).\n */\n public static double angle(int x1, int y1, int x2, int y2) {\n return angle((float)x1,(float)y1,(float)x2,(float)y2);\n }\n \n public static double angle(float x1, float y1, float x2, float y2) {\n double a = Math.atan2(y2 - y1, x2 - x1) * DEG;\n return a < 0 ? a + 360 : a;\n }\n \n /**\n * Sets the x/y values of the provided object to a vector of the specified angle and length.\n * @param object The object whose x/y properties should be set.\n * @param angle The angle of the vector, in degrees.\n * @param length The distance to the vector from (0, 0).\n * @param x X offset.\n * @param y Y offset.\n */\n public static void angleXY(Positionable object, double angle) {\n angleXY(object, angle,1,0,0);\n }\n public static void angleXY(Positionable object, double angle, double length) {\n angleXY(object, angle, length, 0, 0);\n }\n public static void angleXY(Positionable object, double angle, double length, int x) {\n angleXY(object, angle, length, x, 0);\n }\n public static void angleXY(Positionable object, double angle, double length, int x, int y) {\n angle *= RAD;\n object.x = (int)(Math.cos(angle) * length + x);\n object.y = (int)(Math.sin(angle) * length + y);\n }\n \n /**\n * Rotates the object around the anchor by the specified amount.\n * @param object Object to rotate around the anchor.\n * @param anchor Anchor to rotate around.\n * @param angle The amount of degrees to rotate by.\n */\n \n public static void rotateAround(Positionable object, Positionable anchor, double angle) {\n rotateAround(object, anchor, angle, true);\n }\n \n public static void rotateAround(Positionable object, Positionable anchor, double angle, boolean relative) {\n if (relative) \n angle += FP.angle(anchor.x, anchor.y, object.x, object.y);\n FP.angleXY(object, angle, FP.distance(anchor.x, anchor.y, object.x, object.y), anchor.x, anchor.y);\n }\n \n /**\n * Gets the difference of two angles, wrapped around to the range -180 to 180.\n * @param a First angle in degrees.\n * @param b Second angle in degrees.\n * @return Difference in angles, wrapped around to the range -180 to 180.\n */\n public static double angleDiff(double a, double b) {\n double diff = b- a;\n\n while (diff > 180) { diff -= 360; }\n while (diff <= -180) { diff += 360; }\n\n return diff;\n }\n \n \n /**\n * Find the distance from (0, 0).\n * @param x1 The first x-position.\n * @param y1 The first y-position.\n * @return The distance.\n */\n public static double distance(int x1, int y1) {\n return distance(x1,y1,0,0);\n }\n \n /**\n * Find the distance between two points.\n * @param x1 The first x-position.\n * @param y1 The first y-position.\n * @param x2 The second x-position.\n * @param y2 The second y-position.\n * @return The distance.\n */\n public static double distance(int x1, int y1, int x2, int y2) {\n return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));\n }\n \n /**\n * Find the distance between two rectangles. Will return 0 if the rectangles overlap.\n * @param x1 The x-position of the first rect.\n * @param y1 The y-position of the first rect.\n * @param w1 The width of the first rect.\n * @param h1 The height of the first rect.\n * @param x2 The x-position of the second rect.\n * @param y2 The y-position of the second rect.\n * @param w2 The width of the second rect.\n * @param h2 The height of the second rect.\n * @return The distance.\n */\n public static double distanceRects(int x1, int y1, int w1, int h1, int x2, int y2, int w2, int h2) {\n if (x1 < x2 + w2 && x2 < x1 + w1)\n {\n if (y1 < y2 + h2 && y2 < y1 + h1) \n return 0;\n if (y1 > y2) \n return y1 - (y2 + h2);\n return y2 - (y1 + h1);\n }\n if (y1 < y2 + h2 && y2 < y1 + h1)\n {\n if (x1 > x2) \n return x1 - (x2 + w2);\n return x2 - (x1 + w1);\n }\n if (x1 > x2)\n {\n if (y1 > y2) \n return distance(x1, y1, (x2 + w2), (y2 + h2));\n return distance(x1, y1 + h1, x2 + w2, y2);\n }\n if (y1 > y2) \n return distance(x1 + w1, y1, x2, y2 + h2);\n return distance(x1 + w1, y1 + h1, x2, y2);\n }\n \n /**\n * Find the distance between a point and a rectangle. Returns 0 if the point is within the rectangle.\n * @param px The x-position of the point.\n * @param py The y-position of the point.\n * @param rx The x-position of the rect.\n * @param ry The y-position of the rect.\n * @param rw The width of the rect.\n * @param rh The height of the rect.\n * @return The distance.\n */\n public static double distanceRectPoint(int px, int py, int rx, int ry, int rw, int rh) {\n if (px >= rx && px <= rx + rw)\n {\n if (py >= ry && py <= ry + rh) \n return 0;\n if (py > ry) \n return py - (ry + rh);\n return ry - py;\n }\n if (py >= ry && py <= ry + rh)\n {\n if (px > rx) \n return px - (rx + rw);\n return rx - px;\n }\n if (px > rx)\n {\n if (py > ry) \n return distance(px, py, rx + rw, ry + rh);\n return distance(px, py, rx + rw, ry);\n }\n if (py > ry) \n return distance(px, py, rx, ry + rh);\n return distance(px, py, rx, ry);\n }\n \n /**\n * Clamps the value within the minimum and maximum values.\n * @param value The Number to evaluate.\n * @param min The minimum range.\n * @param max The maximum range.\n * @return The clamped value.\n */\n public static int clamp(int value, int min, int max)\n {\n if (max > min)\n {\n value = value < max ? value : max;\n return value > min ? value : min;\n }\n value = value < min ? value : min;\n return value > max ? value : max;\n }\n \n /**\n * Clamps the object inside the rectangle.\n * @param object The object to clamp (must have an x and y property).\n * @param x Rectangle's x.\n * @param y Rectangle's y.\n * @param width Rectangle's width.\n * @param height Rectangle's height.\n */\n public static void clampInRect(Positionable object, int x, int y, int width, int height) {\n clampInRect(object, x, y, width, height, 0);\n }\n \n /**\n * Clamps the object inside the rectangle.\n * @param object The object to clamp (must have an x and y property).\n * @param x Rectangle's x.\n * @param y Rectangle's y.\n * @param width Rectangle's width.\n * @param height Rectangle's height.\n * @param padding Padding on the Rectangle.\n */\n public static void clampInRect(Positionable object, int x, int y, int width, int height, int padding) {\n object.x = clamp(object.x, x + padding, x + width - padding);\n object.y = clamp(object.y, y + padding, y + height - padding);\n }\n \n /**\n * Transfers a value from one scale to another scale. For example, scale(.5, 0, 1, 10, 20) == 15, and scale(3, 0, 5, 100, 0) == 40.\n * @param value The value on the first scale.\n * @param min The minimum range of the first scale.\n * @param max The maximum range of the first scale.\n * @param min2 The minimum range of the second scale.\n * @param max2 The maximum range of the second scale.\n * @return The scaled value.\n */\n public static double scale(double value, double min, double max, double min2, double max2) {\n return min2 + ((value - min) / (max - min)) * (max2 - min2);\n }\n \n /**\n * Transfers a value from one scale to another scale, but clamps the return value within the second scale.\n * @param value The value on the first scale.\n * @param min The minimum range of the first scale.\n * @param max The maximum range of the first scale.\n * @param min2 The minimum range of the second scale.\n * @param max2 The maximum range of the second scale.\n * @return The scaled and clamped value.\n */\n public static double scaleClamp(double value, double min, double max, double min2, double max2) {\n value = min2 + ((value - min) / (max - min)) * (max2 - min2);\n if (max2 > min2)\n {\n value = value < max2 ? value : max2;\n return value > min2 ? value : min2;\n }\n value = value < min2 ? value : min2;\n return value > max2 ? value : max2;\n }\n \n /**\n * The random seed used by FP's random functions.\n */\n public static long getRandomSeed() {\n return mGetSeed;\n }\n \n public static void setRandomSeed(int value) {\n mSeed = FP.clamp(value,1, Integer.MAX_VALUE);\n mGetSeed = mSeed;\n }\n \n /**\n * Randomizes the random seed using Java's Math.random() function.\n */\n public static void randomizeSeed() {\n setRandomSeed((int)(Integer.MAX_VALUE * Math.random()));\n }\n \n /**\n * A pseudo-random Number produced using FP's random seed, where 0 <= Number < 1.\n */\n public static double random() {\n mSeed = (mSeed * 16807) % Integer.MAX_VALUE;\n return (double)mSeed / Integer.MAX_VALUE;\n }\n \n /**\n * Returns a pseudo-random uint.\n * @param amount The returned int will always be 0 <= uint < amount.\n * @return The uint.\n */\n public static int rand(int amount) {\n mSeed = (mSeed * 16807) % Integer.MAX_VALUE;\n return (int)(((double)mSeed / Integer.MAX_VALUE) * amount);\n }\n \n /**\n\t * Returns the next item after current in the list of options.\n\t * @param\tcurrent\t\tThe currently selected item (must be one of the options).\n\t * @param\toptions\t\tAn array of all the items to cycle through.\n\t * @param\tloop\t\tIf true, will jump to the first item after the last item is reached.\n\t * @return\tThe next item in the list.\n\t */\n\tpublic static Object next(Object current, Object[] options, boolean loop) {\n\t\t\n\t\tfor (int i = 0; i < options.length; i++) {\n\t\t\tif (options[i].equals(current)) {\n\t\t\t\tif (loop) {\n\t\t\t\t\treturn options[i+1 % options.length];\n\t\t\t\t} else {\n\t\t\t\t\treturn options[Math.max(i + 1, options.length - 1)];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\t/**\n\t * Returns the item previous to the current in the list of options.\n\t * @param\tcurrent\t\tThe currently selected item (must be one of the options).\n\t * @param\toptions\t\tAn array of all the items to cycle through.\n\t * @param\tloop\t\tIf true, will jump to the last item after the first is reached.\n\t * @return\tThe previous item in the list.\n\t */\n\tpublic static Object prev(Object current, Object[] options, boolean loop) {\n\t\t\n\t\tfor (int i = 0; i < options.length; i++) {\n\t\t\tif (options[i].equals(current)) {\n\t\t\t\tif (loop) {\n\t\t\t\t\treturn options[(i-1 + options.length) % options.length];\n\t\t\t\t} else {\n\t\t\t\t\treturn options[Math.max(i - 1, 0)];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\t/**\n\t * Swaps the current item between a and b. Useful for quick state/string/value swapping.\n\t * @param\tcurrent\t\tThe currently selected item.\n\t * @param\ta\t\t\tItem a.\n\t * @param\tb\t\t\tItem b.\n\t * @return\tReturns a if current is b, and b if current is a.\n\t */\n\tpublic static Object swap(Object current, Object a, Object b) {\n\t\treturn (current == a) ? b : a;\n\t}\n\n\t\n\t/**\n\t * Creates a color value by combining the chosen RGB values.\n\t * @param\tR\t\tThe red value of the color, from 0 to 255.\n\t * @param\tG\t\tThe green value of the color, from 0 to 255.\n\t * @param\tB\t\tThe blue value of the color, from 0 to 255.\n\t * @return\tThe color uint.\n\t */\n\tpublic static int getColorRGB(int r, int g, int b) {\n\t\treturn Color.rgb(r, g, b);\n\t}\n\t\n\t/**\n\t * Creates a color value with the chosen HSV values.\n\t * @param\th\t\tThe hue of the color (from 0 to 1).\n\t * @param\ts\t\tThe saturation of the color (from 0 to 1).\n\t * @param\tv\t\tThe value of the color (from 0 to 1).\n\t * @return\tThe color uint.\n\t */\n\tpublic static int getColorHSV(float h, float s, float v) {\n\t\t\n\t\tHSV[0] = h;\n\t\tHSV[1] = s;\n\t\tHSV[2] = v;\n\t\treturn Color.HSVToColor(HSV);\n\t}\n\t\n\t/**\n\t * Finds the red factor of a color.\n\t * @param\tcolor\t\tThe color to evaluate.\n\t * @return\tA uint from 0 to 255.\n\t */\n\tpublic static int getRed(int color) {\n\t\treturn Color.red(color);\n\t}\n\t\n\t/**\n\t * Finds the green factor of a color.\n\t * @param\tcolor\t\tThe color to evaluate.\n\t * @return\tA uint from 0 to 255.\n\t */\n\tpublic static int getGreen(int color) {\n\t\treturn Color.green(color);\n\t}\n\t\n\t/**\n\t * Finds the blue factor of a color.\n\t * @param\tcolor\t\tThe color to evaluate.\n\t * @return\tA uint from 0 to 255.\n\t */\n\tpublic static int getBlue(int color) {\n\t\treturn Color.blue(color);\n\t}\n\t\n\t/**\n\t * Sets a time flag.\n\t * @return\tTime elapsed (in milliseconds) since the last time flag was set.\n\t */\n\tpublic static long timeFlag() {\n\t\tlong t = System.currentTimeMillis();\n\t\tlong e = t - mTime;\n\t\tmTime = t;\n\t\treturn e;\n\t}\n\t\n\t/**\n\t * The global Console object.\n\t */\n\tpublic static Console getConsole() {\n\t\tif (mConsole == null) \n\t\t\tmConsole = new Console();\n\t\treturn mConsole;\n\t}\n\t\n\t/**\n\t * Logs data to the console.\n\t * @param\t...data\t\tThe data parameters to log, can be variables, objects, etc. Parameters will be separated by a space (\" \").\n\t */\n\tpublic static void log(Object... data) {\n\t\tif (mConsole != null) {\n\t\t\tif (data.length > 1) {\n\t\t\t\tint i = 0;\n\t\t\t\tString s = \"\";\n\t\t\t\twhile (i < data.length)\n\t\t\t\t{\n\t\t\t\t\tif (i > 0)\n\t\t\t\t\t\ts += \" \";\n\t\t\t\t\ts += data[i++].toString();\n\t\t\t\t}\n\t\t\t\tmConsole.log(s);\n\t\t\t} else {\n\t\t\t\tmConsole.log(data[0].toString());\n\t\t\t}\n\t\t}\n\t}\n\t\n\t\n\t/**\n\t * Get a list of a directory of the assets path.\n\t * @param path to check for files\n\t * @return a string array of the filenames.\n\t */\n\tpublic static String[] getAssetList(String path) {\n\t\ttry {\n\t\t\treturn FP.context.getAssets().list(path);\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn null;\n\t}\n\t\n\t/**\n\t * Get the file descriptor of an asset.\n\t * @param path to the file.\n\t * @return the file descriptor for the asset. \n\t */\n\tpublic static InputStream getAsset(String file) {\n\t\ttry {\n\t\t\treturn FP.context.getAssets().open(file);\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn null;\n\t}\n\t\n\t/**\n\t * Loads the file as an XML object.\n\t * @param\tfile\t\tThe embedded file to load.\n\t * @return\tAn XML object representing the file.\n\t */\n\tpublic static Document getXML(int resId) {\n\t\treturn createDocument(FP.context.getResources().openRawResource(resId));\n\t\t\n\t}\n\t\n\t/**\n\t * Loads the file as an XML object.\n\t * @param\tassetFile\t\tThe asset file to load.\n\t * @return\tAn XML object representing the file.\n\t */\n\tpublic static Document getXML(String assetFile) {\n\t\treturn createDocument(getAsset(assetFile));\n\t}\n\t\n\tprivate static Document createDocument(InputStream is) {\n\t\tif (is == null) {\n\t\t\treturn null;\n\t\t}\n\t\tDocumentBuilderFactory builderfactory = DocumentBuilderFactory.newInstance();\n\t\tDocument d;\n\t\ttry {\n\t\t\td = builderfactory.newDocumentBuilder().parse(is);\n\t\t\treturn d;\n\t\t} catch (SAXException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (ParserConfigurationException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tpublic static Map<String, Number> tweenmap(String k1, Number v1) {\n\t\treturn tweenmap(k1, v1, null, null, null, null, null, null, null, null);\n\t}\n\t\n\tpublic static Map<String, Number> tweenmap(String k1, Number v1, String k2, Number v2) {\n\t\treturn tweenmap(k1,v1,k2,v2, null, null, null, null, null, null);\n\t}\n\t\n\tpublic static Map<String, Number> tweenmap(String k1, Number v1, String k2, Number v2, String k3, Number v3) {\n\t\treturn tweenmap(k1,v1,k2,v2,k3,v3, null, null, null, null);\n\t}\n\t\n\tpublic static Map<String, Number> tweenmap(String k1, Number v1, String k2, Number v2, String k3, Number v3, String k4, Number v4) {\n\t\treturn tweenmap(k1,v1,k2,v2,k3,v3,k4,v4, null, null);\n\t}\n\t\n\tpublic static Map<String, Number> tweenmap(String k1, Number v1, String k2, Number v2,\n\t\t\t\t\t\t\t\t\t\t\tString k3, Number v3, String k4, Number v4,\n\t\t\t\t\t\t\t\t\t\t\tString k5, Number v5) {\n\t\tMap<String, Number> theMap = new HashMap<String, Number>();\n\t\t\n\t\tif (k5 != null) \n\t\t\ttheMap.put(k5, v5);\n\t\tif (k4 != null) \n\t\t\ttheMap.put(k4, v4);\n\t\tif (k3 != null) \n\t\t\ttheMap.put(k3, v3);\n\t\tif (k2 != null) \n\t\t\ttheMap.put(k2, v2);\n\t\tif (k1 != null) \n\t\t\ttheMap.put(k1, v1);\n\t\t\n\t\treturn theMap;\n\t}\n\t\n\tpublic static class TweenOptions {\n\t\tint type;\n\t\tOnCompleteCallback complete;\n\t\tOnEaseCallback ease;\n\t\tTweener tweener;\n\t\t\n\t\tpublic TweenOptions(int theType, OnCompleteCallback theComplete, OnEaseCallback theEase, Tweener theTweener) {\n\t\t\ttype = theType;\n\t\t\tcomplete = theComplete;\n\t\t\tease = theEase;\n\t\t\ttweener = theTweener;\n\t\t}\n\t}\n\t\n\tpublic static MultiVarTween tween(Object object, Map<String, Number> values, float duration) {\n\t\treturn tween(object, values, duration, null);\n\t}\n\t/**\n\t * Tweens numeric public properties of an Object. Shorthand for creating a MultiVarTween tween, starting it and adding it to a Tweener.\n\t * @param\tobject\t\tThe object containing the properties to tween.\n\t * @param\tvalues\t\tAn object containing key/value pairs of properties and target values.\n\t * @param\tduration\tDuration of the tween.\n\t * @param\toptions\t\tAn object containing key/value pairs of the following optional parameters:\n\t * \t\t\t\t\t\ttype\t\tTween type.\n\t * \t\t\t\t\t\tcomplete\tOptional completion callback function.\n\t * \t\t\t\t\t\tease\t\tOptional easer function.\n\t * \t\t\t\t\t\ttweener\t\tThe Tweener to add this Tween to.\n\t * @return\tThe added MultiVarTween object.\n\t * \n\t * Example: FP.tween(object, { x: 500, y: 350 }, 2.0, { ease: easeFunction, complete: onComplete } );\n\t */\n\t\n\tpublic static MultiVarTween tween(Object object, Map<String, Number> values, float duration, TweenOptions options) {\n\t\tint type = Tween.ONESHOT;\n\t\tOnCompleteCallback complete = null;\n\t\tOnEaseCallback ease = null;\n\t\tTweener tweener = FP.getWorld();\n\t\t\n\t\tif (object instanceof Tweener) \n\t\t\ttweener = (Tweener)object;\n\t\tif (options != null){\n\t\t\ttype = options.type;\n\t\t\tcomplete = options.complete;\n\t\t\tease = options.ease;\n\t\t\ttweener = options.tweener;\n\t\t}\n\t\tMultiVarTween tween = new MultiVarTween(complete, type);\n\t\ttween.tween(object, values, duration, ease);\n\t\ttweener.addTween(tween);\n\t\treturn tween;\n\t} \n\t\n\tpublic static int[] frames(int from, int to) {\n\t\treturn frames(from, to, 0);\n\t}\n\t\n\t/**\n\t * Gets an array of frame indices.\n\t * @param\tfrom\tStarting frame.\n\t * @param\tto\t\tEnding frame.\n\t * @param\tskip\tSkip amount every frame (eg. use 1 for every 2nd frame).\n\t */\n\tpublic static int[] frames(int from, int to, int skip) {\n\t\tint index = 0;\n\t\tskip++;\n\t\tint a[] = new int[(int)(Math.abs(to - from) / skip) + 1];\n\t\tif (from < to) {\n\t\t\twhile (from <= to) {\n\t\t\t\ta[index++] = from;\n\t\t\t\tfrom += skip;\n\t\t\t}\n\t\t} else {\n\t\t\twhile (from >= to) {\n\t\t\t\ta[index++] = from;\n\t\t\t\tfrom -= skip;\n\t\t\t}\n\t\t}\n\t\treturn a;\n\t}\n\t\n\t/**\n\t * Shuffles the elements in the array.\n\t * @param\ta\t\tThe Object to shuffle (an Array or Vector).\n\t */\n\tpublic static void shuffle(Object[] a) {\n\t\tint i = a.length;\n\t\tint j;\n\t\tObject t;\n\t\t\n\t\twhile (--i > 0) {\n\t\t\tt = a[i];\n\t\t\ta[i] = a[j = FP.rand(i + 1)];\n\t\t\ta[j] = t;\n\t\t}\n\t}\n\t\n\t/**\n\t * Shuffles the elements in the array.\n\t * @param\ta\t\tThe Object to shuffle (an Array or Vector).\n\t */\n\tpublic static void shuffle(Vector<Object> a) {\n\t\tint i = a.size();\n\t\tint j;\n\t\tObject t;\n\t\t\n\t\twhile (--i > 0) {\n\t\t\tt = a.get(i);\n\t\t\ta.add(i, a.get(j = FP.rand(i + 1)));\n\t\t\ta.add(j, t);\n\t\t}\n\t}\n\t\n\t/**\n\t * Get a bitmap from the Android resource package using Resource id. Consider these immutable and cached.\n\t * \n\t * Make a copy if you need to edit it.\n\t * @param resId the resource id to load.\n\t * @return A bitmap of resource id for the current display density.\n\t */\n\tpublic static Bitmap getBitmap(int resId) {\n\t\tBitmap bm = CACHED_BITMAPS.get(resId);\n\t\tif (bm == null) {\n\t\t\t//TODO do something with scale.\n\t\t\tDrawable d = FP.resources.getDrawable(resId);\n\t\t\tbm = ((BitmapDrawable) d).getBitmap();\n\t\t\tCACHED_BITMAPS.put(resId, bm);\n\t\t}\n\t\treturn bm;\n\t}\n\t\n\tpublic static void clearCachedBitmaps() {\n\t\tIterator<Integer> it = CACHED_BITMAPS.keySet().iterator();\n\t\twhile (it.hasNext()) {\n\t\t\tint i = it.next();\n\t\t\tit.remove();\n\t\t}\n\t}\n}", "public class SpriteMap extends AtlasGraphic {\r\n\tprivate static final String TAG = \"SpriteMap\";\r\n\t\r\n\tpublic abstract static class OnAnimationEndCallback {\r\n\t\tpublic abstract void onAnimationEnd();\r\n\t}\r\n\t\r\n\t/**\r\n\t * If the animation has stopped.\r\n\t */\r\n\tpublic boolean complete = true;\r\n\r\n\t/**\r\n\t * Optional callback function for animation end.\r\n\t */\r\n\tpublic OnAnimationEndCallback callback;\r\n\r\n\t/**\r\n\t * Animation speed factor, alter this to speed up/slow down all animations.\r\n\t */\r\n\tpublic float rate = 1;\r\n\t\r\n\t// Spritemap information.\r\n\tprotected int mWidth;\r\n\tprotected int mHeight;\r\n\tprivate int mColumns;\r\n\tprivate int mRows;\r\n\tprivate int mFrameCount;\r\n\tprivate final Map<String, Anim> mAnims = new HashMap<String, Anim>();\r\n\tprivate Anim mAnim;\r\n\tprivate int mIndex;\r\n\tprotected int mFrame;\r\n\tprivate float mTimer = 0;\r\n\t\r\n\tprotected int mFrameWidth;\r\n\tprotected int mFrameHeight;\r\n\t\r\n\tprotected FloatBuffer mVertexBuffer = getDirectFloatBuffer(8);\r\n\tprotected FloatBuffer mTextureBuffer = getDirectFloatBuffer(8);\r\n\t\r\n\t/**\r\n\t * Constructor. frame width = frame height = 0 and no callback.\r\n\t * @param\tsource\t\t\tSource image.\r\n\t */\r\n\tpublic SpriteMap(SubTexture subTexture) {\r\n\t\tthis(subTexture, 0, 0, null);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Constructor. No callback\r\n\t * @param\tsource\t\t\tSource image.\r\n\t * @param\tframeWidth\t\tFrame width.\r\n\t * @param\tframeHeight\t\tFrame height.\r\n\t */\r\n\tpublic SpriteMap(SubTexture subTexture, int frameWidth, int frameHeight) {\r\n\t\tthis(subTexture, frameWidth, frameHeight, null);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Constructor.\r\n\t * @param\tsource\t\t\tSource image.\r\n\t * @param\tframeWidth\t\tFrame width.\r\n\t * @param\tframeHeight\t\tFrame height.\r\n\t * @param\tcallback\t\tOptional callback function for animation end.\r\n\t */\r\n\tpublic SpriteMap(SubTexture subTexture, int frameWidth, int frameHeight, OnAnimationEndCallback callback) {\r\n\t\tsuper(subTexture);\r\n\t\t\r\n\t\tmFrameWidth = frameWidth;\r\n\t\tmFrameHeight = frameHeight;\r\n\t\t\r\n\t\tmWidth = subTexture.getWidth();\r\n\t\tmHeight = subTexture.getHeight();\r\n\t\tmColumns = mWidth / frameWidth;\r\n\t\tmRows = mHeight / frameHeight;\r\n\t\tmFrameCount = mColumns * mRows;\r\n\t\tthis.callback = callback;\r\n\t\tactive = true;\r\n\t\t\r\n\t\tmTextureBuffer = getDirectFloatBuffer(8*mFrameCount);\r\n\t\t\r\n\t\tsetGeometryBuffer(mVertexBuffer, 0, 0, mFrameWidth, mFrameHeight);\r\n\t\t\r\n\t\tRect r = FP.rect;\r\n\t\t\r\n\t\tmTextureBuffer.position(0);\r\n\t\tTexture t = subTexture.getTexture();\r\n\t\tfor( int i = 0; i < mFrameCount; i++) {\r\n\t\t\tsubTexture.getFrame(r, i, frameWidth, frameHeight);\r\n\t\t\t\r\n\t\t\tmTextureBuffer.put((float)r.left/t.getWidth()).put((float)r.top/t.getHeight());\r\n\t\t\tmTextureBuffer.put((float)(r.left + r.width())/t.getWidth()).put((float)r.top/t.getHeight());\r\n\t\t\tmTextureBuffer.put((float)r.left/t.getWidth()).put((float)(r.top + r.height())/t.getHeight());\r\n\t\t\tmTextureBuffer.put((float)(r.left + r.width())/t.getWidth()).put((float)(r.top + r.height())/t.getHeight());\r\n\t\t}\r\n\t\t//setTextureBuffer(mTextureBuffer, mSubTexture, 0, mFrameWidth, mFrameHeight);\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic void render(GL10 gl, Point point, Point camera) {\r\n\t\tsuper.render(gl, point, camera);\r\n\t\tif (!getAtlas().isLoaded()) {\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tmPoint.x = (int)(point.x + x - camera.x * scrollX);\r\n\t\tmPoint.y = (int)(point.y + y - camera.y * scrollY);\r\n\t\t\r\n\t\toriginX = mFrameWidth/2;\r\n\t\toriginY = mFrameHeight/2;\r\n\t\t\r\n\t\tmTextureBuffer.position(8 * mFrame);\r\n\t\tsetBuffers(gl, mVertexBuffer, mTextureBuffer);\r\n\t\t\r\n\t\tgl.glPushMatrix(); \r\n\t\t{\r\n\t\t\tsetMatrix(gl);\r\n\t\t\tgl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);\r\n\t\t}\r\n\t\tgl.glPopMatrix();\r\n\t}\r\n\r\n\t/** @private Updates the animation. */\r\n\t@Override \r\n\tpublic void update() {\r\n\t\tif (mAnim != null && !complete) {\r\n\t\t\tmTimer += (FP.fixed ? mAnim.mFrameRate : mAnim.mFrameRate * FP.elapsed) * rate;\r\n\t\t\tif (mTimer >= 1) {\r\n\t\t\t\twhile (mTimer >= 1) {\r\n\t\t\t\t\tmTimer -= 1;\r\n\t\t\t\t\tmIndex++;\r\n\t\t\t\t\tif (mIndex == mAnim.mFrameCount) {\r\n\t\t\t\t\t\tif (mAnim.mLoop) {\r\n\t\t\t\t\t\t\tmIndex = 0;\r\n\t\t\t\t\t\t\tif (callback != null) \r\n\t\t\t\t\t\t\t\tcallback.onAnimationEnd();\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tmIndex = mAnim.mFrameCount - 1;\r\n\t\t\t\t\t\t\tcomplete = true;\r\n\t\t\t\t\t\t\tif (callback != null)\r\n\t\t\t\t\t\t\t\tcallback.onAnimationEnd();\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif (mAnim != null) {\r\n\t\t\t\t\tmFrame = (int)(mAnim.mFrames[mIndex]);\r\n\t\t\t\t\t//setTextureBuffer(mTextureBuffer, mSubTexture, mFrame, mFrameWidth, mFrameHeight);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\t/**\r\n\t * Add an Animation with no change.\r\n\t * @param\tname\t\tName of the animation.\r\n\t * @param\tframes\t\tArray of frame indices to animate through.\r\n\t * @return\tA new Anim object for the animation.\r\n\t */\r\n\tpublic Anim add(String name, int[] frames) {\r\n\t\treturn add(name, frames, 0, true);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Add a looping Animation.\r\n\t * @param\tname\t\tName of the animation.\r\n\t * @param\tframes\t\tArray of frame indices to animate through.\r\n\t * @param\tframeRate\tAnimation speed.\r\n\t * @return\tA new Anim object for the animation.\r\n\t */\r\n\tpublic Anim add(String name, int[] frames, int frameRate) {\r\n\t\treturn add(name, frames, frameRate, true);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Add an Animation.\r\n\t * @param\tname\t\tName of the animation.\r\n\t * @param\tframes\t\tArray of frame indices to animate through.\r\n\t * @param\tframeRate\tAnimation speed.\r\n\t * @param\tloop\t\tIf the animation should loop.\r\n\t * @return\tA new Anim object for the animation.\r\n\t */\r\n\tpublic Anim add(String name, int[] frames, int frameRate, boolean loop) {\r\n\t\tif (mAnims.get(name) != null) {\r\n\t\t\tLog.e(TAG, \"Cannot have multiple animations with the same name\");\r\n\t\t\t\r\n\t\t}\r\n\t\tAnim a = new Anim(name, frames, frameRate, loop);\r\n\t\ta.mParent = this;\r\n\t\tmAnims.put(name, a);\r\n\t\treturn a;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Plays an animation, without restarting it if already playing.\r\n\t * @param\tname\t\tName of the animation to play.\r\n\t * @return\tAnim object representing the played animation.\r\n\t */\r\n\tpublic Anim play(String name) {\r\n\t\treturn play(name, false);\r\n\t}\r\n\t/**\r\n\t * Plays an animation.\r\n\t * @param\tname\t\tName of the animation to play.\r\n\t * @param\treset\t\tIf the animation should force-restart if it is already playing.\r\n\t * @return\tAnim object representing the played animation.\r\n\t */\r\n\tpublic Anim play(String name, boolean reset) {\r\n\t\tif (!reset && mAnim != null && mAnim.mName.equals(name))\r\n\t\t\t\treturn mAnim;\r\n\t\tmAnim = mAnims.get(name);\r\n\t\tif (mAnim == null) {\r\n\t\t\tmFrame = mIndex = 0;\r\n\t\t\tcomplete = true;\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\tmIndex = 0;\r\n\t\tmTimer = 0;\r\n\t\tmFrame = mAnim.mFrames[0];\r\n\t\tsetTextureBuffer(mTextureBuffer, mSubTexture, mFrame, mFrameWidth, mFrameHeight);\r\n\t\tcomplete = false;\r\n\t\treturn mAnim;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Gets the frame index of the first column and row of the source image.\r\n\t * @param\tcolumn\t\tFrame column.\r\n\t * @param\trow\t\t\tFrame row.\r\n\t * @return\tFrame index.\r\n\t */\r\n\tpublic int getFrame() {\r\n\t\treturn getFrame(0, 0);\r\n\t}\r\n\t/**\r\n\t * Gets the frame index based on the column and first row of the source image.\r\n\t * @param\tcolumn\t\tFrame column.\r\n\t * @param\trow\t\t\tFrame row.\r\n\t * @return\tFrame index.\r\n\t */\r\n\tpublic int getFrame(int column) {\r\n\t\treturn getFrame(column, 0);\r\n\t}\r\n\t/**\r\n\t * Gets the frame index based on the column and row of the source image.\r\n\t * @param\tcolumn\t\tFrame column.\r\n\t * @param\trow\t\t\tFrame row.\r\n\t * @return\tFrame index.\r\n\t */\r\n\tpublic int getFrame(int column, int row) {\r\n\t\treturn (row % mRows) * mColumns + (column % mColumns);\r\n\t}\r\n\t\r\n\r\n\t/**\r\n\t * Sets the current display frame based on the column and first row of the source image.\r\n\t * When you set the frame, any animations playing will be stopped to force the frame.\r\n\t * @param\tcolumn\t\tFrame column.\r\n\t */\r\n\tpublic void setFrame(int column) {\r\n\t\tsetFrame(column, 0);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Sets the current display frame based on the column and row of the source image.\r\n\t * When you set the frame, any animations playing will be stopped to force the frame.\r\n\t * @param\tcolumn\t\tFrame column.\r\n\t * @param\trow\t\t\tFrame row.\r\n\t */\r\n\tpublic void setFrame(int column, int row) {\r\n\t\tmAnim = null;\r\n\t\tint frame = (row % mRows) * mColumns + (column % mColumns);\r\n\t\tif (mFrame == frame) \r\n\t\t\treturn;\r\n\t\tmFrame = frame;\r\n\t\tsetTextureBuffer(mTextureBuffer, mSubTexture, mFrame, mFrameWidth, mFrameHeight);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Assigns the Spritemap to a random frame.\r\n\t */\r\n\tpublic void randFrame() {\r\n\t\tsetFrameIndex(FP.rand(mFrameCount));\r\n\t}\r\n\t\r\n\t/**\r\n\t * Sets the frame to the frame index of an animation.\r\n\t * @param\tname\tAnimation to draw the frame frame.\r\n\t * @param\tindex\tIndex of the frame of the animation to set to.\r\n\t */\r\n\tpublic void setAnimFrame(String name, int index) {\r\n\t\tAnim a = mAnims.get(name);\r\n\t\tif (a != null) {\r\n\t\t\tint frames[] = a.mFrames;\r\n\t\t\tindex %= frames.length;\r\n\t\t\tif (index < 0)\r\n\t\t\t\tindex += frames.length;\r\n\t\t\tsetFrameIndex(frames[index]);\r\n\t\t}\r\n\t}\r\n\t\r\n\t/**\r\n\t * Gets the current frame index.\r\n\t */\r\n\tpublic int getFrameIndex() { return mFrame; }\r\n\t\r\n\t/**\r\n\t * Sets the current frame index. When you set this, any\r\n\t * animations playing will be stopped to force the frame.\r\n\t */\r\n\tpublic void setFrameIndex(int value) {\r\n\t\tmAnim = null;\r\n\t\tvalue %= mFrameCount;\r\n\t\tif (value < 0)\r\n\t\t\tvalue = mFrameCount + value;\r\n\t\tif (mFrame == value) \r\n\t\t\treturn;\r\n\t\tmFrame = value;\r\n\t\tsetTextureBuffer(mTextureBuffer, mSubTexture, mFrame, mFrameWidth, mFrameHeight);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Current index of the playing animation.\r\n\t */\r\n\tpublic int getAnimIndex() { return mAnim != null ? mIndex : 0; }\r\n\t/**\r\n\t * Current index of the playing animation.\r\n\t */\r\n\tpublic void setAnimIndex(int value) {\r\n\t\tif (mAnim == null)\r\n\t\t\treturn;\r\n\t\tvalue %= mAnim.mFrameCount;\r\n\t\tif (mIndex == value)\r\n\t\t\treturn;\r\n\t\tmIndex = value;\r\n\t\tmFrame = mAnim.mFrames[mIndex];\r\n\t\tsetTextureBuffer(mTextureBuffer, mSubTexture, mFrame, mFrameWidth, mFrameHeight);\r\n\t}\r\n\t\r\n\t/**\r\n\t * The amount of frames in the Spritemap.\r\n\t */\r\n\tpublic int getFrameCount() { return mFrameCount; }\r\n\r\n\t/**\r\n\t * Columns in the Spritemap.\r\n\t */\r\n\tpublic int getColumns() { return mColumns; }\r\n\r\n\t/**\r\n\t * Rows in the Spritemap.\r\n\t */\r\n\tpublic int getRows() { return mRows; }\r\n\t\r\n\t/**\r\n\t * The currently playing animation.\r\n\t */\r\n\tpublic String getCurrentAnim() { return mAnim != null ? mAnim.mName : \"\"; }\r\n\t\r\n\t/**\r\n\t * The framewidth of this spritemap.\r\n\t */\r\n\tpublic int getFrameWidth() { return mFrameWidth; }\r\n\t\r\n\t/**\r\n\t * The frameheight of this spritemap.\r\n\t */\r\n\tpublic int getFrameHeight() { return mFrameHeight; }\r\n}\r", "public class TileMap extends AtlasGraphic {\r\n\r\n\tprivate static final String TAG = \"TileMap\";\r\n\t/**\r\n\t * If x/y positions should be used instead of columns/rows.\r\n\t */\r\n\tpublic boolean usePositions = false;\r\n\t\r\n\tprivate FloatBuffer mVertexBuffer;\r\n\tprivate FloatBuffer mTextureBuffer;\r\n\tprivate CharBuffer mIndexBuffer;\r\n\t\r\n\tprivate int mIndexCount;\r\n\tprivate int mVerticesCount;\r\n\tprivate int mVerticiesAcross;\r\n\tprivate int mVerticiesDown;\r\n\t\r\n\t// Tilemap information.\r\n\tprotected Bitmap mMap;\r\n\tprivate Bitmap mTemp;\r\n\tprivate int mWidth;\r\n\tprivate int mHeight;\r\n\tprivate int mColumns;\r\n\tprivate int mRows;\r\n\r\n\t// Tileset information.\r\n\tprivate SubTexture mSet;\r\n\tprivate int mSetColumns;\r\n\tprivate int mSetRows;\r\n\tprivate int mSetCount;\r\n\tprivate Rect mTile;\r\n\r\n\t// Global objects.\r\n\tprivate Rect mRect = FP.rect;\r\n\tprivate Canvas mCanvas = FP.canvas;\r\n\t\r\n\t/**\r\n\t * Constructor.\r\n\t * @param\ttileset\t\t\tThe source tileset image.\r\n\t * @param\twidth\t\t\tWidth of the tilemap, in pixels.\r\n\t * @param\theight\t\t\tHeight of the tilemap, in pixels.\r\n\t * @param\ttileWidth\t\tTile width.\r\n\t * @param\ttileHeight\t\tTile height.\r\n\t */\r\n\tpublic TileMap(SubTexture tileset, int width, int height, int tileWidth, int tileHeight) {\r\n\t\tsuper(tileset);\r\n\t\t// set some tilemap information\r\n\t\tmWidth = width - (width % tileWidth);\r\n\t\tmHeight = height - (height % tileHeight);\r\n\t\tmColumns = mWidth / tileWidth;\r\n\t\tmRows = mHeight / tileHeight;\r\n\t\tmMap = Bitmap.createBitmap(mColumns, mRows, Config.ARGB_8888);\r\n\t\t//mTemp = mMap.copy(Config.ARGB_8888, true);\r\n\t\tmTile = new Rect(0, 0, tileWidth, tileHeight);\r\n\t\t\r\n\t\t/*\r\n * Initialize triangle list mesh.\r\n *\r\n * [0]------[1] [2]------[3] ...\r\n * | / | | / |\r\n * | / | | / |\r\n * | / | | / |\r\n * [w]-----[w+1] [w+2]----[w+3]...\r\n * | |\r\n *\r\n */\r\n\t\tmVerticiesAcross = mColumns * 2;\r\n\t\tmVerticiesDown = mRows * 2;\r\n\t\tmVerticesCount = mVerticiesAcross * mVerticiesDown;\r\n\t\tmVertexBuffer = getDirectFloatBuffer(mVerticesCount * 2);\r\n\t\tmTextureBuffer = getDirectFloatBuffer(mVerticesCount * 2);\r\n\t\t\r\n\t\tLog.d(TAG, String.format(\"%d vertices\", mVerticesCount));\r\n\t\t\r\n\t\t//mIndexCount = mColumns * mRows * 6;\r\n\t\tmIndexBuffer = getDirectCharBuffer(mColumns * mRows * 6);\r\n\t\t\r\n\t\tsetTileVerticesBuffer();\r\n\t\tmIndexCount = setTileIndexBuffer();\r\n\t\t\r\n\t\t// load the tileset graphic\r\n\t\tmSet = tileset;\r\n\t\tif (mSet == null) {\r\n\t\t\tLog.e(TAG, \"Invalid tileset graphic provided\");\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tmSetColumns = (int)(mSet.getWidth() / tileWidth);\r\n\t\tmSetRows = (int)(mSet.getHeight() / tileHeight);\r\n\t\tmSetCount = mSetColumns * mSetRows;\r\n\t}\r\n\t\r\n\tprivate void setTileVerticesBuffer() {\r\n\t\tfloat f[] = new float[mVerticesCount * 2];\r\n\t\tint i = 0;\r\n\t\tmVertexBuffer.position(0);\r\n\t\t\r\n\t\tfor(int y = 0; y < mRows; y++) {\r\n\t\t\tfor(int x = 0; x < mColumns; x++) {\r\n\t\t\t\t//mVertexBuffer.put(x * mTile.width()).put(y * mTile.height());\r\n\t\t\t\tf[i++] = x * mTile.width();\r\n\t\t\t\tf[i++] = y * mTile.height();\r\n\t\t\t\t//index += 2;\r\n\t\t\t\t//mVertexBuffer.put((x+1) * mTile.width()).put(y * mTile.height());\r\n\t\t\t\tf[i++] = (x+1) * mTile.width();\r\n\t\t\t\tf[i++] = y * mTile.height();\r\n\t\t\t\t//index += 2;\r\n\t\t\t\t//Log.d(TAG, String.format(\"quad top %d,%d value %d,%d - %d,%d\", x, y, \r\n\t\t\t\t//\t\tx * mTile.width(), y * mTile.height(), (x+1) * mTile.width(), y * mTile.height()));\r\n\t\t\t}\r\n\t\t\tfor(int x = 0; x < mColumns; x++) {\r\n\t\t\t\t//mVertexBuffer.put(x * mTile.width()).put((y+1) * mTile.height());\r\n\t\t\t\tf[i++] = x * mTile.width();\r\n\t\t\t\tf[i++] = (y+1) * mTile.height();\r\n\t\t\t\t//index += 2;\r\n\t\t\t\t//mVertexBuffer.put((x+1) * mTile.width()).put((y+1) * mTile.height());\r\n\t\t\t\tf[i++] = (x+1) * mTile.width();\r\n\t\t\t\tf[i++] = (y+1) * mTile.height();\r\n\t\t\t\t//index += 2;\r\n\t\t\t\t//Log.d(TAG, String.format(\"quad bottom %d,%d value %d,%d - %d,%d\", x, y,\r\n\t\t\t\t//\t\tx * mTile.width(), (y+1) * mTile.height(), (x+1) * mTile.width(), (y+1) * mTile.height()));\r\n\t\t\t}\r\n\t\t}\r\n\t\tmVertexBuffer.put(f).position(0);\r\n\t}\r\n\t\r\n\tprivate void setTileTextureBuffer() {\r\n\t\tfloat f[] = new float[mVerticesCount * 2];\r\n\t\tint i = 0;\r\n\t\tRect r = new Rect();\r\n\t\tint texWidth = mSubTexture.getTexture().getWidth();\r\n\t\tint texHeight = mSubTexture.getTexture().getHeight();\r\n\t\t\r\n\t\tmTextureBuffer.position(0);\r\n\t\tfor(int y = 0; y < mRows; y++) {\r\n\t\t\tfor(int x = 0; x < mColumns; x++) {\r\n\t\t\t\tint tile = getTile(x, y);\r\n\t\t\t\tmSubTexture.getFrame(r, tile, mTile.width(), mTile.height());\r\n\t\t\t\t//mTextureBuffer.put((float)r.left/texWidth).put((float)r.top/texHeight);\r\n\t\t\t\tf[i++] = (float)r.left/texWidth;\r\n\t\t\t\tf[i++] = (float)r.top/texHeight;\r\n\t\t\t\t//mTextureBuffer.put((float)(r.left + r.width())/texWidth).put((float)r.top/texHeight);\r\n\t\t\t\tf[i++] = (float)(r.left + r.width())/texWidth;\r\n\t\t\t\tf[i++] = (float)r.top/texHeight;\r\n\t\t\t\t//Log.d(TAG, String.format(\"texture quad top %d,%d value %d,%d - %d,%d\", x, y, \r\n\t\t\t\t//\t\tr.left, r.top, r.left + r.width(), r.top));\r\n\t\t\t}\r\n\t\t\tfor(int x = 0; x < mColumns; x++) {\r\n\t\t\t\tint tile = getTile(x, y);\r\n\t\t\t\tmSubTexture.getFrame(r, tile, mTile.width(), mTile.height());\r\n\t\t\t\t//mTextureBuffer.put((float)r.left/texWidth).put((float)(r.top + r.height())/ texHeight);\r\n\t\t\t\tf[i++] = (float)r.left/texWidth;\r\n\t\t\t\tf[i++] = (float)(r.top + r.height())/ texHeight;\r\n\t\t\t\t//mTextureBuffer.put((float)(r.left + r.width())/texWidth).put((float)(r.top + r.height())/ texHeight);\r\n\t\t\t\tf[i++] = (float)(r.left + r.width())/texWidth;\r\n\t\t\t\tf[i++] = (float)(r.top + r.height())/ texHeight;\r\n\t\t\t\t//Log.d(TAG, String.format(\"texture quad bottom %d,%d value %d,%d - %d,%d\", x, y,\r\n\t\t\t\t//\t\tr.left, r.top + r.height(), r.left + r.width(), r.top + r.height()));\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tmTextureBuffer.put(f).position(0);\r\n\t}\r\n\t\r\n\tprivate int setTileIndexBuffer() {\r\n\t\tchar indices[] = new char[mColumns * mRows * 6];\r\n\t\tmIndexBuffer.position(0);\r\n\t\tint i = 0;\r\n\t\tfor (int y = 0; y < mRows; y++) {\r\n\t\t\tfinal int indexY = y * 2;\r\n\t\t\tfor (int x = 0; x < mColumns; x++) {\r\n\t\t\t\tint tile = getTile(x, y);\r\n\t\t\t\tif (tile == 0x00ffffff) {\r\n\t\t\t\t\t//Log.d(TAG, String.format(\"Skipping (%d, %d)\", x, y));\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t\tfinal int indexX = x * 2;\r\n\t\t\t\tchar a = (char) (indexY * mVerticiesAcross + indexX);\r\n\t\t\t\tchar b = (char) (indexY * mVerticiesAcross + indexX + 1);\r\n\t\t\t\tchar c = (char) ((indexY + 1) * mVerticiesAcross + indexX);\r\n\t\t\t\tchar d = (char) ((indexY + 1) * mVerticiesAcross + indexX + 1);\r\n\t\t\t\t\r\n\t\t\t\t//Log.d(TAG, String.format(\"Quad %d, %d -> tl:%d tr:%d bl:%d br:%d\", x, y, (int)a, (int)b, (int)c, (int)d));\r\n\t\t\t\t\r\n\t\t\t\tindices[i++] = a;\r\n\t\t\t\tindices[i++] = b;\r\n\t\t\t\tindices[i++] = c;\r\n\t\t\t\t//mIndexBuffer.put(a);\r\n\t\t\t\t//mIndexBuffer.put(b);\r\n\t\t\t\t//mIndexBuffer.put(c);\r\n\t\t\t\t\r\n\t\t\t\tindices[i++] = b;\r\n\t\t\t\tindices[i++] = d;\r\n\t\t\t\tindices[i++] = c;\r\n\t\t\t\t//mIndexBuffer.put(b);\r\n\t\t\t\t//mIndexBuffer.put(c);\r\n\t\t\t\t//mIndexBuffer.put(d);\r\n\t\t\t}\r\n\t\t}\r\n\t\tmIndexBuffer.put(indices).position(0);\r\n\t\tLog.d(TAG, String.format(\"Tilemap is %d indicies down from %d\", i, mColumns * mRows * 6));\r\n\t\treturn i;\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic void render(GL10 gl, Point point, Point camera) {\r\n\t\tsuper.render(gl, point, camera);\r\n\t\tif (!getAtlas().isLoaded()) {\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tmPoint.x = (int)(point.x + x - camera.x * scrollX);\r\n\t\tmPoint.y = (int)(point.y + y - camera.y * scrollY);\r\n\t\t\r\n\t\tsetBuffers(gl, mVertexBuffer, mTextureBuffer);\r\n\t\t\r\n\t\tgl.glPushMatrix(); \r\n\t\t{\r\n\t\t\tsetMatrix(gl);\r\n\t\t\t\r\n\t\t\tgl.glDrawElements(GL10.GL_TRIANGLES, mIndexCount, GL10.GL_UNSIGNED_SHORT, mIndexBuffer);\r\n\t\t}\r\n\t\tgl.glPopMatrix();\r\n\r\n\t\t/*\r\n\t\tfor (int y = 0; y < mRows; y++) {\r\n\t\t\tgl.glPushMatrix(); \r\n\t\t\tgl.glTranslatef(mPoint.x, mPoint.y + y * mTile.height(), 0);\r\n\t\t\t\r\n\t\t\tfor (int x = 0; x < mColumns && mPoint.x + x * mTile.width() < FP.screen.getWidth(); x++) {\r\n\t\t\t\tint color = mMap.getPixel(x, y) & 0x00ffffff;\r\n\t\t\t\tif (color != -1) {\r\n\t\t\t\t\t\r\n\t\t\t\t\tsetTextureBuffer(QUAD_FLOAT_BUFFER_2, mSet, color, mTile.width(), mTile.height());\r\n\t\t\t\t\r\n\t\t\t\t\tsetBuffers(gl, mVertexBuffer, QUAD_FLOAT_BUFFER_2);\r\n\t\t\t\t\r\n\t\t\t\t\tgl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);\r\n\t\t\t\t\tgl.glTranslatef(mTile.width(), 0, 0);\r\n\t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tgl.glPopMatrix();\r\n\t\t}\r\n\t\t*/\r\n\t}\r\n\r\n\r\n\tpublic void setTile(int column, int row) {\r\n\t\tsetTile(column, row, 0);\r\n\t}\r\n\t/**\r\n\t * Sets the index of the tile at the position.\r\n\t * @param\tcolumn\t\tTile column.\r\n\t * @param\trow\t\t\tTile row.\r\n\t * @param\tindex\t\tTile index.\r\n\t */\r\n\tpublic void setTile(int column, int row, int index) {\r\n\t\tif (usePositions) {\r\n\t\t\tcolumn /= mTile.width();\r\n\t\t\trow /= mTile.height();\r\n\t\t}\r\n\t\t\r\n\t\tindex %= mSetCount;\r\n\t\tcolumn %= mColumns;\r\n\t\trow %= mRows;\r\n\t\t\r\n\t\tmMap.setPixel(column, row, 0xff << 24 | index);\r\n\t\t//Log.d(TAG, String.format(\"Setting %d %d to %d = %d\", column, row, index, getTile(column, row)));\r\n\t}\r\n\t\r\n\t/**\r\n\t * Clears the tile at the position.\r\n\t * @param\tcolumn\t\tTile column.\r\n\t * @param\trow\t\t\tTile row.\r\n\t */\r\n\tpublic void clearTile(int column, int row) {\r\n\t\tif (usePositions) {\r\n\t\t\tcolumn /= mTile.width();\r\n\t\t\trow /= mTile.height();\r\n\t\t}\r\n\t\tcolumn %= mColumns;\r\n\t\trow %= mRows;\r\n\t\tmMap.setPixel(column, row, -1);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Gets the tile index at the position.\r\n\t * @param\tcolumn\t\tTile column.\r\n\t * @param\trow\t\t\tTile row.\r\n\t * @return\tThe tile index.\r\n\t */\r\n\tpublic int getTile(int column, int row) {\r\n\t\tif (usePositions) {\r\n\t\t\tcolumn /= mTile.width();\r\n\t\t\trow /= mTile.height();\r\n\t\t}\r\n\t\treturn mMap.getPixel(column % mColumns, row % mRows) & 0x00ffffff;\r\n\t}\r\n\t\r\n\t\r\n\tpublic void setRect(int column, int row) {\r\n\t\tsetRect(column, row, 1, 1, 0);\r\n\t}\r\n\t\r\n\tpublic void setRect(int column, int row, int width, int height) {\r\n\t\tsetRect(column, row, width, height, 0);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Sets a rectangular region of tiles to the index.\r\n\t * @param\tcolumn\t\tFirst tile column.\r\n\t * @param\trow\t\t\tFirst tile row.\r\n\t * @param\twidth\t\tWidth in tiles.\r\n\t * @param\theight\t\tHeight in tiles.\r\n\t * @param\tindex\t\tTile index.\r\n\t */\r\n\tpublic void setRect(int column, int row, int width, int height, int index) {\r\n\t\tif (usePositions)\r\n\t\t{\r\n\t\t\tcolumn /= mTile.width();\r\n\t\t\trow /= mTile.height();\r\n\t\t\twidth /= mTile.width();\r\n\t\t\theight /= mTile.height();\r\n\t\t}\r\n\t\tcolumn %= mColumns;\r\n\t\trow %= mRows;\r\n\t\tint c = column;\r\n\t\tint r = column + width;\r\n\t\tint b = row + height;\r\n\t\tboolean u = usePositions;\r\n\t\tusePositions = false;\r\n\t\twhile (row < b) {\r\n\t\t\twhile (column < r) {\r\n\t\t\t\tsetTile(column, row, index);\r\n\t\t\t\tcolumn ++;\r\n\t\t\t}\r\n\t\t\tcolumn = c;\r\n\t\t\trow ++;\r\n\t\t}\r\n\t\tusePositions = u;\r\n\t}\r\n\t\r\n\t\r\n\t/**\r\n\t * Clears the rectangular region of tiles.\r\n\t * @param\tcolumn\t\tFirst tile column.\r\n\t * @param\trow\t\t\tFirst tile row.\r\n\t */\r\n\tpublic void clearRect(int column, int row) {\r\n\t\tclearRect(column, row, 1, 1);\r\n\t}\r\n\t\r\n\t\r\n\t/**\r\n\t * Clears the rectangular region of tiles.\r\n\t * @param\tcolumn\t\tFirst tile column.\r\n\t * @param\trow\t\t\tFirst tile row.\r\n\t * @param\twidth\t\tWidth in tiles.\r\n\t * @param\theight\t\tHeight in tiles.\r\n\t */\r\n\tpublic void clearRect(int column, int row, int width, int height) {\r\n\t\tif (usePositions)\r\n\t\t{\r\n\t\t\tcolumn /= mTile.width();\r\n\t\t\trow /= mTile.height();\r\n\t\t\twidth /= mTile.width();\r\n\t\t\theight /= mTile.height();\r\n\t\t}\r\n\t\tcolumn %= mColumns;\r\n\t\trow %= mRows;\r\n\t\tint c = column;\r\n\t\tint r = column + width;\r\n\t\tint b = row + height;\r\n\t\tboolean u = usePositions;\r\n\t\tusePositions = false;\r\n\t\twhile (row < b) {\r\n\t\t\twhile (column < r) {\r\n\t\t\t\tclearTile(column, row);\r\n\t\t\t\tcolumn ++;\r\n\t\t\t}\r\n\t\t\tcolumn = c;\r\n\t\t\trow ++;\r\n\t\t}\r\n\t\tusePositions = u;\r\n\t}\r\n\t\r\n\t\r\n\t/**\r\n\t* Loads the Tilemap tile index data from a string. Column Seperator is \",\" and Row Seperator is \"\\n\"\r\n\t* @param str\t\t\tThe string data, which is a set of tile values separated by the columnSep and rowSep strings.\r\n\t*/\r\n\tpublic void loadFromString(String str) {\r\n\t\tloadFromString(str, \",\", \"\\n\");\r\n\t}\r\n\t\r\n\t/**\r\n\t* Loads the Tilemap tile index data from a string.\r\n\t* @param str\t\t\tThe string data, which is a set of tile values separated by the columnSep and rowSep strings.\r\n\t* @param columnSep\t\tThe string that separates each tile value on a row, default is \",\".\r\n\t* @param rowSep\t\t\tThe string that separates each row of tiles, default is \"\\n\".\r\n\t*/\r\n\tpublic void loadFromString(String str, String columnSep, String rowSep) {\r\n\t\tString row[] = str.split(rowSep);\r\n\t\tint rows = row.length;\r\n\t\tString col[];\r\n\t\tint cols;\r\n\t\tint x, y;\r\n\t\tint xp;\r\n\t\tfor (y = 0; y < rows; y ++) {\r\n\t\t\txp = 0;\r\n\t\t\tif (\"\".equals(row[y])) \r\n\t\t\t\tcontinue;\r\n\t\t\tcol = row[y].split(columnSep);\r\n\t\t\tcols = col.length;\r\n\t\t\tfor (x = 0; x < cols; x ++)\r\n\t\t\t{\r\n\t\t\t\tif (\"\".equals(col[x])) {\r\n\t\t\t\t\txp--;\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t\tsetTile(x+xp, y, Integer.parseInt(col[x]));\r\n\t\t\t}\r\n\t\t}\r\n\t\tsetTileVerticesBuffer();\r\n\t\tsetTileTextureBuffer();\r\n\t\tmIndexCount = setTileIndexBuffer();\r\n\t}\r\n\t\r\n\t/**\r\n\t* Saves the Tilemap tile index data to a string. columnSep = \",\" rowSep = \"\\n\"\r\n\t*/\r\n\tpublic String saveToString() {\r\n\t\treturn saveToString(\",\", \"\\n\");\r\n\t}\r\n\t\r\n\t/**\r\n\t* Saves the Tilemap tile index data to a string.\r\n\t* @param columnSep\t\tThe string that separates each tile value on a row, default is \",\".\r\n\t* @param rowSep\t\t\tThe string that separates each row of tiles, default is \"\\n\".\r\n\t*/\r\n\tpublic String saveToString(String columnSep, String rowSep) {\r\n\t\tStringBuilder s = new StringBuilder(mRows*mColumns);\r\n\t\tint x, y;\r\n\t\tfor (y = 0; y < mRows; y ++) {\r\n\t\t\tfor (x = 0; x < mColumns; x ++) {\r\n\t\t\t\ts.append(String.valueOf(getTile(x, y)));\r\n\t\t\t\tif (x != mColumns - 1) \r\n\t\t\t\t\ts.append(columnSep);\r\n\t\t\t}\r\n\t\t\tif (y != mRows - 1) \r\n\t\t\t\ts.append(rowSep);\r\n\t\t}\r\n\t\treturn s.toString();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Gets the index of a tile, based on its column and row in the tileset.\r\n\t * @param\ttilesColumn\t\tTileset column.\r\n\t * @param\ttilesRow\t\tTileset row.\r\n\t * @return\tIndex of the tile.\r\n\t */\r\n\tpublic int getIndex(int tilesColumn, int tilesRow) {\r\n\t\treturn (tilesRow % mSetRows) * mSetColumns + (tilesColumn % mSetColumns);\r\n\t}\r\n\t\r\n\t/**\r\n\t * The tile width.\r\n\t */\r\n\tpublic int getTileWidth() { return mTile.width(); }\r\n\r\n\t/**\r\n\t * The tile height.\r\n\t */\r\n\tpublic int getTileHeight() { return mTile.height(); }\r\n\r\n\t/**\r\n\t * How many columns the tilemap has.\r\n\t */\r\n\tpublic int getColumns() { return mColumns; }\r\n\r\n\t/**\r\n\t * How many rows the tilemap has.\r\n\t */\r\n\tpublic int getRows() { return mRows; }\r\n\r\n\t@Override\r\n\tprotected void release() {\r\n\t\tsuper.release();\r\n\t\t\r\n\t\tmMap.recycle();\r\n\t}\r\n\r\n}\r", "public class SubTexture {\r\n\r\n\tprivate final Rect mRect = new Rect();\r\n\tprivate Texture mTexture;\r\n\t\r\n\t/**\r\n\t * Create a subtexture object to describe a texture in a texture.\r\n\t * @param t The base Texture to use.\r\n\t * @param x The start x coord of the subtexture (in pixels).\r\n\t * @param y The start y coord of the subtexture (in pixels).\r\n\t * @param width The width of the subtexture (in pixels).\r\n\t * @param height The height of the subtexture (in pixels).\r\n\t */\r\n\tpublic SubTexture(Texture t, int x, int y, int width, int height) {\r\n\t\tmTexture = t;\r\n\t\tmRect.set(x,y,x+width,y+height);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Gets the texture this subtexture uses.\r\n\t * @return The subtexture.\r\n\t */\r\n\tpublic Texture getTexture() {\r\n\t\treturn mTexture;\r\n\t}\r\n\t\r\n\t/**\r\n\t * The bounds of the whole subtexture. \r\n\t * @return\r\n\t */\r\n\tpublic Rect getBounds() {\r\n\t\treturn mRect;\r\n\t}\r\n\t\r\n\t/**\r\n\t * The width of the subtexture.\r\n\t * @return\r\n\t */\r\n\tpublic int getWidth() {\r\n\t\treturn mRect.width();\r\n\t}\r\n\t\r\n\t/**\r\n\t * The height of the subtexture.\r\n\t * @return\r\n\t */\r\n\tpublic int getHeight() {\r\n\t\treturn mRect.height();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Set a rect to the clip for that frame in the whole texture\r\n\t * @param r the rect to set to the clip of the whole texture.\r\n\t */\r\n\tpublic void getFrame(Rect r, int index, int frameWidth, int frameHeight) {\r\n\t\tint x = index * frameWidth;\r\n\t\tint y = (x / mRect.width()) * frameHeight;\r\n\t\tx %= mRect.width();\r\n\t\tr.set(mRect.left + x, mRect.top + y, mRect.left + x + frameWidth, mRect.top + y + frameHeight);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Set a rec to the clip based on a relative rect.\r\n\t * @param clipRect the rect to set to the clip of the whole texture.\r\n\t * @param relativeClipRect a relative rect of the subtexture.\r\n\t */\r\n\tpublic void GetAbsoluteClipRect(Rect clipRect, Rect relativeClipRect) {\r\n\t\tint width = relativeClipRect.width();\r\n\t\tint height = relativeClipRect.height();\r\n\t\tclipRect.left = relativeClipRect.left + mRect.left;\r\n\t\tclipRect.top = relativeClipRect.top + mRect.top;\r\n\t\tclipRect.right = clipRect.left + width;\r\n\t\tclipRect.bottom = clipRect.top + height;\r\n\t}\r\n}\r", "public class Input {\r\n\r\n\t/**\r\n\t * Map from KeyCode to Action (ACTION_DOWN, ACTION_UP)\r\n\t */\r\n\tpublic static final Map<Integer, Integer> KEY_STATE = new HashMap<Integer, Integer>();\r\n\t\r\n\t/**\r\n\t * If the mouse button is down.\r\n\t */\r\n\tpublic static boolean mouseDown = false;\r\n\r\n\t/**\r\n\t * If the mouse button is up.\r\n\t */\r\n\tpublic static boolean mouseUp = true;\r\n\r\n\t/**\r\n\t * If the mouse button was pressed this frame.\r\n\t */\r\n\tpublic static boolean mousePressed = false;\r\n\r\n\t/**\r\n\t * If the mouse button was released this frame.\r\n\t */\r\n\tpublic static boolean mouseReleased = false;\r\n\t\r\n\t/**\r\n\t * X positions of up to two fingers on the screen.\r\n\t */\r\n\tpublic static int[] getMouseX() {\r\n\t\treturn FP.screen.getTouchX();\r\n\t}\r\n\r\n\t/**\r\n\t * Y position of up to two fingers on the screen.\r\n\t */\r\n\tpublic static int[] getMouseY() {\r\n\t\treturn FP.screen.getTouchY();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Gets the number of pointers on the screen.\r\n\t * @return The number of points\r\n\t */\r\n\tpublic static int getTouchesCount() {\r\n\t\treturn FP.screen.getTouchesCount();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Gets the points of contact with the screen.\r\n\t * @return An array of points use getTouchesCount() to find the size;\r\n\t */\r\n\tpublic static Point[] getTouches() {\r\n\t\treturn FP.screen.getTouches();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Store the state of the inputs.\r\n\t * @param keyCode\r\n\t * @param event\r\n\t */\r\n\tpublic static void onKeyChange(int keyCode, KeyEvent event) {\r\n\t\tswitch(event.getAction()) {\r\n\t\tcase KeyEvent.ACTION_DOWN:\r\n\t\t\tKEY_STATE.put(keyCode, 1);\r\n\t\t\tbreak;\r\n\t\tcase KeyEvent.ACTION_UP:\r\n\t\t\tKEY_STATE.put(keyCode, 0);\r\n\t\t\tbreak;\r\n\t\tcase KeyEvent.ACTION_MULTIPLE:\r\n\t\t\tString keys = event.getCharacters();\r\n\t\t\tfor (int i = 0; i < keys.length(); i++) {\r\n\t\t\t\tKEY_STATE.put((int)keys.charAt(i), 1);\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static boolean checkKey(int keyCode) {\r\n\t\treturn KEY_STATE.containsKey(keyCode) && KEY_STATE.get(keyCode) == 1;\r\n\t}\r\n\t\r\n\t/** @private Called by Engine to update the input. */\r\n\tpublic static void update() {\r\n\t\tif (mousePressed) \r\n\t\t\tmousePressed = false;\r\n\t\tif (mouseReleased) \r\n\t\t\tmouseReleased = false;\r\n\t}\r\n}\r", "public class Main extends Engine {\r\n\r\n\tprivate static final String TAG = \"Game\";\r\n\tpublic static Sfx mBonk;\r\n\tpublic static Sfx mJump;\r\n\tpublic static Sfx mDeath;\r\n\tpublic static Sfx mBGM;\r\n\t\r\n\tpublic static final String DATA_CURRENT_LEVEL = \"current_level\";\r\n\t\r\n\tpublic static final String MUTE_PREF = \"mute\";\r\n\tpublic static Atlas mAtlas;\r\n\t//public static Typeface mTypeface;\r\n\r\n\tpublic Main(int width, int height, float frameRate, boolean fixed) {\r\n\t\tsuper(width, height, frameRate, fixed);\r\n\t\t\r\n\t\tmAtlas = new Atlas(\"textures/texture1.xml\");\r\n\t\t//mTypeface = TextAtlas.getFontFromRes(R.raw.font_fixed_bold);\r\n\t\t//mTypeface = TextAtlas.getFontFromAssets(\"fonts/periodic_three/periodic_three.ttf\");\r\n\t\t// Set typeface default.\r\n\t\tFP.typeface = TextAtlas.getFontFromAssets(\"fonts/periodic_three/periodic_three.ttf\");\r\n\t\t\r\n\t\tFP.setWorld(new MenuWorld());\r\n\t\r\n\t\tLog.d(TAG, \"Loading sounds\");\r\n\t\t\r\n\t\tmBonk = new Sfx(R.raw.bonk);\r\n\t\tmJump = new Sfx(R.raw.jump);\r\n\t\tmDeath = new Sfx(R.raw.death);\r\n\t\tmBGM = new Sfx(R.raw.bgm);\r\n\t\t\r\n\t\tif (FP.debug) {\r\n\t\t\tCommand changeLevel = new Command() {\r\n\t\t\t\t\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic String execute(String... args) {\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tint level = Integer.parseInt(args[0]);\r\n\t\t\t\t\t\tFP.getWorld().active = false;\r\n\t\t\t\t\t\tFP.setWorld(new OgmoEditorWorld(level));\r\n\t\t\t\t\t\treturn \"Changing level to \"+ level + \"\\r\\n\"; \r\n\t\t\t\t\t} catch (Exception e) {\r\n\t\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t\t\treturn \"Bad argument to \\\"level\\\": \" + args[0] + \"\\r\\n\"; \r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t};\r\n\t\t\t\r\n\t\t\tConsole.registerCommand(\"level\", changeLevel);\r\n\t\t}\r\n\t}\r\n\r\n\tpublic static void setMute(boolean mute) {\r\n\t\tData.getData().edit().putBoolean(MUTE_PREF, mute).commit();\r\n\t\tSfx.setMasterVolume(mute ? 0 : 1);\r\n\t}\r\n\t\r\n\tpublic static boolean isMute() {\r\n\t\treturn Data.getData().getBoolean(MUTE_PREF, false);\r\n\t}\r\n\t\r\n\tpublic static Backdrop getLevelBackdrop(int level) {\r\n\t\tBackdrop bd;\r\n\t\tswitch(((level-1)/10)+1) {\r\n\t\tcase 3: \r\n\t\t\tbd = new Backdrop(Main.mAtlas.getSubTexture(\"background_city\"));\r\n\t\t\tbreak;\r\n\t\tcase 2:\r\n\t\t\tbd = new Backdrop(Main.mAtlas.getSubTexture(\"background_desert\"));\r\n\t\t\tbreak;\r\n\t\tcase 1:\r\n\t\t\tbd = new Backdrop(Main.mAtlas.getSubTexture(\"background_forest\"));\r\n\t\t\tbreak;\r\n\t\tdefault:\r\n\t\t\tbd = new Backdrop(Main.mAtlas.getSubTexture(\"background_forest\"));\r\n\t\t}\r\n\t\treturn bd;\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic void init() {\r\n\t\tLog.d(TAG, \"At init!\");\r\n\t}\r\n}\r", "public class OgmoEditorWorld extends World {\r\n\r\n\tprivate static final String TAG = \"OgmoEditorWorld\";\r\n\t\r\n\tpublic static final String TYPE_DANGER = \"danger\";\r\n\tpublic static Ogmo mOgmo = null;\r\n\tpublic static boolean restart = false;\r\n\t\r\n\tprivate static final String LEVEL_FOLDER = \"levels\";\r\n\tprivate int mCurrentLevel = 1;\r\n\tprivate int mNumLevels;\r\n\t\r\n\tprivate Entity mLevel = new Entity();\r\n\t\r\n\tprivate PlayerStart mPlayerStart = null;\r\n\tprivate Exit mExit = null;\r\n\t\r\n\tprivate int mWidth = 0, mHeight = 0;\r\n\t\r\n\tprivate Entity mBackdropEntity;\r\n\t\r\n\tprivate boolean mPlayIntro = false;\r\n\t\r\n\t\r\n\t\r\n\tpublic static abstract class XMLEntityConstructor {\r\n\t\tpublic abstract Entity make(Node n);\r\n\t}\r\n\t\r\n\tprivate static Map<String, XMLEntityConstructor> mXMLEntityConstructors = new TreeMap<String, XMLEntityConstructor>();\r\n\t\r\n\tstatic {\r\n\t\tmXMLEntityConstructors.put(\"Cannon\", new XMLEntityConstructor() {\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic Cannon make(Node n) {\r\n\t\t\t\tNamedNodeMap atts = n.getAttributes();\r\n\t\t\t\tint x = Integer.parseInt(atts.getNamedItem(\"x\").getNodeValue());\r\n\t\t\t\tint y = Integer.parseInt(atts.getNamedItem(\"y\").getNodeValue());\r\n\t\t\t\tint angle = Integer.parseInt(atts.getNamedItem(\"angle\").getNodeValue());\r\n\t\t\t\tfloat interval = 3.0f;\r\n\t\t\t\ttry {\r\n\t\t\t\t\tinterval = Float.parseFloat(atts.getNamedItem(\"interval\").getNodeValue());\r\n\t\t\t\t} catch (NumberFormatException e) {\r\n\t\t\t\t} catch (NullPointerException ex) {}\r\n\t\t\t\t\r\n\t\t\t\tCannon c = new Cannon(x, y, angle, interval);\r\n\t\t\t\treturn c;\r\n\t\t\t}\r\n\t\t});\r\n\t\t\r\n\t\tmXMLEntityConstructors.put(\"Lightning\", new XMLEntityConstructor() {\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic Lightning make(Node n) {\r\n\t\t\t\tNamedNodeMap atts = n.getAttributes();\r\n\t\t\t\tint x = Integer.parseInt(atts.getNamedItem(\"x\").getNodeValue());\r\n\t\t\t\tint y = Integer.parseInt(atts.getNamedItem(\"y\").getNodeValue());\r\n\t\t\t\tint width = Integer.parseInt(atts.getNamedItem(\"width\").getNodeValue());\r\n\t\t\t\tint angle = Integer.parseInt(atts.getNamedItem(\"angle\").getNodeValue());\r\n\t\t\t\t\r\n\t\t\t\tfloat duration = 0, offset = 0;\r\n\t\t\t\t\r\n\t\t\t\ttry {\r\n\t\t\t\t\tduration = Float.parseFloat(atts.getNamedItem(\"duration\").getNodeValue());\r\n\t\t\t\t} catch (NumberFormatException e) {\r\n\t\t\t\t} catch (NullPointerException ex) {}\r\n\t\t\t\t\r\n\t\t\t\ttry {\r\n\t\t\t\t\toffset = Float.parseFloat(atts.getNamedItem(\"offset\").getNodeValue());\r\n\t\t\t\t} catch (NumberFormatException e) {\r\n\t\t\t\t} catch (NullPointerException ex) {}\r\n\t\t\t\t\r\n\t\t\t\tLightning l = new Lightning(x, y, width, 32, angle, duration, offset);\r\n\r\n\t\t\t\treturn l;\r\n\t\t\t}\r\n\t\t});\r\n\t}\r\n\tprivate final OnBackCallback mGameOnBack = new OnBackCallback() {\r\n\t\t\r\n\t\t@Override\r\n\t\tpublic boolean onBack() {\r\n\t\t\tif (FP.engine != null)\r\n\t\t\t\tFP.engine.paused = true;\r\n\t\t\tAlertDialog.Builder builder = new AlertDialog.Builder(FP.context);\r\n\t\t\t\r\n\t\t\tbuilder.setTitle(R.string.return_to_menu_title);\r\n\t\t\tbuilder.setMessage(R.string.return_to_menu_message);\r\n\t\t\t\r\n\t\t\tOnClickListener ocl = new OnClickListener() {\r\n\t\t\t\t\r\n\t\t\t\tpublic void onClick(DialogInterface dialog, int which) {\r\n\t\t\t\t\tif (which == DialogInterface.BUTTON_POSITIVE) {\r\n\t\t\t\t\t\tFP.setWorld(new MenuWorld());\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (FP.engine != null)\r\n\t\t\t\t\t\tFP.engine.paused = false;\r\n\t\t\t\t}\r\n\t\t\t};\r\n\t\t\tbuilder.setPositiveButton(R.string.yes, ocl);\r\n\t\t\tbuilder.setNegativeButton(R.string.no, ocl);\r\n\t\t\tbuilder.create().show();\r\n\t\t\treturn true;\r\n\t\t}\r\n\t};\r\n\t\r\n\tpublic OgmoEditorWorld(int level) {\r\n\t\tthis(level, true);\r\n\t}\r\n\t\r\n\tpublic OgmoEditorWorld(int level, boolean playIntro) {\r\n\t\tmCurrentLevel = level;\r\n\t\tswitch(level) {\r\n\t\tcase 1:\r\n\t\tcase 11:\r\n\t\tcase 21:\r\n\t\t\tmPlayIntro = playIntro;\r\n\t\t\tbreak;\r\n\t\tcase 31:\r\n\t\t\tLog.d(TAG, \"Done game. Play Final Thing and return to the menu.\");\r\n\t\t\tmPlayIntro = playIntro;\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tFP.activity.setOnBackCallback(mGameOnBack);\r\n\t\t\r\n\t\t\r\n\t\tString levels[] = FP.getAssetList(LEVEL_FOLDER);\r\n\t\tmNumLevels = levels.length;\r\n\t\tString theLevel = String.format(\"%d_\", level);\r\n\t\t//Log.d(TAG, String.format(\"%d levels looking for level %s\", mNumLevels, theLevel));\r\n\t\tfor (String l : levels) {\r\n\t\t\tLog.d(TAG, l);\r\n\t\t\tif (l.startsWith(theLevel)) {\r\n\t\t\t\tparseOgmoEditorLevel(LEVEL_FOLDER + File.separator + l);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tmBackdropEntity = new Entity();\r\n\t\tBackdrop bd = Main.getLevelBackdrop(mCurrentLevel);\r\n\t\t\r\n\t\tBackdrop clouds = new Backdrop(Main.mAtlas.getSubTexture(\"jumper_clouds\"), true, false);\r\n\t\tbd.scale = 2.0f;\r\n\t\tbd.scrollX = 0.55f;\r\n\t\tbd.scrollY = 0.55f;\r\n\t\tbd.setColor(0xff808080);\r\n\t\tclouds.x = -FP.rand(800);\r\n\t\tclouds.scrollX = 0.75f;\r\n\t\tclouds.setColor(0xffb0b0b0);\r\n\t\tclouds.y = FP.screen.getHeight()/3 + (FP.rand(FP.screen.getHeight()/4)-FP.screen.getHeight()/8);\r\n\t\tmBackdropEntity.setGraphic(new GraphicList(bd, clouds));\r\n\t\tmBackdropEntity.setLayer(200);\r\n\t\tadd(mBackdropEntity);\r\n\t\t\r\n\t\t/*\r\n\t\t// Setup the \"HUD\"\r\n\t\tint jumpLine = FP.height/4;\r\n\t\t\r\n\t\t\r\n\t\tShape leftBlocker = Shape.rect(0, 0, 40, FP.height);\r\n\t\tleftBlocker.setColor(0xff330000);\r\n\t\t\r\n\t\tAtlasText leftJumpText = new AtlasText(\"JUMP\", 16, Main.mTypeface); \r\n\t\tleftJumpText.angle = 270;\r\n\t\tleftJumpText.x = 0;\r\n\t\tleftJumpText.y = FP.halfHeight/2 - leftJumpText.getWidth()/2;\r\n\t\t\r\n\t\tShape leftJumpLine = Shape.line(0, jumpLine, 40, jumpLine, 3);\r\n\t\tleftJumpLine.setColor(0xffff3333);\r\n\t\t\r\n\t\tShape rightBlocker = Shape.rect(FP.width-40, 0, 40, FP.height);\r\n\t\trightBlocker.setColor(0xff330000);\r\n\t\t\r\n\t\tAtlasText rightJumpText = new AtlasText(\"JUMP\", 16, Main.mTypeface); \r\n\t\trightJumpText.angle = 90;\r\n\t\trightJumpText.x = FP.width;\r\n\t\trightJumpText.y = FP.halfHeight/2 - 3*rightJumpText.getWidth()/2;\r\n\t\t\r\n\t\tShape rightJumpLine = Shape.line(FP.width-40, jumpLine, FP.width, jumpLine, 3);\r\n\t\trightJumpLine.setColor(0xffff3333);\r\n\t\t\r\n\t\tblocker.setGraphic(new GraphicList(leftBlocker, rightBlocker, leftJumpText, rightJumpText, leftJumpLine, rightJumpLine));\r\n\t\tblocker.setLayer(-1);\r\n\t\tadd(blocker);\r\n\t\t*/\r\n\t}\r\n\t\r\n\t\r\n\t@Override\r\n\tpublic void begin() {\r\n\t\tmOgmo = null;\r\n\t\trestart = false;\r\n\t\tif (mPlayIntro) {\r\n\t\t\tswitch(mCurrentLevel) {\r\n\t\t\tcase 1:\r\n\t\t\t\tLog.d(TAG, \"Story 1 coming up\");\r\n\t\t\t\tFP.setWorld(new StoryWorld(R.string.story_begining, new OgmoEditorWorld(mCurrentLevel, false)));\r\n\t\t\t\tbreak;\r\n\t\t\tcase 11:\r\n\t\t\t\tLog.d(TAG, \"Story 2 coming up\");\r\n\t\t\t\tFP.setWorld(new StoryWorld(R.string.story_act1, new OgmoEditorWorld(mCurrentLevel, false)));\r\n\t\t\t\tbreak;\r\n\t\t\tcase 21:\r\n\t\t\t\tLog.d(TAG, \"Story 3 coming up\");\r\n\t\t\t\tFP.setWorld(new StoryWorld(R.string.story_act2, new OgmoEditorWorld(mCurrentLevel, false)));\r\n\t\t\t\tbreak;\r\n\t\t\tcase 31:\r\n\t\t\t\tLog.d(TAG, \"Story 4 coming up\");\r\n\t\t\t\tFP.setWorld(new StoryWorld(R.string.story_final, new MenuWorld()));\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t\tmPlayIntro = false;\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void parseOgmoEditorLevel(String assetFilename) {\r\n\t\tDocument doc = FP.getXML(assetFilename);\r\n\t\tparseOgmoEditorLevel(doc);\r\n\t}\r\n\t\r\n\tprivate void parseOgmoEditorLevel(int resId) {\r\n\t\tDocument doc = FP.getXML(resId);\r\n\t\tparseOgmoEditorLevel(doc);\r\n\t}\r\n\t\r\n\tprivate void parseOgmoEditorLevel(Document doc) {\r\n\t\tif (doc == null) {\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tNamedNodeMap levelatts = doc.getFirstChild().getAttributes();\r\n\t\tmWidth = Integer.parseInt(levelatts.getNamedItem(\"width\").getNodeValue());\r\n\t\tmHeight = Integer.parseInt(levelatts.getNamedItem(\"height\").getNodeValue());\r\n\t\tLog.d(TAG, String.format(\"Level is %dx%d\",mWidth,mHeight));\r\n\t\tmLevel.setHitbox(mWidth, mHeight);\r\n\t\t\r\n\t\tNodeList cameras = doc.getElementsByTagName(\"camera\");\r\n\t\tif (cameras.getLength() > 0) {\r\n\t\t\tNode cameraElement = cameras.item(0);\r\n\t\t\tNamedNodeMap catts = cameraElement.getAttributes();\r\n\t\t\tint x = Integer.parseInt(catts.getNamedItem(\"x\").getNodeValue());\r\n\t\t\tint y = Integer.parseInt(catts.getNamedItem(\"y\").getNodeValue());\r\n\t\t\tLog.d(TAG, String.format(\"camera at %d,%d\",x,y) );\r\n\r\n\t\t\tcamera.set(x, y); \r\n\t\t} else {\r\n\t\t\tcamera.set(0, 0);\r\n\t\t}\r\n\t\t\r\n\t\tNodeList tiles = doc.getElementsByTagName(\"Tiles\");\r\n\t\tfor (int i = 0; i < tiles.getLength(); i++) {\r\n\t\t\tNode n = tiles.item(i);\r\n\t\t\tString tileset = n.getAttributes().getNamedItem(\"tileset\").getNodeValue();\r\n\t\t\t\r\n\t\t\tint resWidth, resHeight;\r\n\t\t\tSubTexture st;\r\n\t\t\t\r\n\t\t\tif (\"grass\".equals(tileset)) {\r\n\t\t\t\tst = Main.mAtlas.getSubTexture(\"grass\");\r\n\t\t\t\tresWidth = st.getWidth()/6;\r\n\t\t\t\tresHeight = st.getHeight()/3;\r\n\t\t\t} else if (\"desert\".equals(tileset)) {\r\n\t\t\t\tst = Main.mAtlas.getSubTexture(\"desert\");\r\n\t\t\t\tresWidth = st.getWidth()/6;\r\n\t\t\t\tresHeight = st.getHeight()/3;\r\n\t\t\t} else if (\"city\".equals(tileset)) {\r\n\t\t\t\tst = Main.mAtlas.getSubTexture(\"city\");\r\n\t\t\t\tresWidth = st.getWidth()/6;\r\n\t\t\t\tresHeight = st.getHeight()/3;\r\n\t\t\t/*\t\r\n\t\t\t} else if (\"grass_box_tiles\".equals(tileset)) {\r\n\t\t\t\tbm = FP.getBitmap(R.drawable.grass_box_tiles);\r\n\t\t\t\tresWidth = bm.getWidth()/3;\r\n\t\t\t\tresHeight = bm.getHeight()/3;\r\n\t\t\t*/\r\n\t\t\t} else {\r\n\t\t\t\tst = Main.mAtlas.getSubTexture(\"grey_cement\");\r\n\t\t\t\tresWidth = st.getWidth();\r\n\t\t\t\tresHeight = st.getHeight();\r\n\t\t\t}\r\n\t\t\tNode child = n.getFirstChild();\r\n\t\t\tif (child.getNodeType() == Document.TEXT_NODE) {\r\n\t\t\t\tString tilescsv = child.getTextContent();\r\n\t\t\t\tTileMap tileMap = new TileMap(st, mWidth, mHeight, resWidth, resHeight);\r\n\t\t\t\ttileMap.loadFromString(tilescsv);\r\n\t\t\t\tmLevel.setGraphic(tileMap);\r\n\t\t\t}\r\n\t\t}\r\n\t\tNodeList grid = doc.getElementsByTagName(\"Grid\");\r\n\t\tfor (int i = 0; i < grid.getLength(); i++) {\r\n\t\t\tNode n = grid.item(i);\r\n\t\t\tNode child = n.getFirstChild();\r\n\t\t\tif (child.getNodeType() == Document.TEXT_NODE) {\r\n\t\t\t\tString gridBitString = child.getTextContent();\r\n\t\t\t\tGrid g = new Grid(mWidth, mHeight, 32, 32);\r\n\t\t\t\tmLevel.setType(\"level\");\r\n\t\t\t\tg.loadFromString(gridBitString, \"\", \"\\n\");\r\n\t\t\t\tmLevel.setMask(g);\r\n\t\t\t}\r\n\t\t}\r\n\t\tadd(mLevel);\r\n\t\t\r\n\t\tNodeList objectsList = doc.getElementsByTagName(\"Objects\");\r\n\t\tif (objectsList.getLength() > 0) {\r\n\t\t\tNodeList objects = objectsList.item(0).getChildNodes();\r\n\t\t\tfor (int i = 0; i < objects.getLength(); i++) {\r\n\t\t\t\tNode n = objects.item(i);\r\n\t\t\t\t//Log.d(TAG, String.format(\"tag '%s' in Objects\", n.getNodeName()));\r\n\t\t\t\t\r\n\t\t\t\tif (mXMLEntityConstructors.containsKey(n.getNodeName())) {\r\n\t\t\t\t\tadd(mXMLEntityConstructors.get(n.getNodeName()).make(n));\r\n\t\t\t\t} else if (\"PlayerStart\".equals(n.getNodeName())) {\r\n\t\t\t\t\tNamedNodeMap atts = n.getAttributes();\r\n\t\t\t\t\tint x = Integer.parseInt(atts.getNamedItem(\"x\").getNodeValue());\r\n\t\t\t\t\tint y = Integer.parseInt(atts.getNamedItem(\"y\").getNodeValue());\r\n\t\t\t\t\tLog.d(TAG, String.format(\"New playerstart at %d,%d\",x,y) );\r\n\t\t\t\t\tmPlayerStart = new PlayerStart(x, y);\r\n\t\t\t\t\tadd(mPlayerStart);\r\n\t\t\t\t} else if (\"Exit\".equals(n.getNodeName())) {\r\n\t\t\t\t\tNamedNodeMap atts = n.getAttributes();\r\n\t\t\t\t\tint x = Integer.parseInt(atts.getNamedItem(\"x\").getNodeValue());\r\n\t\t\t\t\tint y = Integer.parseInt(atts.getNamedItem(\"y\").getNodeValue());\r\n\t\t\t\t\tLog.d(TAG, String.format(\"New exit at %d,%d\",x,y) );\r\n\t\t\t\t\tmExit = new Exit(x, y);\r\n\t\t\t\t\tadd(mExit);\r\n\t\t\t\t} else if (\"Text\".equals(n.getNodeName())) {\r\n\t\t\t\t\tNamedNodeMap atts = n.getAttributes();\r\n\t\t\t\t\tint x = Integer.parseInt(atts.getNamedItem(\"x\").getNodeValue());\r\n\t\t\t\t\tint y = Integer.parseInt(atts.getNamedItem(\"y\").getNodeValue());\r\n\t\t\t\t\tString text = atts.getNamedItem(\"text\").getNodeValue();\r\n\t\t\t\t\t\r\n\t\t\t\t\tLog.d(TAG, String.format(\"New text %s at %d, %d\", text, x, y));\r\n\t\t\t\t\t\r\n\t\t\t\t\tEntity e = new Entity(x, y);\r\n\t\t\t\t\te.setLayer(-1);\r\n\t\t\t\t\tAtlasText t = new AtlasText(text, 30);\r\n\t\t\t\t\t\r\n\t\t\t\t\te.setGraphic(t);\r\n\t\t\t\t\tadd(e);\r\n\t\t\t\t} else if (\"TreeSpikes\".equals(n.getNodeName())) {\r\n\t\t\t\t\tNamedNodeMap atts = n.getAttributes();\r\n\t\t\t\t\tint x = Integer.parseInt(atts.getNamedItem(\"x\").getNodeValue());\r\n\t\t\t\t\tint y = Integer.parseInt(atts.getNamedItem(\"y\").getNodeValue());\r\n\t\t\t\t\tint width = Integer.parseInt(atts.getNamedItem(\"width\").getNodeValue());\r\n\t\t\t\t\tint height = Integer.parseInt(atts.getNamedItem(\"height\").getNodeValue());\r\n\t\t\t\t\tint angle = Integer.parseInt(atts.getNamedItem(\"angle\").getNodeValue());\r\n\t\t\t\t\t\r\n\t\t\t\t\tTreeSpikes t = new TreeSpikes(x, y, width, height, angle);\r\n\t\t\t\t\t\r\n\t\t\t\t\tadd(t);\r\n\t\t\t\t} else if (\"AcidPit\".equals(n.getNodeName())) {\r\n\t\t\t\t\tNamedNodeMap atts = n.getAttributes();\r\n\t\t\t\t\tint x = Integer.parseInt(atts.getNamedItem(\"x\").getNodeValue());\r\n\t\t\t\t\tint y = Integer.parseInt(atts.getNamedItem(\"y\").getNodeValue());\r\n\t\t\t\t\tint width = Integer.parseInt(atts.getNamedItem(\"width\").getNodeValue());\r\n\t\t\t\t\t\r\n\t\t\t\t\tAcidPit p = new AcidPit(x, y, width);\r\n\t\t\t\t\t\r\n\t\t\t\t\tadd(p);\r\n\t\t\t\t} else if (\"Volcano\".equals(n.getNodeName())) {\r\n\t\t\t\t\tNamedNodeMap atts = n.getAttributes();\r\n\t\t\t\t\tint x = Integer.parseInt(atts.getNamedItem(\"x\").getNodeValue());\r\n\t\t\t\t\tint y = Integer.parseInt(atts.getNamedItem(\"y\").getNodeValue());\r\n\t\t\t\t\tint angle = Integer.parseInt(atts.getNamedItem(\"angle\").getNodeValue());\r\n\t\t\t\t\t\r\n\t\t\t\t\tVolcano v = new Volcano(x, y, angle);\r\n\t\t\t\t\t\r\n\t\t\t\t\tadd(v);\r\n\t\t\t\t} else if (\"Enemy\".equals(n.getNodeName())) {\r\n\t\t\t\t\tNamedNodeMap atts = n.getAttributes();\r\n\t\t\t\t\tint x = Integer.parseInt(atts.getNamedItem(\"x\").getNodeValue());\r\n\t\t\t\t\tint y = Integer.parseInt(atts.getNamedItem(\"y\").getNodeValue());\r\n\t\t\t\t\tfloat speed = 100.0f;\r\n\t\t\t\t\ttry { \r\n\t\t\t\t\t\tspeed = (float)Integer.parseInt(atts.getNamedItem(\"speed\").getNodeValue());\r\n\t\t\t\t\t} catch (Exception e) {}\r\n\t\t\t\t\tLog.d(TAG, String.format(\"New enemy at %d,%d\",x,y) );\r\n\t\t\t\t\t\r\n\t\t\t\t\tMonster m = new Monster(x, y);\r\n\t\t\t\t\tm.setSpeed(speed);\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\tNodeList enemyPoints = n.getChildNodes();\r\n\t\t\t\t\tfor (int j = 0; j < enemyPoints.getLength(); j++) {\r\n\t\t\t\t\t\tNode node = enemyPoints.item(j);\r\n\t\t\t\t\t\tif (\"node\".equals(node.getNodeName())) {\r\n\t\t\t\t\t\t\tNamedNodeMap natts = node.getAttributes();\r\n\t\t\t\t\t\t\tint nx = Integer.parseInt(natts.getNamedItem(\"x\").getNodeValue());\r\n\t\t\t\t\t\t\tint ny = Integer.parseInt(natts.getNamedItem(\"y\").getNodeValue());\r\n\t\t\t\t\t\t\tm.addPoint(nx, ny);\r\n\t\t\t\t\t\t\tLog.d(TAG, String.format(\"Path to %d %d\", nx, ny));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (enemyPoints.getLength() > 0) {\r\n\t\t\t\t\t\tm.start();\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t\tadd(m);\r\n\t\t\t\t} else if (\"Bird\".equals(n.getNodeName())) {\r\n\t\t\t\t\tNamedNodeMap atts = n.getAttributes();\r\n\t\t\t\t\tint x = Integer.parseInt(atts.getNamedItem(\"x\").getNodeValue());\r\n\t\t\t\t\tint y = Integer.parseInt(atts.getNamedItem(\"y\").getNodeValue());\r\n\t\t\t\t\tLog.d(TAG, String.format(\"New bird at %d,%d\",x,y) );\r\n\t\t\t\t\t\r\n\t\t\t\t\tBird b = new Bird(x, y);\r\n\t\t\t\t\t\r\n\t\t\t\t\tNodeList enemyPoints = n.getChildNodes();\r\n\t\t\t\t\tfor (int j = 0; j < enemyPoints.getLength(); j++) {\r\n\t\t\t\t\t\tNode node = enemyPoints.item(j);\r\n\t\t\t\t\t\tif (\"node\".equals(node.getNodeName())) {\r\n\t\t\t\t\t\t\tNamedNodeMap natts = node.getAttributes();\r\n\t\t\t\t\t\t\tint nx = Integer.parseInt(natts.getNamedItem(\"x\").getNodeValue());\r\n\t\t\t\t\t\t\tint ny = Integer.parseInt(natts.getNamedItem(\"y\").getNodeValue());\r\n\t\t\t\t\t\t\tb.addPoint(nx, ny);\r\n\t\t\t\t\t\t\tLog.d(TAG, String.format(\"Path to %d %d\", nx, ny));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (enemyPoints.getLength() > 0) {\r\n\t\t\t\t\t\tb.addPoint(x, y);\r\n\t\t\t\t\t\tb.start();\r\n\t\t\t\t\t}\r\n\t\t\t\t\tadd(b);\r\n\t\t\t\t}\r\n\t\t\t\t else if (\"Platform\".equals(n.getNodeName())) {\r\n\t\t\t\t\t\tNamedNodeMap atts = n.getAttributes();\r\n\t\t\t\t\t\tint x = Integer.parseInt(atts.getNamedItem(\"x\").getNodeValue());\r\n\t\t\t\t\t\tint y = Integer.parseInt(atts.getNamedItem(\"y\").getNodeValue());\r\n\t\t\t\t\t\tint width = Integer.parseInt(atts.getNamedItem(\"width\").getNodeValue());\r\n\t\t\t\t\t\tLog.d(TAG, String.format(\"New platform at %d,%d\",x,y) );\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tPlatform p = new Platform(x, y, width);\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tNodeList enemyPoints = n.getChildNodes();\r\n\t\t\t\t\t\tfor (int j = 0; j < enemyPoints.getLength(); j++) {\r\n\t\t\t\t\t\t\tNode node = enemyPoints.item(j);\r\n\t\t\t\t\t\t\tif (\"node\".equals(node.getNodeName())) {\r\n\t\t\t\t\t\t\t\tNamedNodeMap natts = node.getAttributes();\r\n\t\t\t\t\t\t\t\tint nx = Integer.parseInt(natts.getNamedItem(\"x\").getNodeValue());\r\n\t\t\t\t\t\t\t\tint ny = Integer.parseInt(natts.getNamedItem(\"y\").getNodeValue());\r\n\t\t\t\t\t\t\t\tp.addPoint(nx, ny);\r\n\t\t\t\t\t\t\t\tLog.d(TAG, String.format(\"Path to %d %d\", nx, ny));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tif (enemyPoints.getLength() > 0) {\r\n\t\t\t\t\t\t\tp.addPoint(x, y);\r\n\t\t\t\t\t\t\tp.start();\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tadd(p);\r\n\t\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic int getWidth() {\r\n\t\treturn mWidth;\r\n\t}\r\n\t\r\n\tpublic int getHeight() {\r\n\t\treturn mHeight;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void update() {\r\n\t\tsuper.update();\r\n\t\t\r\n\t\tif (mOgmo != null) {\r\n\t\t\tif (mOgmo.collideWith(mExit, mOgmo.x, mOgmo.y) != null) {\r\n\t\t\t\tLog.d(TAG, \"Level Compelete\");\r\n\t\t\t\tif (mCurrentLevel + 1 > mNumLevels) {\r\n\t\t\t\t\tData.getData().edit().remove(Main.DATA_CURRENT_LEVEL).commit();\r\n\t\t\t\t\tFP.setWorld(new OgmoEditorWorld(mCurrentLevel + 1));\r\n\t\t\t\t\t//FP.setWorld(new MenuWorld());\r\n\t\t\t\t\t//Main.mBGM.stopLooping();\r\n\t\t\t\t\t//Main.mBGM.setVolume(0);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tFP.setWorld(new OgmoEditorWorld(mCurrentLevel + 1));\r\n\t\t\t\t\tData.getData().edit().putInt(Main.DATA_CURRENT_LEVEL, mCurrentLevel + 1).commit();\r\n\t\t\t\t}\r\n\t\t\t\treturn;\r\n\t\t\t\t//remove(mOgmo);\r\n\t\t\t\t//mOgmo = null;\r\n\t\t\t}\r\n\t\t\r\n\t\t\t\r\n\t\t\tint width = FP.screen.getWidth();\r\n\t\t\tint height = FP.screen.getHeight();\r\n\t\t\t// move the camera if you can.\r\n\t\t\tif (mOgmo.x > camera.x + 2 * width / 3 ) {\r\n\t\t\t\tint newLeft = mOgmo.x - 2 * width / 3 ;\r\n\t\t\t\tcamera.x = Math.min(mLevel.width - width, newLeft);\r\n\t\t\t} else if (mOgmo.x < camera.x + 1 * width / 3) {\r\n\t\t\t\tint newLeft = mOgmo.x - 1 * width/3;\r\n\t\t\t\tcamera.x = Math.max(0, newLeft);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif (mOgmo.y > camera.y + 2 * height / 3) {\r\n\t\t\t\tint newTop = mOgmo.y - 2 * height / 3;\r\n\t\t\t\tcamera.y = Math.min(mLevel.height - height, newTop);\r\n\t\t\t} else if (mOgmo.y < camera.y + 1 * height/3) {\r\n\t\t\t\tint newTop = mOgmo.y - 1 * height / 3;\r\n\t\t\t\tcamera.y = Math.max(0, newTop);\r\n\t\t\t}\r\n\t\t\tif (mOgmo.y > mLevel.height) {\r\n\t\t\t\tmOgmo.setDead();\r\n\t\t\t} else if (mOgmo.collide(TYPE_DANGER, mOgmo.x, mOgmo.y) != null) {\r\n\t\t\t\tmOgmo.setDead();\r\n\t\t\t}\r\n\r\n\t\t\tif (restart) {\r\n\t\t\t\trestart = false;\r\n\t\t\t\tmOgmo = null;\r\n\t\t\t\tFP.setWorld(new OgmoEditorWorld(mCurrentLevel, false));\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n}\r" ]
import java.util.Vector; import net.androidpunk.Entity; import net.androidpunk.FP; import net.androidpunk.graphics.atlas.SpriteMap; import net.androidpunk.graphics.atlas.TileMap; import net.androidpunk.graphics.opengl.SubTexture; import net.androidpunk.utils.Input; import android.graphics.Point; import android.graphics.PointF; import android.view.KeyEvent; import com.gamblore.androidpunk.Main; import com.gamblore.androidpunk.OgmoEditorWorld;
package com.gamblore.androidpunk.entities; public class Ogmo extends Entity { private static final String TAG = "Ogmo"; public static final String TYPE_PLAYER = "player"; private static final int X_SPEED = 200; private static final int MAX_FALL_SPEED = 200; private static final int JUMP_SPEED = -500; private boolean mMoveLeft = false; private boolean mMoveRight = false; private boolean mMoveJump = false; //private static final String ANIM_STANDING = "standing"; public static final String ANIM_WALKING = "walking"; private PointF mVelocity = new PointF(); private SpriteMap mMap; private boolean mDead = false; private boolean mCanJump = false; private static final Vector<String> CollidableTypes = new Vector<String>(); public Ogmo(int x, int y) { super(x, y); SubTexture ogmo = Main.mAtlas.getSubTexture("ogmo"); mMap = new SpriteMap(ogmo, (int) ogmo.getWidth()/6, (int) ogmo.getHeight()); //mMap.add(ANIM_STANDING, new int[] {0}, 0); mMap.add(ANIM_WALKING, FP.frames(0, 5), 20); mMap.setFrame(0); //mMap.play(ANIM_STANDING); setGraphic(mMap); //setGraphic(new Image(FP.getBitmap(R.drawable.ogmo), new Rect(45,0,90,45))); setHitbox((int) ogmo.getWidth()/6, (int) ogmo.getHeight()); setType(TYPE_PLAYER); CollidableTypes.clear(); CollidableTypes.add("level"); } private void updateMoveBooleans() { mMoveJump = mMoveLeft = mMoveRight = false; if (Input.mouseDown) { Point points[] = Input.getTouches(); if (points[0].y < FP.height/4) { mMoveJump = true; return; } if (Input.getTouchesCount() > 1 || Input.checkKey(KeyEvent.KEYCODE_SPACE)) { mMoveJump = true; } if (points[0].x > FP.screen.getWidth()/2) { mMoveRight = true; } else { mMoveLeft = true; } } } @Override public void update() { updateMoveBooleans(); float deltax = 0, deltay = 0; mVelocity.y = mVelocity.y > MAX_FALL_SPEED ? MAX_FALL_SPEED : mVelocity.y + (1000 * FP.elapsed); if (mMoveJump && mCanJump) { Main.mJump.play(); y -= 1; // break locks to moving platforms. mVelocity.y = JUMP_SPEED; mCanJump = false; } if (mMoveLeft) { mVelocity.x = -X_SPEED; } if (mMoveRight) { mVelocity.x = X_SPEED; } mCanJump = false; deltax = (int)(mVelocity.x * FP.elapsed); deltay = (int)(mVelocity.y * FP.elapsed); float previousXVelocity = mVelocity.x; // Check for moving platforms Entity e; Entity platformVertical = collide(Platform.TYPE, x, (int) (y + deltay)); if ((e = collide(Platform.TYPE, (int) (x + deltax), y)) != null && platformVertical == null) { if (previousXVelocity < 0) { x = e.x + e.width + 1; } else { x = e.x - width - 1; } if (!Main.mBonk.getPlaying()) Main.mBonk.loop(1); } else if ((e = collideTypes(CollidableTypes, (int) (x + deltax), y)) != null) { if (mVelocity.y > 0) { mVelocity.y *= 0.90; }
int width = ((TileMap)e.getGraphic()).getTileWidth();
3
crukci-bioinformatics/MGA
src/main/java/org/cruk/mga/report/SummaryPlotter.java
[ "public static final int DEFAULT_PLOT_WIDTH = 800;", "public class AlignmentSummary implements Serializable\n{\n private static final long serialVersionUID = 1121576146340427575L;\n\n private String referenceGenomeId;\n private int alignedCount = 0;\n private int totalAlignedSequenceLength = 0;\n private int totalMismatchCount = 0;\n private int uniquelyAlignedCount = 0;\n private int totalUniquelyAlignedSequenceLength = 0;\n private int totalUniquelyAlignedMismatchCount = 0;\n private int preferentiallyAlignedCount = 0;\n private int totalPreferentiallyAlignedSequenceLength = 0;\n private int totalPreferentiallyAlignedMismatchCount = 0;\n private int assignedCount = 0;\n private int totalAssignedSequenceLength = 0;\n private int totalAssignedMismatchCount = 0;\n\n /**\n * @return the referenceGenomeId\n */\n public String getReferenceGenomeId()\n {\n return referenceGenomeId;\n }\n\n /**\n * @param referenceGenomeId the referenceGenomeId to set\n */\n public void setReferenceGenomeId(String referenceGenomeId)\n {\n this.referenceGenomeId = referenceGenomeId;\n }\n\n /**\n * @return the alignedCount the number of aligned sequences.\n */\n public int getAlignedCount()\n {\n return alignedCount;\n }\n\n /**\n * Increments the aligned sequence count.\n */\n public void incrementAlignedCount()\n {\n alignedCount++;\n }\n\n /**\n * @return the total aligned sequence length.\n */\n public int getTotalAlignedSequenceLength()\n {\n return totalAlignedSequenceLength;\n }\n\n /**\n * Adds the given aligned sequence length to the total.\n *\n * @param alignedSequenceLength the aligned sequence length.\n */\n public void addAlignedSequenceLength(int alignedSequenceLength)\n {\n totalAlignedSequenceLength += alignedSequenceLength;\n }\n\n /**\n * @return the total number of mismatches in aligned sequences.\n */\n public int getTotalMismatchCount()\n {\n return totalMismatchCount;\n }\n\n /**\n * Adds the given number of mismatches to the total.\n *\n * @param mismatchCount the number of mismatches.\n */\n public void addMismatchCount(int mismatchCount)\n {\n totalMismatchCount += mismatchCount;\n }\n\n /**\n * @return the error rate\n */\n public float getErrorRate()\n {\n return totalAlignedSequenceLength == 0 ? 0.0f : (float)totalMismatchCount / totalAlignedSequenceLength;\n }\n\n /**\n * @return the uniquely aligned sequence count.\n */\n public int getUniquelyAlignedCount()\n {\n return uniquelyAlignedCount;\n }\n\n /**\n * Increments the number of uniquely aligned sequences.\n */\n public void incrementUniquelyAlignedCount()\n {\n uniquelyAlignedCount++;\n }\n\n /**\n * @return the total uniquely aligned sequence length.\n */\n public int getTotalUniquelyAlignedSequenceLength()\n {\n return totalUniquelyAlignedSequenceLength;\n }\n\n /**\n * Adds the given uniquely aligned sequence length to the total.\n *\n * @param alignedLength the aligned sequence length.\n */\n public void addUniquelyAlignedSequenceLength(int alignedLength)\n {\n totalUniquelyAlignedSequenceLength += alignedLength;\n }\n\n /**\n * @return the total number of mismatches in uniquely aligned sequences.\n */\n public int getTotalUniquelyAlignedMismatchCount()\n {\n return totalUniquelyAlignedMismatchCount;\n }\n\n /**\n * Adds the given number of mismatches to the total for uniquely aligned sequences.\n *\n * @param mismatchCount the number of mismatches.\n */\n public void addUniquelyAlignedMismatchCount(int mismatchCount)\n {\n totalUniquelyAlignedMismatchCount += mismatchCount;\n }\n\n /**\n * @return the error rate for uniquely aligned sequences.\n */\n public float getUniquelyAlignedErrorRate()\n {\n return totalUniquelyAlignedSequenceLength == 0 ? 0.0f : (float)totalUniquelyAlignedMismatchCount / totalUniquelyAlignedSequenceLength;\n }\n\n\n /**\n * @return the preferentially aligned sequence count.\n */\n public int getPreferentiallyAlignedCount()\n {\n return preferentiallyAlignedCount;\n }\n\n /**\n * Increments the number of preferentially aligned sequences.\n */\n public void incrementPreferentiallyAlignedCount()\n {\n preferentiallyAlignedCount++;\n }\n\n /**\n * @return the total preferentially aligned sequence length.\n */\n public int getTotalPreferentiallyAlignedSequenceLength()\n {\n return totalPreferentiallyAlignedSequenceLength;\n }\n\n /**\n * Adds the given preferentially aligned sequence length to the total.\n *\n * @param alignedLength the aligned sequence length.\n */\n public void addPreferentiallyAlignedSequenceLength(int alignedLength)\n {\n totalPreferentiallyAlignedSequenceLength += alignedLength;\n }\n\n /**\n * @return the total number of mismatches in preferentially aligned sequences.\n */\n public int getTotalPreferentiallyAlignedMismatchCount()\n {\n return totalPreferentiallyAlignedMismatchCount;\n }\n\n /**\n * Adds the given number of mismatches to the total for preferentially aligned sequences.\n *\n * @param mismatchCount the number of mismatches.\n */\n public void addPreferentiallyAlignedMismatchCount(int mismatchCount)\n {\n totalPreferentiallyAlignedMismatchCount += mismatchCount;\n }\n\n /**\n * @return the error rate for preferentially aligned sequences.\n */\n public float getPreferentiallyAlignedErrorRate()\n {\n return totalPreferentiallyAlignedSequenceLength == 0 ? 0.0f : (float)totalPreferentiallyAlignedMismatchCount / totalPreferentiallyAlignedSequenceLength;\n }\n\n /**\n * @return the assigned sequence count.\n */\n public int getAssignedCount()\n {\n return assignedCount;\n }\n\n /**\n * Increments the number of assigned sequences.\n */\n public void incrementAssignedCount()\n {\n assignedCount++;\n }\n\n /**\n * @return the total assigned sequence length.\n */\n public int getTotalAssignedSequenceLength()\n {\n return totalAssignedSequenceLength;\n }\n\n /**\n * Adds the given assigned sequence length to the total.\n *\n * @param alignedLength the aligned sequence length.\n */\n public void addAssignedSequenceLength(int alignedLength)\n {\n totalAssignedSequenceLength += alignedLength;\n }\n\n /**\n * @return the total number of mismatches in assigned sequences.\n */\n public int getTotalAssignedMismatchCount()\n {\n return totalAssignedMismatchCount;\n }\n\n /**\n * Adds the given number of mismatches to the total for assigned sequences.\n *\n * @param mismatchCount the number of mismatches.\n */\n public void addAssignedMismatchCount(int mismatchCount)\n {\n totalAssignedMismatchCount += mismatchCount;\n }\n\n /**\n * @return the error rate for assigned sequences.\n */\n public float getAssignedErrorRate()\n {\n return totalAssignedSequenceLength == 0 ? 0.0f : (float)totalAssignedMismatchCount / totalAssignedSequenceLength;\n }\n\n @Override\n public String toString()\n {\n ToStringBuilder sb = new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE);\n sb.append(\"referenceGenomeId\", referenceGenomeId);\n sb.append(\"alignedCount\", alignedCount);\n return sb.toString();\n }\n}", "public class MGAConfig\n{\n public static final long MINIMUM_SEQUENCE_COUNT = 10;\n\n public static final int DEFAULT_PLOT_WIDTH = 800;\n public static final int MINIMUM_PLOT_WIDTH = 600;\n\n private static Logger log = LoggerFactory.getLogger(MGAConfig.class);\n\n private String runId;\n private Integer trimStart;\n private Integer trimLength;\n private String outputPrefix;\n private String sampleSheetFilename;\n private String referenceGenomeMappingFilename;\n private String xslStyleSheetFilename;\n private boolean separateDatasetReports;\n private String datasetReportFilenamePrefix;\n private int plotWidth;\n private long minimumSequenceCount;\n\n public MGAConfig()\n {\n }\n\n public String getRunId()\n {\n return runId;\n }\n\n public void setRunId(String runId)\n {\n this.runId = runId;\n }\n\n public Integer getTrimStart()\n {\n return trimStart;\n }\n\n public void setTrimStart(Number trimStart)\n {\n this.trimStart = trimStart == null ? null : trimStart.intValue();\n }\n\n public Integer getTrimLength()\n {\n return trimLength;\n }\n\n public void setTrimLength(Number trimLength)\n {\n this.trimLength = trimLength == null ? null : trimLength.intValue();\n }\n\n public String getOutputPrefix()\n {\n return outputPrefix;\n }\n\n public void setOutputPrefix(String outputPrefix)\n {\n this.outputPrefix = outputPrefix;\n }\n\n public File getXmlFile()\n {\n return isEmpty(outputPrefix) ? null : new File(outputPrefix + \".xml\");\n }\n\n public File getYamlFile()\n {\n return isEmpty(outputPrefix) ? null : new File(outputPrefix + \".yml\");\n }\n\n public File getHtmlFile()\n {\n return isEmpty(outputPrefix) ? null : new File(outputPrefix + \".html\");\n }\n\n public File getImageFile()\n {\n return isEmpty(outputPrefix) ? null : new File(outputPrefix + \".png\");\n }\n\n public boolean hasSampleSheet()\n {\n return isNotEmpty(sampleSheetFilename);\n }\n\n public File getSampleSheetFile()\n {\n return isEmpty(sampleSheetFilename) ? null : new File(sampleSheetFilename);\n }\n\n public void setSampleSheetFilename(String sampleSheetFilename)\n {\n this.sampleSheetFilename = sampleSheetFilename;\n }\n\n public boolean hasReferenceGenomeMapping()\n {\n return isNotEmpty(referenceGenomeMappingFilename);\n }\n\n public File getReferenceGenomeMappingFile()\n {\n return isEmpty(referenceGenomeMappingFilename) ? null : new File(referenceGenomeMappingFilename);\n }\n\n public void setReferenceGenomeMappingFilename(String referenceGenomeMappingFilename)\n {\n this.referenceGenomeMappingFilename = referenceGenomeMappingFilename;\n }\n\n public boolean hasXSLStyleSheet()\n {\n return isNotEmpty(xslStyleSheetFilename);\n }\n\n public File getXSLStyleSheetFile()\n {\n return isEmpty(xslStyleSheetFilename) ? null : new File(xslStyleSheetFilename);\n }\n\n public void setXSLStyleSheetFilename(String xslStyleSheetFilename)\n {\n this.xslStyleSheetFilename = xslStyleSheetFilename;\n }\n\n public boolean isSeparateDatasetReports()\n {\n return separateDatasetReports;\n }\n\n public void setSeparateDatasetReports(boolean separateDatasetReports)\n {\n this.separateDatasetReports = separateDatasetReports;\n }\n\n public String getDatasetReportFilenamePrefix()\n {\n return datasetReportFilenamePrefix;\n }\n\n public void setDatasetReportFilenamePrefix(String datasetReportFilenamePrefix)\n {\n this.datasetReportFilenamePrefix = datasetReportFilenamePrefix;\n }\n\n public int getPlotWidth()\n {\n return plotWidth;\n }\n\n public void setPlotWidth(Number plotWidthN)\n {\n plotWidth = plotWidthN == null ? DEFAULT_PLOT_WIDTH : plotWidthN.intValue();\n if (plotWidth < MINIMUM_PLOT_WIDTH)\n {\n log.warn(\"Minimum width of plot is {} pixels.\", MINIMUM_PLOT_WIDTH);\n plotWidth = MINIMUM_PLOT_WIDTH;\n }\n }\n\n public long getMinimumSequenceCount()\n {\n return minimumSequenceCount;\n }\n\n public void setMinimumSequenceCount(Number minimumSequenceCountN)\n {\n minimumSequenceCount = minimumSequenceCountN == null ? MINIMUM_SEQUENCE_COUNT : minimumSequenceCountN.longValue();\n }\n}", "public class MultiGenomeAlignmentSummary implements Serializable\n{\n private static final long serialVersionUID = 7594987898110254817L;\n\n private String datasetId;\n private long sequenceCount;\n private int sampledCount;\n private int trimLength;\n private int adapterCount;\n private int alignedCount;\n private Map<String, AlignmentSummary> alignmentSummaries = new HashMap<String, AlignmentSummary>();\n private List<OrderedProperties> sampleProperties = new ArrayList<OrderedProperties>();\n private Set<String> expectedReferenceGenomeIds = new HashSet<String>();\n\n /**\n * @return the datasetId\n */\n public String getDatasetId()\n {\n return datasetId;\n }\n\n /**\n * @param datasetId the datasetId to set\n */\n public void setDatasetId(String datasetId)\n {\n this.datasetId = datasetId;\n }\n\n /**\n * @return the sequenceCount\n */\n public long getSequenceCount()\n {\n return sequenceCount;\n }\n\n /**\n * @param sequenceCount the sequenceCount to set\n */\n public void setSequenceCount(long sequenceCount)\n {\n this.sequenceCount = sequenceCount;\n }\n\n /**\n * @return the sampledCount\n */\n public int getSampledCount()\n {\n return sampledCount;\n }\n\n /**\n * @param sampledCount the sampledCount to set\n */\n public void setSampledCount(int sampledCount)\n {\n this.sampledCount = sampledCount;\n }\n\n /**\n * @return the trim length\n */\n public int getTrimLength()\n {\n return trimLength;\n }\n\n /**\n * @param trimLength the trim length\n */\n public void setTrimLength(int trimLength)\n {\n this.trimLength = trimLength;\n }\n\n /**\n * @return the adapterCount\n */\n public int getAdapterCount()\n {\n return adapterCount;\n }\n\n /**\n * @param adapterCount the adapterCount to set\n */\n public void setAdapterCount(int adapterCount)\n {\n this.adapterCount = adapterCount;\n }\n\n /**\n * @return the number of aligned sequences\n */\n public int getAlignedCount()\n {\n return alignedCount;\n }\n\n /**\n * Increments the number of aligned sequences.\n */\n public void incrementAlignedCount()\n {\n alignedCount++;\n }\n\n /**\n * @return the unmappedCount\n */\n public int getUnmappedCount()\n {\n return sampledCount - alignedCount;\n }\n\n /**\n * @return the alignmentSummaries\n */\n public AlignmentSummary[] getAlignmentSummaries()\n {\n return alignmentSummaries.values().toArray(new AlignmentSummary[0]);\n }\n\n /**\n * Add an alignment summary for a specific reference genome.\n *\n * @param alignmentSummary the alignment summary.\n */\n public void addAlignmentSummary(AlignmentSummary alignmentSummary)\n {\n alignmentSummaries.put(alignmentSummary.getReferenceGenomeId(), alignmentSummary);\n }\n\n /**\n * Returns the alignment summary for the given reference genome.\n *\n * @param referenceGenomeId the reference genome identifier.\n * @return\n */\n public AlignmentSummary getAlignmentSummary(String referenceGenomeId)\n {\n return alignmentSummaries.get(referenceGenomeId);\n }\n\n /**\n * @return the sample properties\n */\n public List<OrderedProperties> getSampleProperties()\n {\n return sampleProperties;\n }\n\n /**\n * Adds the given reference genome to the set of Expecteds for this dataset.\n *\n * @param referenceGenomeId\n */\n public void addExpectedReferenceGenomeId(String referenceGenomeId) {\n expectedReferenceGenomeIds.add(referenceGenomeId);\n }\n\n /**\n * Determines if the given reference genome is a control for this dataset.\n * \n * @param referenceGenomeId\n * @return\n */\n public boolean isExpectedReferenceGenome(String referenceGenomeId)\n {\n return expectedReferenceGenomeIds.contains(referenceGenomeId);\n }\n\n @Override\n public String toString()\n {\n ToStringBuilder sb = new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE);\n sb.append(\"datasetId\", datasetId);\n sb.append(\"sequenceCount\", sequenceCount);\n sb.append(\"sampledCount\", sampledCount);\n sb.append(\"adapterCount\", adapterCount);\n sb.append(\"alignedCount\", alignedCount);\n if (alignmentSummaries != null && !alignmentSummaries.isEmpty())\n {\n sb.append(\"alignmentSummaries\", StringUtils.join(alignmentSummaries.keySet(), \",\"));\n }\n return sb.toString();\n }\n}", "public class ReferenceGenomeSpeciesMapping implements Serializable\n{\n private static final long serialVersionUID = 4030199690379891172L;\n\n private Map<String, String> referenceGenomeSpeciesLookup = new HashMap<String, String>();\n private Map<String, String> referenceGenomeIdLookup = new HashMap<String, String>();\n\n /**\n * Loads reference genome ID to species mappings from the given properties\n * file.\n *\n * @param referenceGenomeMappingFile the reference genome mapping file\n * @throws FileNotFoundException\n * @throws IOException\n */\n public void loadFromPropertiesFile(File referenceGenomeMappingFile) throws FileNotFoundException, IOException\n {\n try (InputStream fileStream = new FileInputStream(referenceGenomeMappingFile))\n {\n Properties properties = new Properties();\n properties.load(fileStream);\n\n Enumeration<?> referenceGenomeIds = properties.keys();\n while (referenceGenomeIds.hasMoreElements())\n {\n String referenceGenomeId = (String)referenceGenomeIds.nextElement();\n String[] names = properties.getProperty(referenceGenomeId).split(\"\\\\|\");\n\n List<String> nameList = new ArrayList<String>();\n for (String name : names)\n {\n name = name.trim();\n if (name.length() > 0)\n {\n nameList.add(name);\n }\n }\n\n if (nameList.isEmpty())\n {\n referenceGenomeSpeciesLookup.put(referenceGenomeId, \"Not specified\");\n }\n else\n {\n referenceGenomeSpeciesLookup.put(referenceGenomeId, nameList.get(0));\n for (String name : nameList)\n {\n name = name.toLowerCase();\n if (!referenceGenomeIdLookup.containsKey(name))\n {\n referenceGenomeIdLookup.put(name, referenceGenomeId);\n }\n }\n }\n }\n }\n }\n\n /**\n * Returns the reference genome ID for the given species name/synonym.\n *\n * @param species the name of the species.\n *\n * @return The reference genome ID for the given species, or null if it isn't mapped.\n */\n public String getReferenceGenomeId(String species)\n {\n return referenceGenomeIdLookup.get(species.toLowerCase());\n }\n\n /**\n * Returns the species display name for the given reference genome ID.\n *\n * @param referenceGenomeId the reference genome identifier\n *\n * @return The species of the given reference genome, or null if it isn't mapped.\n */\n public String getSpecies(String referenceGenomeId)\n {\n return referenceGenomeSpeciesLookup.get(referenceGenomeId);\n }\n\n /**\n * Get an unordered list of all the reference genome identifiers.\n *\n * @return A list of reference genome IDs.\n */\n public Collection<String> listReferenceGenomeIds()\n {\n return Collections.unmodifiableCollection(referenceGenomeIdLookup.keySet());\n }\n\n /**\n * Get an unordered list of all the species names.\n *\n * @return A list of species.\n */\n public Collection<String> listSpecies()\n {\n return Collections.unmodifiableCollection(referenceGenomeSpeciesLookup.keySet());\n }\n}", "public class OrderedProperties extends LinkedMap<String, String>\n{\n private static final long serialVersionUID = 8837732667981161564L;\n\n /**\n * Get the key set as an array.\n *\n * @return The key set as an array.\n *\n * @deprecated Use {@link #keySet()} instead and work with the collection.\n */\n @Deprecated\n public String[] getPropertyNames()\n {\n return keySet().toArray(new String[0]);\n }\n\n /**\n * Set a key to a value.\n *\n * @param name The key.\n * @param value The value;\n *\n * @deprecated Use {@link #put(String, String)} instead.\n */\n @Deprecated\n public void setProperty(String name, String value)\n {\n put(name, value);\n }\n\n /**\n * Get a value by key.\n *\n * @param name The key of the value to get.\n *\n * @return The value matching the given key, or null if there is no match.\n *\n * @deprecated Use {@link #get(Object)} instead.\n */\n public String getProperty(String name)\n {\n return get(name);\n }\n\n /**\n * Returns the value of the property matching the first of the given\n * set of names.\n *\n * @param names the possible names for the property.\n * @return the property value.\n */\n public String getProperty(String[] names)\n {\n for (String name : names)\n {\n String value = get(name);\n if (value != null) return value;\n }\n return null;\n }\n\n /**\n * Remove a key and value from the map.\n *\n * @param name The key.\n * @return The value removed, or null.\n *\n * @deprecated Use {@link #remove(Object)} instead.\n */\n @Deprecated\n public String removeProperty(String name)\n {\n return remove(name);\n }\n}" ]
import static org.cruk.mga.MGAConfig.DEFAULT_PLOT_WIDTH; import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Composite; import java.awt.Font; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.imageio.ImageIO; import org.cruk.mga.AlignmentSummary; import org.cruk.mga.MGAConfig; import org.cruk.mga.MultiGenomeAlignmentSummary; import org.cruk.mga.ReferenceGenomeSpeciesMapping; import org.cruk.util.OrderedProperties; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package org.cruk.mga.report; public class SummaryPlotter { private static final int[] INTERVALS = new int[] {5, 10, 25}; private static final int OPTIMUM_NO_INTERVALS = 6; private static final float ROW_HEIGHT_SCALING_FACTOR = 1.5f; private static final float ROW_GAP_SCALING_FACTOR = 2.0f; private static final int DEFAULT_FONT_SIZE = 12; private static final int DEFAULT_AXIS_FONT_SIZE = 10; private static final int DEFAULT_GAP_SIZE = 10; private static final Color ADAPTER_COLOR = new Color(255, 102, 255); private static final float MAX_ALPHA = 1.0f; private static final float MIN_ALPHA = 0.1f; private static final float MIN_ERROR = 0.0025f; private static final float MAX_ERROR = 0.01f; private static final String[] SPECIES_PROPERTY_NAMES = new String[] { "Species", "species" }; private static final String[] CONTROL_PROPERTY_NAMES = new String[] { "Control", "control" }; protected Logger log = LoggerFactory.getLogger(SummaryPlotter.class); public SummaryPlotter() { } /** * Creates a summary plot for the given set of multi-genome alignment summaries. * * @param multiGenomeAlignmentSummaries * @param the name of the image file * @throws IOException */
public void createSummaryPlot(MGAConfig mgaConfig,
2
ericleong/forceengine
Force Engine/src/forceengine/demo/objects/Gel.java
[ "public interface Colored {\n\tpublic Color getColor();\n}", "public class CircleMath {\n\t/**\n\t * checks whether or not 2 circles have collided with each other\n\t * \n\t * @param circle1\n\t * the first circle\n\t * @param circle2\n\t * the second circle\n\t * @return whether or not they have collided\n\t */\n\tpublic static final boolean checkcirclecollide(Circle circle1,\n\t\t\tCircle circle2) {\n\t\treturn checkcirclecollide(circle1.getX(), circle1.getY(),\n\t\t\t\tcircle1.getRadius(), circle2.getX(), circle2.getY(),\n\t\t\t\tcircle2.getRadius());\n\t}\n\n\t/**\n\t * checks whether or not 2 circles have collided\n\t * \n\t * @param x1\n\t * the x value of the first circle\n\t * @param y1\n\t * the y value of the first circle\n\t * @param radius1\n\t * the radius of the first circle\n\t * @param x2\n\t * the x value of the second circle\n\t * @param y2\n\t * the y value of the second circle\n\t * @param radius2\n\t * the radius of the second circle\n\t * @return whether or not they have collided\n\t */\n\tpublic static final boolean checkcirclecollide(double x1, double y1,\n\t\t\tdouble radius1, double x2, double y2, double radius2) {\n\t\treturn Math.abs((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) < (radius1 + radius2)\n\t\t\t\t* (radius1 + radius2);\n\t}\n\n\t/**\n\t * Checks whether or not an array of Circles has collided with a circle.\n\t * \n\t * @param circles\n\t * The <code>ArrayList</code> of <code>Circle</code>.\n\t * @param circle\n\t * The <code>Circle</code> that collision is to be done with.\n\t * @return The index of the <code>Circle</code> in circles that collided\n\t * with circle.\n\t */\n\tpublic static final ArrayList<Integer> checkcirclescollide(\n\t\t\tArrayList<Circle> circles, Circle circle) {\n\t\tArrayList<Integer> collisionindex = new ArrayList<Integer>(\n\t\t\t\t(int) Math.ceil(circles.size() / 10));\n\t\tfor (int i = 0; i < circles.size(); i++) {\n\t\t\tif (checkcirclecollide(circles.get(i), circle)) { // they\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// intersect\n\t\t\t\tcollisionindex.add(i);\n\t\t\t}\n\t\t}\n\t\treturn collisionindex;\n\t}\n\n\t/**\n\t * Checks whether or not an array of StaticCircles has collided with a\n\t * circle.\n\t * \n\t * @param circles\n\t * The <code>ArrayList</code> of <code>StaticCircle</code>.\n\t * @param circle\n\t * The <code>StaticCircle</code> that collision is to be done\n\t * with.\n\t * @return The index of the <code>StaticCircle</code> in circles that\n\t * collided with circle.\n\t */\n\tpublic static final ArrayList<Integer> checkstaticcirclescollide(\n\t\t\tArrayList<StaticCircle> circles, Circle circle) {\n\t\tArrayList<Integer> collisionindex = new ArrayList<Integer>(\n\t\t\t\t(int) Math.ceil(circles.size() / 10));\n\t\tfor (int i = 0; i < circles.size(); i++) {\n\t\t\tif (checkcirclecollide(circles.get(i), circle)) { // they intersect\n\t\t\t\tcollisionindex.add(i);\n\t\t\t}\n\t\t}\n\t\treturn collisionindex;\n\t}\n}", "public interface Circle extends Rect {\n\t/**\n\t * (double) getRadius\n\t * \n\t * @return the radius\n\t */\n\tpublic double getRadius();\n\n\t/**\n\t * (double) getRadius\n\t * \n\t * @return the radius squared (radius^2)\n\t */\n\tpublic double getRadiusSq();\n\n\n\t/**\n\t * Sets the radius of the circle.\n\t * \n\t * @param radius\n\t * The new radius of this circle.\n\t */\n\tpublic void setRadius(double radius);\n\n}", "public class ForceCircle extends Force implements Circle {\n\tprotected double radius;\n\tprotected double radiussq; // probably won't dump but not all that useful to keep\n\n\t/**\n\t * Creates a <code>ForceCircle</code> at (<code>x</code>, <code>y</code>) with the specified mass and radius. Vector\n\t * components are set to 0 (no movement).\n\t * \n\t * @param x The x value.\n\t * @param y The y value.\n\t * @param radius The radius of the circle.\n\t * @param mass The mass of the circle.\n\t */\n\tpublic ForceCircle(double x, double y, double radius, double mass){\n\t\tthis(x, y, 0, 0, radius, mass);\n\t}\n\t/**\n\t * Creates a <code>ForceCircle</code> at (<code>x</code>, <code>y</code>) with vector components &#60<code>vx</code>\n\t * , <code>vy</code>&#62 and the specified mass and radius.\n\t * \n\t * @param x The x value.\n\t * @param y The y value.\n\t * @param vx The horizontal vector component.\n\t * @param vy The vertical vector component.\n\t * @param radius The radius of the circle.\n\t * @param mass The mass of the circle.\n\t */\n\tpublic ForceCircle(double x, double y, double vx, double vy, double radius, double mass){\n\t\tthis(x, y, vx, vy, radius, mass, 1);\n\t}\n\t/**\n\t * Creates a <code>ForceCircle</code> at (<code>x</code>, <code>y</code>) with vector components &#60<code>vx</code>\n\t * , <code>vy</code>&#62 and the specified mass and radius.\n\t * \n\t * @param x The x value.\n\t * @param y The y value.\n\t * @param vx The horizontal vector component.\n\t * @param vy The vertical vector component.\n\t * @param radius The radius of the circle.\n\t * @param mass The mass of the circle.\n\t */\n\tpublic ForceCircle(double x, double y, double vx, double vy, double radius, double mass, boolean polar){\n\t\tthis(x, y, vx, vy, radius, mass, 1);\n\t}\n\tpublic ForceCircle(double x, double y, double vx, double vy, double radius, double mass, double restitution){\n\t\tsuper(x, y, vx, vy, mass, restitution);\n\t\tthis.radius = radius;\n\t\tthis.radiussq = radius * radius;\n\t}\n\tpublic ForceCircle(double x, double y, double vx, double vy, double radius, double mass, double restitution, boolean polar){\n\t\tsuper(x, y, vx, vy, mass, restitution, polar);\n\t\tthis.radius = radius;\n\t\tthis.radiussq = radius * radius;\n\t}\n\n\tpublic ForceCircle(Force f, double radius){\n\t\tsuper(f);\n\t\tthis.setRadius(radius);\n\t}\n\tpublic ForceCircle(ForceCircle f){\n\t\tsuper(f);\n\t\tthis.radius = f.getRadius();\n\t\tthis.radiussq = f.getRadiusSq();\n\t}\n\tpublic ForceCircle(Point p, Vector v, double radius, double mass){\n\t\tsuper(p, v, mass);\n\t\tthis.setRadius(radius);\n\t}\n\tpublic ForceCircle(PointVector v, double radius, double mass){\n\t\tsuper(v, mass);\n\t\tthis.setRadius(radius);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj){\n\t\tif(this == obj)\n\t\t\treturn true;\n\t\tif(!super.equals(obj))\n\t\t\treturn false;\n\t\tif(getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tForceCircle other = (ForceCircle)obj;\n\t\tif(java.lang.Double.doubleToLongBits(radius) != java.lang.Double.doubleToLongBits(other.radius))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\t@Override\n\tpublic double getRadius(){\n\t\treturn radius;\n\t}\n\t@Override\n\tpublic double getRadiusSq(){\n\t\treturn radiussq;\n\t}\n\t@Override\n\tpublic int hashCode(){\n\t\tfinal int prime = 31;\n\t\tint result = super.hashCode();\n\t\tresult = (int)(prime * result + java.lang.Double.doubleToLongBits(radius));\n\t\treturn result;\n\t}\n\t@Override\n\tpublic void setRadius(double radius){\n\t\tif(radius > 0){\n\t\t\tthis.radius = radius;\n\t\t\tthis.radiussq = radius * radius;\n\t\t}\n\t}\n\t@Override\n\tpublic double getMaxX() {\n\t\treturn x + radius;\n\t}\n\t@Override\n\tpublic double getMaxY() {\n\t\treturn y + radius;\n\t}\n\t@Override\n\tpublic double getMinX() {\n\t\treturn x - radius;\n\t}\n\t@Override\n\tpublic double getMinY() {\n\t\treturn y - radius;\n\t}\n\t@Override\n\tpublic double getHeight() {\n\t\treturn 2 * radius;\n\t}\n\t@Override\n\tpublic double getWidth() {\n\t\treturn 2 * radius;\n\t}\n\t@Override\n\tpublic void setHeight(double height) {\n\t\tsetRadius(height / 2);\n\t}\n\t@Override\n\tpublic void setWidth(double width) {\n\t\tsetRadius(width / 2);\n\t}\n}", "public class Point {\n\t\n\tprotected double x, y;\n\t\n\t/**\n\t * Finds the midpoint between two points, in rectangular coordinates.\n\t * \n\t * @param x1 The x value of the first point.\n\t * @param y1 The y value of the first point.\n\t * @param x2 The x value of the second point.\n\t * @param y2 The y value of the second point.\n\t * @return A <code>Point</code> with the coordinates of the midpoint of (x1, y1) and (x2, y2).\n\t */\n\tpublic static final Point midpoint(double x1, double y1, double x2, double y2){\n\t\treturn new Point(((x1 + x2) / 2), ((y1 + y2) / 2));\n\t}\n\t/**\n\t * Finds the midpoint between two points.\n\t * \n\t * @param p1 The first <code>Point</code>.\n\t * @param p2 The second <code>Point</code>.\n\t * @return The midpoint between <b>p1</b> and <b>p2</b>.\n\t */\n\tpublic static final Point midpoint(Point p1, Point p2){\n\t\treturn midpoint(p1.getX(), p1.getY(), p2.getX(), p2.getY());\n\t}\n\t\n\t/**\n\t * Constructs a Point with the coordinates (0, 0).\n\t */\n\tpublic Point(){\n\t\tx = 0;\n\t\ty = 0;\n\t}\n\t/**\n\t * Constructs a Point with specified x and y values.\n\t * \n\t * @param x The x value.\n\t * @param y The y value.\n\t */\n\tpublic Point(double x, double y){\n\t\tif(java.lang.Double.isNaN(x) || java.lang.Double.isInfinite(x))\n\t\t\tx = 0;\n\t\tif(java.lang.Double.isNaN(y) || java.lang.Double.isInfinite(y))\n\t\t\ty = 0;\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t}\n\tpublic Point(Point p){\n\t\tthis(p.getX(), p.getY());\n\t}\n\t/**\n\t * Contstructs a <code>Point</code>, given a <code>Vector</code>. It takes the endpoint of the head of the vector if\n\t * the tail of the vector is at (0, 0).\n\t * \n\t * @param v The vector to be used.\n\t */\n\tpublic Point(Vector v){\n\t\tthis(v.getvx(), v.getvy());\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj){\n\t\tif(this == obj)\n\t\t\treturn true;\n\t\tif(obj == null)\n\t\t\treturn false;\n\t\tif(getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tPoint other = (Point)obj;\n\t\tif(java.lang.Double.doubleToLongBits(x) != java.lang.Double.doubleToLongBits(other.x))\n\t\t\treturn false;\n\t\tif(java.lang.Double.doubleToLongBits(y) != java.lang.Double.doubleToLongBits(other.y))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\t/**\n\t * Return's this object's location (included to match Point2D).\n\t * \n\t * @return This object.\n\t */\n\tpublic Point getLocation(){\n\t\treturn this;\n\t}\n\n\t/**\n\t * Returns the (1 - ) coefficient of restitution between this object and another object.\n\t * <code>a.getRestitution(b)</code> does not necessarily have to equal <code>b.getRestitution(a)</code>, but the\n\t * coefficient of restitution for <code>a</code> is determined by <code>a.getRestitution(b)</code> to avoid casting\n\t * b. Default is 1.\n\t * \n\t * @param o The <code>Object</code> to be checked against.\n\t * @return The coefficient of restitution between this object and <b>o</b> if this object collides into <b>o</b>.\n\t */\n\tpublic double getRestitution(Object o){\n\t\treturn 1;\n\t}\n\n\tpublic double getX(){\n\t\treturn x;\n\t}\n\tpublic double getY(){\n\t\treturn y;\n\t}\n\tpublic Point getPoint(){\n\t\treturn this;\n\t}\n\t@Override\n\tpublic int hashCode(){\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = (int)(prime * result + java.lang.Double.doubleToLongBits(x));\n\t\tresult = (int)(prime * result + java.lang.Double.doubleToLongBits(y));\n\t\treturn result;\n\t}\n\t\n\t/**\n\t * @return Whether or not this {@link Point} is alive.\n\t */\n\tpublic boolean isAlive() {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Checks if this object collides with another object. Default is <code>true</code>. <code>a.isCollide(b)</code> and\n\t * <code>b.isCollide(a)</code> must be <code>true</code> for collision checking to go through.\n\t * \n\t * @param o The <code>Object</code> to be checked against.\n\t * @return Whether or not this object collides with <b>o</b>.\n\t */\n\tpublic boolean isCollide(Object o){\n\t\treturn true;\n\t}\n\t/**\n\t * Checks if this object responds to collision with another object. Should not return <code>true</code> if\n\t * <code>isCollide(<b>o</b>)</code> returns <code>false</code>. Default is <code>true</code>.\n\t * <code>a.isResponsive(b)</code> does not have to equal <code>b.isResponsive(a)</code>, but the reaction of\n\t * <code>a</code> depends on the value of <code>a.isResponsive(b)</code>.\n\t * \n\t * @param o The <code>Object</code> to be checked against.\n\t * @return Whether or not this object responds to <b>o</b>.\n\t */\n\tpublic boolean isResponsive(Object o){\n\t\treturn isCollide(o);\n\t}\n\n\t/**\n\t * Converts the X and Y values into doubles and sets both of the X and Y values in one function.\n\t * \n\t * @param x the new x value\n\t * @param y the new y value\n\t */\n\tpublic void setPoint(double x, double y){\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t}\n\t/**\n\t * Changes the x and y coordinates of this point to match those of the argument.\n\t * \n\t * @param p The new coordinates.\n\t */\n\tpublic void setPoint(Point p){\n\t\tthis.x = p.getX();\n\t\tthis.y = p.getY();\n\t}\n\tpublic void setX(double x){\n\t\tthis.x = x;\n\t}\n\tpublic void setY(double y){\n\t\tthis.y = y;\n\t}\n\t@Override\n\tpublic String toString(){\n\t\treturn String.format(\"(%4.8f, %4.8f)\", this.x, this.y);\n\t}\n\tpublic Point translate(double dx, double dy){\n\t\tsetPoint(x + dx, y + dy);\n\t\treturn this;\n\t}\n\tpublic Point translate(Vector v){\n\t\treturn translate(v.getvx(), v.getvy());\n\t}\n\t\n\t/**\n * Returns the square of the distance between two points.\n *\n * @param x1 the X coordinate of the first specified point\n * @param y1 the Y coordinate of the first specified point\n * @param x2 the X coordinate of the second specified point\n * @param y2 the Y coordinate of the second specified point\n * @return the square of the distance between the two\n * sets of specified coordinates.\n * @since 1.2\n */\n public static double distanceSq(double x1, double y1,\n double x2, double y2)\n {\n x1 -= x2;\n y1 -= y2;\n return (x1 * x1 + y1 * y1);\n }\n\n /**\n * Returns the distance between two points.\n *\n * @param x1 the X coordinate of the first specified point\n * @param y1 the Y coordinate of the first specified point\n * @param x2 the X coordinate of the second specified point\n * @param y2 the Y coordinate of the second specified point\n * @return the distance between the two sets of specified\n * coordinates.\n * @since 1.2\n */\n public static double distance(double x1, double y1,\n double x2, double y2)\n {\n x1 -= x2;\n y1 -= y2;\n return Math.sqrt(x1 * x1 + y1 * y1);\n }\n\n /**\n * Returns the square of the distance from this\n * <code>Point2D</code> to a specified point.\n *\n * @param px the X coordinate of the specified point to be measured\n * against this <code>Point2D</code>\n * @param py the Y coordinate of the specified point to be measured\n * against this <code>Point2D</code>\n * @return the square of the distance between this\n * <code>Point2D</code> and the specified point.\n * @since 1.2\n */\n public double distanceSq(double px, double py) {\n px -= getX();\n py -= getY();\n return (px * px + py * py);\n }\n\n /**\n * Returns the square of the distance from this\n * <code>Point2D</code> to a specified <code>Point2D</code>.\n *\n * @param pt the specified point to be measured\n * against this <code>Point2D</code>\n * @return the square of the distance between this\n * <code>Point2D</code> to a specified <code>Point2D</code>.\n * @since 1.2\n */\n public double distanceSq(Point pt) {\n double px = pt.getX() - this.getX();\n double py = pt.getY() - this.getY();\n return (px * px + py * py);\n }\n\n /**\n * Returns the distance from this <code>Point2D</code> to\n * a specified point.\n *\n * @param px the X coordinate of the specified point to be measured\n * against this <code>Point2D</code>\n * @param py the Y coordinate of the specified point to be measured\n * against this <code>Point2D</code>\n * @return the distance between this <code>Point2D</code>\n * and a specified point.\n * @since 1.2\n */\n public double distance(double px, double py) {\n px -= getX();\n py -= getY();\n return Math.sqrt(px * px + py * py);\n }\n\n /**\n * Returns the distance from this <code>Point2D</code> to a\n * specified <code>Point2D</code>.\n *\n * @param pt the specified point to be measured\n * against this <code>Point2D</code>\n * @return the distance between this <code>Point2D</code> and\n * the specified <code>Point2D</code>.\n * @since 1.2\n */\n public double distance(Point pt) {\n double px = pt.getX() - this.getX();\n double py = pt.getY() - this.getY();\n return Math.sqrt(px * px + py * py);\n }\n}", "public class PointVector extends Point implements Vector, Line {\n\tprotected double vx = 0;\n\tprotected double vy = 0;\n\t\n\tpublic PointVector(){\n\t\tthis(0, 0);\n\t}\n\n\tpublic PointVector(double x, double y) {\n\t\tthis(x, y, 0, 0);\n\t}\n\n\tpublic PointVector(double x, double y, double vx, double vy) {\n\t\tsuper(x, y);\n\t\tthis.vx = vx;\n\t\tthis.vy = vy;\n\t}\n\n\tpublic PointVector(Point p) {\n\t\tthis(p.getX(), p.getY(), 0, 0);\n\t}\n\n\tpublic PointVector(Point p, Vector v) {\n\t\tthis(p.getX(), p.getY(), v.getvx(), v.getvy());\n\t}\n\n\tpublic PointVector(PointVector pv) {\n\t\tthis(pv.getX(), pv.getY(), pv.getvx(), pv.getvy());\n\t}\n\n\tpublic PointVector(Vector v) {\n\t\tthis(0, 0, v.getvx(), v.getvy());\n\t}\n\n\t@Override\n\tpublic PointVector add(Vector v) {\n\t\tsetRect(getvx() + v.getvx(), getvy() + v.getvy());\n\t\treturn this;\n\t}\n\n\t@Override\n\tpublic double dot(Vector v) {\n\t\treturn getvx() * v.getvx() + getvy() * v.getvy();\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (!super.equals(obj))\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tPointVector other = (PointVector) obj;\n\t\tif (java.lang.Double.doubleToLongBits(x) != java.lang.Double.doubleToLongBits(other.x))\n\t\t\treturn false;\n\t\tif (java.lang.Double.doubleToLongBits(y) != java.lang.Double.doubleToLongBits(other.y))\n\t\t\treturn false;\n\t\tif (java.lang.Double.doubleToLongBits(vx) != java.lang.Double.doubleToLongBits(other.vx))\n\t\t\treturn false;\n\t\tif (java.lang.Double.doubleToLongBits(vy) != java.lang.Double.doubleToLongBits(other.vy))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic double getAngle() {\n\t\treturn Math.atan2(this.vy, this.vx);\n\t}\n\n\t@Override\n\tpublic Rect getBounds() {\n\t\treturn StaticRect.fromUpperLeft((int)Math.min(getX1(), getX2()), (int)Math.min(getY1(), getY2()), (int)Math.max(getX1(), getX2()), (int)Math.max(getY1(), getY2()));\n\t}\n\n\t@Override\n\tpublic double getLength() {\n\t\treturn VectorMath.length(vx, vy);\n\t}\n\t\n\t@Override\n\tpublic Point getP1() {\n\t\treturn new Point(getX1(), getY1());\n\t}\n\n\t@Override\n\tpublic Point getP2() {\n\t\treturn new Point(getX2(), getY2());\n\t}\n\n\t@Override\n\tpublic Vector getUnitVector() {\n\t\tdouble length = getLength();\n\t\treturn new RectVector(getvx() / length, getvy() / length);\n\t}\n\n\t/**\n\t * Returns the vector components.\n\t * \n\t * @return The vector components of this <code>PointVector</code>.\n\t */\n\tpublic Vector getVector() {\n\t\treturn new RectVector(this.vx, this.vy);\n\t}\n\n\t@Override\n\tpublic double getvx() {\n\t\treturn vx;\n\t}\n\n\t@Override\n\tpublic double getvy() {\n\t\treturn vy;\n\t}\n\n\t@Override\n\tpublic double getX1() {\n\t\treturn x;\n\t}\n\n\t@Override\n\tpublic double getX2() {\n\t\treturn x + vx;\n\t}\n\n\t@Override\n\tpublic double getY1() {\n\t\treturn y;\n\t}\n\n\t@Override\n\tpublic double getY2() {\n\t\treturn y + vy;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = super.hashCode();\n\t\tresult = (int) (prime * result + java.lang.Double.doubleToLongBits(vx));\n\t\tresult = (int) (prime * result + java.lang.Double.doubleToLongBits(vy));\n\t\treturn result;\n\t}\n\n\t/**\n\t * Checks if this object is frozen (immobile or static).\n\t * \n\t * @return Whether or not this object is frozen.\n\t */\n\tpublic boolean isFrozen() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic Vector rotate(double angle) {\n\t\tsetRect(getvx() * Math.cos(angle) - getvy() * Math.sin(angle), getvx()\n\t\t\t\t* Math.sin(angle) + getvy() * Math.cos(angle));\n\t\treturn this;\n\t}\n\t@Override\n\tpublic Vector scale(double scalar) {\n\t\tthis.vx *= scalar;\n\t\tthis.vy *= scalar;\n\t\t\n\t\treturn this;\n\t}\n\n\t@Override\n\tpublic void setAngle(double angle) {\n\t\tdouble length = getLength();\n\t\tthis.vx = length * Math.cos(angle);\n\t\tthis.vy = length * Math.sin(angle);\n\t}\n\n\t@Override\n\tpublic void setLength(double length) {\n\t\tdouble origlen = getLength();\n\t\tsetRect((length * (getvx() / origlen)), (length * (getvy() / origlen)));\n\t}\n\n\t@Override\n\tpublic void setLine(double x1, double y1, double x2, double y2) {\n\t\tx = x1;\n\t\ty = y1;\n\t\tvx = x2 - x1;\n\t\tvy = y2 - y1;\n\t}\n\n\tpublic void setPointVector(PointVector v) {\n\t\tthis.x = v.getX();\n\t\tthis.y = v.getY();\n\t\tthis.vx = v.getvx();\n\t\tthis.vy = v.getvy();\n\t}\n\n\t@Override\n\tpublic void setPolar(double angle, double length) {\n\t\tsetRect(length * Math.cos(angle), length * Math.sin(angle));\n\t}\n\n\t@Override\n\tpublic void setRect(double vx, double vy) {\n\t\tthis.vx = vx;\n\t\tthis.vy = vy;\n\t}\n\n\t@Override\n\tpublic void setVector(Vector v) {\n\t\tthis.vx = v.getvx();\n\t\tthis.vy = v.getvy();\n\t}\n\n\t@Override\n\tpublic void setvx(double vx) {\n\t\tthis.vx = vx;\n\t}\n\n\t@Override\n\tpublic void setvy(double vy) {\n\t\tthis.vy = vy;\n\t}\n\n\t@Override\n\tpublic Vector subtract(Vector v) {\n\t\tsetRect(getvx() - v.getvx(), getvy() - v.getvy());\n\t\treturn this;\n\t}\n\t\n\tpublic PointVector translate(Vector v){\n\t\ttranslate(v.getvx(), v.getvy());\n\t\treturn this;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn super.toString() + String.format(\"\\t<%4.8f, %4.8f>\", this.vx, this.vy);\n\t}\n}", "public class RectVector extends AbstractVector implements Vector {\n\n\tpublic static final RectVector ZERO = new RectVector(0, 0);\n\n\tprivate double vx;\n\tprivate double vy;\n\n\tpublic RectVector(double vx, double vy) {\n\t\tthis.vx = vx;\n\t\tthis.vy = vy;\n\t}\n\n\tpublic RectVector(Vector v) {\n\t\tsetVector(v);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (!super.equals(obj))\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tRectVector other = (RectVector) obj;\n\t\tif (Double.doubleToLongBits(vx) != Double.doubleToLongBits(other.vx))\n\t\t\treturn false;\n\t\tif (Double.doubleToLongBits(vy) != Double.doubleToLongBits(other.vy))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic double getvx() {\n\t\treturn this.vx;\n\t}\n\n\t@Override\n\tpublic double getvy() {\n\t\treturn this.vy;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tlong result = 1;\n\t\tresult = prime * result + Double.doubleToLongBits(vx);\n\t\tresult = prime * result + Double.doubleToLongBits(vy);\n\t\treturn (int) result;\n\t}\n\n\tpublic void setRect(double vx, double vy) {\n\t\tthis.vx = vx;\n\t\tthis.vy = vy;\n\t}\n\n\t@Override\n\tpublic void setVector(Vector v) {\n\t\tthis.vx = v.getvx();\n\t\tthis.vy = v.getvy();\n\t}\n\n\t@Override\n\tpublic void setvx(double vx) {\n\t\tthis.vx = vx;\n\t}\n\n\t@Override\n\tpublic void setvy(double vy) {\n\t\tthis.vy = vy;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"RectVector <\" + vx + \", \" + vy + \">\";\n\t}\n}", "public interface Vector {\n\t/**\n\t * Adds a vector to this vector.\n\t * \n\t * @param v\n\t * The vector to be added.\n\t * \n\t * @return The resultant vector.\n\t */\n\tpublic Vector add(Vector v);\n\n\t/**\n\t * Takes the dot product of this vector with another vector.\n\t * \n\t * @param v\n\t * The vector to be multiplied.\n\t * @return The resultant vector.\n\t */\n\tpublic double dot(Vector v);\n\n\t/**\n\t * Returns the angle of the x and y components when translating to polar\n\t * coordinates.\n\t * \n\t * @return The angle of the x and y components.\n\t */\n\tpublic double getAngle();\n\n\t/**\n\t * Gets the length of the <code>Vector</code>.\n\t * \n\t * @return The length of the <code>Vector</code>.\n\t */\n\tpublic double getLength();\n\n\t/**\n\t * Gets the normal vector.\n\t * \n\t * @return The normal vector.\n\t */\n\tpublic Vector getUnitVector();\n\n\t/**\n\t * Gets the x component.\n\t * \n\t * @return The x component.\n\t */\n\tpublic double getvx();\n\n\t/**\n\t * Gets the y component.\n\t * \n\t * @return The y component.\n\t */\n\tpublic double getvy();\n\n\t/**\n\t * Scales this vector.\n\t * \n\t * @param scalar\n\t * The scalar to multiply this vector by.\n\t * \n\t * @return The resultant vector.\n\t */\n\tpublic Vector scale(double scalar);\n\n\t/**\n\t * Subtracts the given vector from this vector.\n\t * \n\t * @param v\n\t * The vector to subtract.\n\t * @return The resultant vector.\n\t */\n\tpublic Vector subtract(Vector v);\n\n\t/**\n\t * Rotates this vector.\n\t * \n\t * @param angle\n\t * The angle to rotate this vector by.\n\t * @return The rotated vector.\n\t */\n\tpublic Vector rotate(double angle);\n\n\t/**\n\t * Sets the angle (in radians).\n\t * \n\t * @param angle\n\t * The new angle (in radians).\n\t */\n\tpublic void setAngle(double angle);\n\n\t/**\n\t * Sets the length.\n\t * \n\t * @param length\n\t * The new length.\n\t */\n\tpublic void setLength(double length);\n\n\t/**\n\t * Sets the values of this {@link Vector} to the given polar coordinates.\n\t * \n\t * @param angle\n\t * The angle of the new vector.\n\t * @param length\n\t * The length of the new vector.\n\t */\n\tpublic void setPolar(double angle, double length);\n\n\t/**\n\t * Sets the values of this {@link Vector} to the given rectangular\n\t * coordinates.\n\t * \n\t * @param vx\n\t * The x component of the new vector.\n\t * @param vy\n\t * The y component of the new vector.\n\t */\n\tpublic void setRect(double vx, double vy);\n\n\t/**\n\t * Sets the values of this <code>Vector</code> to the values of another\n\t * <code>Vector</code>. Does not guarantee equality.\n\t * \n\t * @param v\n\t * The new values for this <code>Vector</code>.\n\t */\n\tpublic void setVector(Vector v);\n\n\t/**\n\t * Sets the x component.\n\t * \n\t * @param vx\n\t * The new x component.\n\t */\n\tpublic void setvx(double vx);\n\n\t/**\n\t * Sets the y component.\n\t * \n\t * @param vy\n\t * The new y component.\n\t */\n\tpublic void setvy(double vy);\n}" ]
import java.awt.Color; import forceengine.graphics.Colored; import forceengine.math.CircleMath; import forceengine.objects.Circle; import forceengine.objects.ForceCircle; import forceengine.objects.Point; import forceengine.objects.PointVector; import forceengine.objects.RectVector; import forceengine.objects.Vector;
package forceengine.demo.objects; public class Gel extends ForceCircle implements Colored { public static final Color color = new Color(26, 141, 240, 100); public Gel(double x, double y, double vx, double vy, double radius, double mass, double restitution) { super(x, y, vx, vy, radius, mass, restitution); } @Override public boolean isCollide(Object o) { if (o instanceof ForceCircle) return false; return true; } public boolean isResponsive(Object o) { return true; }
public Vector responsiveAcceleration(PointVector pv, double t, Point b) {
5
TU-Berlin-SNET/JCPABE
src/main/java/cpabe/bsw07/policy/Bsw07PolicyParentNode.java
[ "public class AbeDecryptionException extends GeneralSecurityException {\n\n private static final long serialVersionUID = 2848983353356933397L;\n\n public AbeDecryptionException(String msg) {\n super(msg);\n }\n\n public AbeDecryptionException(String msg, Throwable t) {\n super(msg, t);\n }\n}", "public class AbeOutputStream extends DataOutputStream {\n\n private AbePublicKey pubKey;\n\n public AbeOutputStream(OutputStream out, AbePublicKey pubKey) {\n super(out);\n this.pubKey = pubKey;\n }\n\n // only used for the curve parameters and attributes, no need for fancy encodings\n public void writeString(String string) throws IOException {\n byte[] bytes = string.getBytes(AbeSettings.STRINGS_LOCALE);\n writeInt(bytes.length);\n write(bytes);\n }\n\n public void writeElement(Element elem) throws IOException {\n writeInt(pubKey.getPairing().getFieldIndex(elem.getField()));\n byte[] bytes = elem.toBytes();\n writeInt(bytes.length);\n write(bytes);\n }\n\n}", "public class AbePrivateKey {\n /*\n * A private key\n */\n /**\n * G2\n **/\n Element d;\n ArrayList<Bsw07PrivateKeyComponent> components;\n AbePublicKey pubKey;\n\n public AbePrivateKey(Element d, ArrayList<Bsw07PrivateKeyComponent> components, AbePublicKey pubKey) {\n this.d = d;\n this.components = components;\n this.pubKey = pubKey;\n }\n\n public static AbePrivateKey readFromFile(File file) throws IOException {\n try (FileInputStream fis = new FileInputStream(file)) {\n return readFromStream(fis);\n }\n }\n\n public static AbePrivateKey readFromStream(InputStream stream) throws IOException {\n AbeInputStream abeStream = new AbeInputStream(stream);\n AbePublicKey pubKey = AbePublicKey.readFromStream(abeStream);\n abeStream.setPublicKey(pubKey);\n Element d = abeStream.readElement();\n int compsLength = abeStream.readInt();\n ArrayList<Bsw07PrivateKeyComponent> components = new ArrayList<Bsw07PrivateKeyComponent>(compsLength);\n\n for (int i = 0; i < compsLength; i++) {\n components.add(Bsw07PrivateKeyComponent.readFromStream(abeStream));\n }\n return new AbePrivateKey(d, components, pubKey);\n }\n\n public AbePublicKey getPublicKey() {\n return pubKey;\n }\n\n /**\n * @return a new privatekey, where d and the component list has been duplicated. The list elements have NOT been duplicated.\n */\n public AbePrivateKey duplicate() {\n ArrayList<Bsw07PrivateKeyComponent> duplicatedComponents = new ArrayList<Bsw07PrivateKeyComponent>(components.size());\n for (Bsw07PrivateKeyComponent cur : components) {\n // should each component also be duplicated? only necessary if components are altered somewhere, which they are not\n duplicatedComponents.add(cur);\n }\n return new AbePrivateKey(d.duplicate(), duplicatedComponents, pubKey);\n }\n\n public Element getD() {\n return d;\n }\n\n public List<Bsw07PrivateKeyComponent> getComponents() {\n return components;\n }\n\n public Bsw07PrivateKeyComponent getSatisfyingComponent(Element hashedAttribute) {\n for (int i = 0; i < components.size(); i++) {\n Bsw07PrivateKeyComponent component = components.get(i);\n if (component.hashedAttribute.isEqual(hashedAttribute)) {\n return component;\n }\n }\n return null;\n }\n\n public AbePrivateKey newKeyWithAddedAttributes(List<Bsw07PrivateKeyComponent> newComponents) {\n AbePrivateKey newKey = this.duplicate();\n newKey.components.addAll(newComponents);\n return newKey;\n }\n\n public void writeToStream(OutputStream stream) throws IOException {\n AbeOutputStream abeStream = new AbeOutputStream(stream, pubKey);\n pubKey.writeToStream(abeStream);\n abeStream.writeElement(d);\n int compsLength = components.size();\n abeStream.writeInt(compsLength);\n for (Bsw07PrivateKeyComponent component : components) {\n component.writeToStream(abeStream);\n }\n }\n\n public void writeToFile(File file) throws IOException {\n try (FileOutputStream fos = new FileOutputStream(file)) {\n writeToStream(fos);\n }\n }\n}", "public class AbePublicKey {\n /**\n * G_1\n **/\n public Element g;\n /**\n * G_1\n **/\n public Element h;\n /**\n * G_1\n **/\n public Element f;\n /**\n * G_T\n **/\n public Element e_g_g_hat_alpha;\n /*\n * A public key\n */\n private String pairingDesc;\n private transient Pairing p;\n\n /**\n * Creates a new AbePublicKey. This key should only be used after the elements have been set (setElements).\n *\n * @param pairingDescription\n */\n public AbePublicKey(String pairingDescription) {\n this.pairingDesc = pairingDescription;\n }\n\n public static AbePublicKey readFromFile(File file) throws IOException {\n try (AbeInputStream stream = new AbeInputStream(new FileInputStream(file))) {\n return readFromStream(stream);\n }\n }\n\n public static AbePublicKey readFromStream(AbeInputStream stream) throws IOException {\n String pairingDescription = stream.readString();\n AbePublicKey publicKey = new AbePublicKey(pairingDescription);\n stream.setPublicKey(publicKey);\n publicKey.g = stream.readElement();\n publicKey.h = stream.readElement();\n publicKey.f = stream.readElement();\n publicKey.e_g_g_hat_alpha = stream.readElement();\n return publicKey;\n }\n\n public String getPairingDescription() {\n return pairingDesc;\n }\n\n public Pairing getPairing() {\n if (p == null) {\n PairingParameters params = new PropertiesParameters().load(new ByteArrayInputStream(pairingDesc.getBytes()));\n p = PairingFactory.getPairing(params);\n }\n return p;\n }\n\n public void setElements(Element g, Element h, Element f, Element e_g_g_hat_alpha) {\n this.g = g;\n this.h = h;\n this.f = f;\n this.e_g_g_hat_alpha = e_g_g_hat_alpha;\n }\n\n public void writeToStream(AbeOutputStream stream) throws IOException {\n stream.writeString(pairingDesc);\n stream.writeElement(g);\n stream.writeElement(h);\n stream.writeElement(f);\n stream.writeElement(e_g_g_hat_alpha);\n }\n\n public void writeToFile(File file) throws IOException {\n try (AbeOutputStream fos = new AbeOutputStream(new FileOutputStream(file), this)) {\n writeToStream(fos);\n }\n }\n}", "public class Bsw07Polynomial {\n /* coefficients from [0] x^0 to [deg] x^deg */\n public Element[] coef; /* G_T (of length deg+1) */\n\n private Bsw07Polynomial(int deg) {\n coef = new Element[deg + 1];\n }\n\n /**\n * Generates a new polynomial with random coefficients of the element type given as zeroVal. The 0th coefficient has the same\n * value as zeroVal.\n *\n * @param deg number of coefficients\n * @param zeroVal\n */\n public static Bsw07Polynomial createRandom(int deg, Element zeroVal) {\n Bsw07Polynomial newPoly = new Bsw07Polynomial(deg);\n for (int i = 0; i < newPoly.coef.length; i++)\n newPoly.coef[i] = zeroVal.duplicate();\n\n newPoly.coef[0].set(zeroVal);\n\n for (int i = 1; i < newPoly.coef.length; i++)\n newPoly.coef[i].setToRandom();\n return newPoly;\n }\n\n}" ]
import cpabe.AbeDecryptionException; import cpabe.AbeOutputStream; import cpabe.AbePrivateKey; import cpabe.AbePublicKey; import cpabe.bsw07.Bsw07Polynomial; import it.unisa.dia.gas.jpbc.Element; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List;
package cpabe.bsw07.policy; public class Bsw07PolicyParentNode extends Bsw07PolicyAbstractNode { private int threshold; private ArrayList<Bsw07PolicyAbstractNode> children; private ArrayList<Integer> satl; private Bsw07Polynomial poly; private Integer satisfiableChildrenCount = null; public Bsw07PolicyParentNode(int threshold, int numberOfChildren) { this.threshold = threshold; children = new ArrayList<>(numberOfChildren); } private static Element evalPoly(Bsw07Polynomial q, Element x) { Element r = x.duplicate().setToZero(); Element t = x.duplicate().setToOne(); for (Element coeff : q.coef) { r.add(coeff.duplicate().mul(t)); t.mul(x); } return r; } private static void lagrangeCoef(Element r, ArrayList<Integer> s, int i) { Element t = r.duplicate(); r.setToOne(); for (Integer j : s) { if (j == i) continue; t.set(-j); r.mul(t); /* num_muls++; */ t.set(i - j).invert(); r.mul(t); /* num_muls++; */ } } public boolean addChild(Bsw07PolicyAbstractNode child) { return children.add(child); } public boolean addAllChildren(List<Bsw07PolicyAbstractNode> newChildren) { return children.addAll(newChildren); } public int getThreshold() { return threshold; } public List<Bsw07PolicyAbstractNode> getChildren() { return children; } @Override public void writeToStream(AbeOutputStream stream) throws IOException { stream.writeInt(getThreshold()); stream.writeInt(children.size()); for (Bsw07PolicyAbstractNode child : children) { child.writeToStream(stream); } } @Override
public void fillPolicy(AbePublicKey pub, Element e) {
3
armouroflight/gstreamer1.x-java
src/org/gstreamer/lowlevel/SubtypeMapper.java
[ "public class DurationMessage extends Message {\n private static interface API extends GstMessageAPI {\n Pointer ptr_gst_message_new_duration(GstObject src, Format format, long duration);\n }\n private static final API gst = GstNative.load(API.class);\n \n /**\n * Creates a new Buffering message.\n * @param init internal initialization data.\n */\n public DurationMessage(Initializer init) {\n super(init);\n }\n \n /**\n * Creates a new Buffering message.\n * @param src the object originating the message.\n * @param format the format of the duration\n * @param duration the new duration.\n */\n public DurationMessage(GstObject src, Format format, long duration) {\n this(initializer(gst.ptr_gst_message_new_duration(src, format, duration)));\n }\n \n /**\n * Gets the format of the duration contained in this message.\n * \n * @return the format of the duration.\n */\n public Format getFormat() {\n Format[] fmt = new Format[1];\n gst.gst_message_parse_duration(this, fmt, null);\n return fmt[0];\n }\n \n /**\n * Gets the duration of this message.\n * \n * @return the new duration.\n */\n public long getDuration() {\n long[] duration = { 0 };\n gst.gst_message_parse_duration(this, null, duration);\n return duration[0];\n }\n}", "public class EOSMessage extends Message {\n private static interface API extends GstMessageAPI {\n Pointer ptr_gst_message_new_eos(GstObject src);\n }\n private static final API gst = GstNative.load(API.class);\n \n /**\n * Creates a new eos message.\n * @param init internal initialization data.\n */\n public EOSMessage(Initializer init) {\n super(init);\n }\n \n /**\n * Creates a new eos message.\n * @param src The object originating the message.\n */\n public EOSMessage(GstObject src) {\n this(initializer(gst.ptr_gst_message_new_eos(src)));\n }\n}", "public class InfoMessage extends GErrorMessage {\n private static interface API extends GstMessageAPI {\n }\n private static final API gst = GstNative.load(API.class);\n \n /**\n * Creates a new info message.\n * \n * @param init internal initialization data.\n */\n public InfoMessage(Initializer init) {\n super(init);\n }\n \n /**\n * Retrieves the GError structure contained in this message.\n * \n * @return the GError contained in this message.\n */\n @Override\n GErrorStruct parseMessage() {\n GErrorStruct[] err = { null };\n gst.gst_message_parse_info(this, err, null);\n return err[0];\n }\n}", "public class LatencyMessage extends Message {\n private static interface API extends GstMessageAPI {\n Pointer ptr_gst_message_new_latency(GstObject source);\n }\n private static final API gst = GstNative.load(API.class);\n \n /**\n * Creates a new Latency message.\n * \n * @param init internal initialization data.\n */\n public LatencyMessage(Initializer init) {\n super(init);\n }\n \n /**\n * Creates a new Latency message.\n * \n * @param source the object originating the message.\n */\n public LatencyMessage(GstObject source) {\n this(initializer(gst.ptr_gst_message_new_latency(source)));\n }\n}", "public class PositionQuery extends Query {\n private static interface API extends com.sun.jna.Library { \n /* position query */\n Pointer ptr_gst_query_new_position(Format format);\n void gst_query_set_position(Query query, Format format, /* gint64 */ long cur);\n void gst_query_parse_position(Query query, int[] format, /* gint64 * */ long[] cur);\n }\n private static final API gst = GstNative.load(API.class);\n \n public PositionQuery(Initializer init) {\n super(init);\n }\n \n /**\n * Constructs a new query stream position query object. A position query is \n * used to query the current position of playback in the streams, in some format.\n * \n * @param format the default {@link Format} for the new query\n */\n public PositionQuery(Format format) {\n super(initializer(gst.ptr_gst_query_new_position(format)));\n }\n \n /**\n * Answers a position query by setting the requested value in the given format.\n * \n * @param format the requested {@link Format}\n * @param position the position to set in the answer\n */\n public void setPosition(Format format, long position) {\n gst.gst_query_set_position(this, format, position);\n }\n \n /**\n * Gets the {@link Format} of this position query.\n * \n * @return The format of the query.\n */\n public Format getFormat() {\n int[] fmt = new int[1];\n gst.gst_query_parse_position(this, fmt, null);\n return Format.valueOf(fmt[0]);\n }\n \n /**\n * Gets the position in terms of the {@link Format} of the query.\n * \n * @return the position.\n */\n public long getPosition() {\n long[] pos = new long[1];\n gst.gst_query_parse_position(this, null, pos);\n return pos[0];\n }\n \n /**\n * Gets the position as a user-readable string.\n * \n * @return A string representation of the position.\n */\n @Override\n public String toString() {\n return String.format(\"position: [format=%s, position=%d]\", getFormat(), getPosition());\n }\n}", "public class SegmentQuery extends Query {\n private static interface API extends com.sun.jna.Library {\n Pointer ptr_gst_query_new_segment(Format format);\n void gst_query_set_segment(SegmentQuery query, double rate, Format format,\n /* gint64 */ long start_value, /* gint64 */ long stop_value);\n void gst_query_parse_segment(SegmentQuery query, double[] rate, /*GstFormat **/ int[] format,\n /* gint64 * */ long[] start_value, /* gint64 * */ long[] stop_value);\n\n }\n private static final API gst = GstNative.load(API.class);\n public SegmentQuery(Initializer init) {\n super(init);\n }\n /**\n * Constructs a new segment query object.\n *\n * @param format the {@link Format} for the new query.\n */\n public SegmentQuery(Format format) {\n this(initializer(gst.ptr_gst_query_new_segment(format)));\n }\n \n /**\n * Answers a segment query by setting the requested values. \n * <p>\n * The normal playback segment of a pipeline is 0 to duration at the default rate of\n * 1.0. If a seek was performed on the pipeline to play a different\n * segment, this query will return the range specified in the last seek.\n *\n * {@code startValue} and {@code stopValue} will respectively contain the configured \n * playback range start and stop values expressed in format. \n * The values are always between 0 and the duration of the media and \n * {@code startValue <= stopValue}. {@code rate} will contain the playback rate. For\n * negative rates, playback will actually happen from {@code stopValue} to\n * {@code startValue}.\n * \n * @param rate the rate of the segment.\n * @param format the {@link Format} of the segment values.\n * @param startValue the start value.\n * @param stopValue the stop value.\n */\n public void setSegment(double rate, Format format, long startValue, long stopValue) {\n gst.gst_query_set_segment(this, rate, format, startValue, stopValue);\n }\n \n /**\n * Gets the rate of the segment Query.\n * \n * @return the rate of the segment.\n */\n public double getRate() {\n double[] rate = new double[1];\n gst.gst_query_parse_segment(this, rate, null, null, null);\n return rate[0];\n }\n \n /**\n * Gets the format of the start and stop values in the segment query.\n * \n * @return The format for the start and stop values.\n */\n public Format getFormat() {\n int[] fmt = new int[1];\n gst.gst_query_parse_segment(this, null, fmt, null, null);\n return Format.valueOf(fmt[0]);\n }\n \n /**\n * Gets the start of the playback range.\n * \n * @return the start of the playback range.\n */\n public long getStart() {\n long[] value = new long[1];\n gst.gst_query_parse_segment(this, null, null, value, null);\n return value[0];\n }\n \n /**\n * Gets the end of the playback range.\n * \n * @return the end of the playback range.\n */\n public long getEnd() {\n long[] value = new long[1];\n gst.gst_query_parse_segment(this, null, null, null, value);\n return value[0];\n }\n}" ]
import java.util.HashMap; import java.util.Map; import org.gstreamer.Event; import org.gstreamer.EventType; import org.gstreamer.Message; import org.gstreamer.MessageType; import org.gstreamer.Query; import org.gstreamer.QueryType; import org.gstreamer.event.BufferSizeEvent; import org.gstreamer.event.EOSEvent; import org.gstreamer.event.FlushStartEvent; import org.gstreamer.event.FlushStopEvent; import org.gstreamer.event.LatencyEvent; import org.gstreamer.event.NavigationEvent; import org.gstreamer.event.NewSegmentEvent; import org.gstreamer.event.QOSEvent; import org.gstreamer.event.SeekEvent; import org.gstreamer.event.TagEvent; import org.gstreamer.message.BufferingMessage; import org.gstreamer.message.DurationMessage; import org.gstreamer.message.EOSMessage; import org.gstreamer.message.ErrorMessage; import org.gstreamer.message.InfoMessage; import org.gstreamer.message.LatencyMessage; import org.gstreamer.message.SegmentDoneMessage; import org.gstreamer.message.StateChangedMessage; import org.gstreamer.message.TagMessage; import org.gstreamer.message.WarningMessage; import org.gstreamer.query.ConvertQuery; import org.gstreamer.query.DurationQuery; import org.gstreamer.query.FormatsQuery; import org.gstreamer.query.LatencyQuery; import org.gstreamer.query.PositionQuery; import org.gstreamer.query.SeekingQuery; import org.gstreamer.query.SegmentQuery; import com.sun.jna.Pointer;
/* * Copyright (c) 2008 Wayne Meissner * * This file is part of gstreamer-java. * * This code is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * version 3 for more details. * * You should have received a copy of the GNU Lesser General Public License * version 3 along with this work. If not, see <http://www.gnu.org/licenses/>. */ package org.gstreamer.lowlevel; /** * Mapper for classes which have subtypes (e.g. Event, Message, Query). * <p> * This class will return the subtype of the super class that best matches the * raw pointer passed in. */ @SuppressWarnings("serial") class SubtypeMapper { static <T extends NativeObject> Class<?> subtypeFor(final Class<T> defaultClass, final Pointer ptr) { Mapper mapper = MapHolder.mappers.get(defaultClass); Class<?> cls = mapper != null ? mapper.subtypeFor(ptr) : null; return cls != null ? cls : defaultClass; } private static final class MapHolder { public static final Map<Class<?>, Mapper> mappers = new HashMap<Class<?>, Mapper>() {{ put(Event.class, new EventMapper()); put(Message.class, new MessageMapper()); put(Query.class, new QueryMapper()); }}; } private static interface Mapper { public Class<? extends NativeObject> subtypeFor(Pointer ptr); } private static class EventMapper implements Mapper { static class MapHolder { private static final Map<EventType, Class<? extends Event>> typeMap = new HashMap<EventType, Class<? extends Event>>() {{ put(EventType.BUFFERSIZE, BufferSizeEvent.class); put(EventType.EOS, EOSEvent.class); put(EventType.LATENCY, LatencyEvent.class); put(EventType.FLUSH_START, FlushStartEvent.class); put(EventType.FLUSH_STOP, FlushStopEvent.class); put(EventType.NAVIGATION, NavigationEvent.class); put(EventType.NEWSEGMENT, NewSegmentEvent.class); put(EventType.SEEK, SeekEvent.class); put(EventType.TAG, TagEvent.class); put(EventType.QOS, QOSEvent.class); }}; public static Class<? extends NativeObject> subtypeFor(Pointer ptr) { GstEventAPI.EventStruct struct = new GstEventAPI.EventStruct(ptr); EventType type = EventType.valueOf((Integer) struct.readField("type")); Class<? extends Event> eventClass = MapHolder.typeMap.get(type); return eventClass != null ? eventClass : Event.class; } } public Class<? extends NativeObject> subtypeFor(Pointer ptr) { return MapHolder.subtypeFor(ptr); } } private static class MessageMapper implements Mapper { static class MapHolder { private static final Map<MessageType, Class<? extends Message>> typeMap = new HashMap<MessageType, Class<? extends Message>>() {{ put(MessageType.EOS, EOSMessage.class); put(MessageType.ERROR, ErrorMessage.class); put(MessageType.BUFFERING, BufferingMessage.class); put(MessageType.DURATION, DurationMessage.class); put(MessageType.INFO, InfoMessage.class); put(MessageType.LATENCY, LatencyMessage.class); put(MessageType.SEGMENT_DONE, SegmentDoneMessage.class); put(MessageType.STATE_CHANGED, StateChangedMessage.class); put(MessageType.TAG, TagMessage.class); put(MessageType.WARNING, WarningMessage.class); }}; public static Class<? extends NativeObject> subtypeFor(Pointer ptr) { GstMessageAPI.MessageStruct struct = new GstMessageAPI.MessageStruct(ptr); MessageType type = (MessageType) struct.readField("type"); Class<? extends Message> messageClass = MapHolder.typeMap.get(type); return messageClass != null ? messageClass : Message.class; } } public Class<? extends NativeObject> subtypeFor(Pointer ptr) { return MapHolder.subtypeFor(ptr); } } private static class QueryMapper implements Mapper { static class MapHolder { private static final Map<QueryType, Class<? extends Query>> typeMap = new HashMap<QueryType, Class<? extends Query>>() {{ put(QueryType.CONVERT, ConvertQuery.class); put(QueryType.DURATION, DurationQuery.class); put(QueryType.FORMATS, FormatsQuery.class); put(QueryType.LATENCY, LatencyQuery.class);
put(QueryType.POSITION, PositionQuery.class);
4
sTorro/triviazo
src/com/torrosoft/triviazo/screens/GameScreen.java
[ "public class TriviazoGame extends Game {\n public static final String VERSION = \" - v0.7 ALPHA - \";\n public static final boolean DEBUG_MODE = false;\n public static final boolean FULL_DEBUG_MODE = false;\n\n /* SERVICES */\n private MusicManager musicManager;\n private SoundManager soundManager;\n private PreferencesManager preferencesManager;\n\n /**\n * The game database.\n */\n private Database database;\n\n /**\n * Default constructor.\n */\n public TriviazoGame(final Database pDatabase) {\n setDatabase(pDatabase);\n }\n\n /**\n * Fired once when the application is created.\n */\n @Override\n public final void create() {\n preferencesManager = new PreferencesManager();\n\n musicManager = new MusicManager();\n musicManager.setVolume(preferencesManager.getVolume());\n musicManager.setEnabled(preferencesManager.isMusicEnabled());\n\n soundManager = new SoundManager();\n soundManager.setVolume(preferencesManager.getVolume());\n soundManager.setEnabled(preferencesManager.isSoundEnabled());\n\n // Mouse hidden\n Gdx.input.setCursorCatched(false);\n }\n\n /**\n * Fired every time the game screen is re-sized and the game is not in the\n * paused state. It is also fired once just after the create event.\n */\n @Override\n public final void resize(final int width, final int height) {\n super.resize(width, height);\n if (getScreen() == null) {\n if (DEBUG_MODE) {\n setScreen(new MenuScreen(this));\n } else setScreen(new SplashScreen(this)); // new SplashScreen(this)\n }\n }\n\n /**\n * Fired when the application is being destroyed. It is preceded by the\n * pause event.\n */\n @Override\n public final void dispose() {\n super.dispose();\n // It's necessary dispose some native methods.\n musicManager.dispose();\n soundManager.dispose();\n }\n\n /**\n * Fired just before the application is destroyed. On Android it happens\n * when the home button is pressed or an incoming call is happening. On\n * desktop it's fired just before disposal when exiting the application.\n * This a good time to save the game state on Android as it is not\n * guaranteed to be resumed.\n */\n @Override\n public final void pause() {\n super.pause();\n }\n\n /**\n * Fired ONLY on Android, when the application receives the focus.\n */\n @Override\n public final void resume() {\n super.resume();\n }\n\n /**\n * Fired by the game loop from the application every time the rendering\n * happens. The game update should take place before the actual rendering.\n */\n @Override\n public final void render() {\n super.render();\n }\n\n /**\n * Switch between the different screens.\n */\n @Override\n public final void setScreen(final Screen screen) {\n super.setScreen(screen);\n }\n\n public final PreferencesManager getPreferencesManager() {\n return preferencesManager;\n }\n\n public final void setPreferencesManager(\n final PreferencesManager pPreferencesManager) {\n preferencesManager = pPreferencesManager;\n }\n\n public final SoundManager getSoundManager() {\n return soundManager;\n }\n\n public final void setSoundManager(final SoundManager pSoundManager) {\n soundManager = pSoundManager;\n }\n\n public final MusicManager getMusicManager() {\n return musicManager;\n }\n\n public final void setMusicManager(final MusicManager pMusicManager) {\n musicManager = pMusicManager;\n }\n\n public final Database getDatabase() {\n return database;\n }\n\n public final void setDatabase(final Database pDatabase) {\n database = pDatabase;\n }\n}", "public class Question {\n public static final int MAX_ANSWERS = 4;\n\n private String pkid;\n private String statement;\n private String[] answers = new String[MAX_ANSWERS];\n private Integer right; // < MAX_ANSWERS\n private Language lang = Language.es_ES;\n private Difficulty difficulty;\n private Discipline discipline;\n\n public Question(final Question question) {\n setPkid(question.getPkid());\n setStatement(question.getStatement());\n setAnswers(question.getAnswers());\n setRight(question.getRight());\n setLang(question.getLang());\n setDifficulty(question.getDifficulty());\n setDiscipline(question.getDiscipline());\n }\n\n public Question(final String pkid, final String statement,\n final String[] answers, final int right, final Language lang,\n final Difficulty difficulty, final Discipline discipline) {\n setPkid(pkid);\n setStatement(statement);\n setAnswers(answers);\n setRight(right);\n setLang(lang);\n setDifficulty(difficulty);\n setDiscipline(discipline);\n }\n\n public Question(final String pkid, final String statement,\n final Language lang, final Difficulty difficulty,\n final Discipline discipline) {\n setPkid(pkid);\n setStatement(statement);\n setLang(lang);\n setDifficulty(difficulty);\n setDiscipline(discipline);\n }\n\n public String[] getAnswers() {\n return answers;\n }\n\n public Language getLang() {\n return lang;\n }\n\n public int getRight() {\n return right;\n }\n\n public String getStatement() {\n return statement;\n }\n\n public void setAnswers(final String[] answers) {\n this.answers = answers;\n }\n\n public void setLang(final Language lang) {\n this.lang = lang;\n }\n\n public void setRight(int right) {\n if ((right > MAX_ANSWERS) || (right < 0)) right = 0;\n this.right = right;\n }\n\n public void setStatement(final String statement) {\n this.statement = statement;\n }\n\n public Difficulty getDifficulty() {\n return difficulty;\n }\n\n public void setDifficulty(final Difficulty difficulty) {\n this.difficulty = difficulty;\n }\n\n public Discipline getDiscipline() {\n return discipline;\n }\n\n public void setDiscipline(final Discipline discipline) {\n this.discipline = discipline;\n }\n\n public String getPkid() {\n return pkid;\n }\n\n public void setPkid(final String pkid) {\n this.pkid = pkid;\n }\n}", "public enum Difficulty {\n EASY(\"Easy\"),\n NORMAL(\"Normal\"),\n HARD(\"Hard\"),\n INSANE(\"Insane\"), // Only used for IA\n ALL(\"All\"); // Only used for questions\n\n private String name;\n\n private Difficulty(final String name) {\n setName(name);\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(final String name) {\n this.name = name;\n }\n\n public static Difficulty getDifficultyByName(final String name) {\n Difficulty res = null;\n for (final Difficulty d : Difficulty.values()) {\n if (d.getName().equals(name)) {\n res = d;\n break;\n }\n }\n\n return res;\n }\n}", "public enum Discipline {\n HISTORY(\"History\"),\n GEOGRAPHY(\"Geography\"),\n POLITICS(\"Politics\"),\n TECNOLOGY(\"Technology\"),\n PHYSICS(\"Physics\"),\n CHEMISTRY(\"Chemistry\"),\n LITERATURE(\"Literature\"),\n MUSIC(\"Music\"),\n ART(\"Art\");\n\n private String name;\n\n private Discipline(final String name) {\n setName(name);\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(final String name) {\n this.name = name;\n }\n\n public static Discipline getDisciplineByName(final String name) {\n Discipline res = null;\n for (final Discipline d : Discipline.values()) {\n if (d.getName().equals(name)) {\n res = d;\n break;\n }\n }\n\n return res;\n }\n}", "public enum GameMode {\n INTELLECTUS_MACHINA(\"Intellectus machina\", \"images/machina_back.png\", \"machina\"),\n TEMPUS_FUGIT(\"Tempus fugit\", \"images/tempus_back.png\", \"tempus\"),\n VINDICETIS_EX_SIMIUS(\"Vindicetis ex simius\", \"images/simius_back.png\", \"simius\");\n\n private String name;\n private String textImg;\n private String dbName;\n\n private GameMode(final String name, final String textImg, final String dbName) {\n setName(name);\n setTextImg(textImg);\n setDbName(dbName);\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(final String name) {\n this.name = name;\n }\n\n public String getTextImg() {\n return textImg;\n }\n\n public void setTextImg(final String textImg) {\n this.textImg = textImg;\n }\n\n @Override\n public String toString() {\n return name;\n }\n\n public String getDbName() {\n return dbName;\n }\n\n public void setDbName(final String dbName) {\n this.dbName = dbName;\n }\n}", "public enum Language {\n es_ES(\"Spanish\"),\n en_GB(\"English\"),\n fr_FR(\"French\"),\n de_DE(\"German\");\n\n private String name;\n\n private Language(final String name) {\n setName(name);\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(final String name) {\n this.name = name;\n }\n\n public static Language getLanguageByName(final String name) {\n Language res = null;\n for (final Language lang : Language.values()) {\n if (lang.getName().equals(name)) {\n res = lang;\n break;\n }\n }\n return res;\n }\n}", "public enum TriviazoMusic {\n /**\n * Creative Commons License: http://ccmixter.org/files/flatwound/14476\n */\n MAIN(\"music/game_music_main.mp3\"),\n /**\n * Creative Commons License: http://ccmixter.org/files/duncan_beattie/7116\n */\n IN_GAME(\"music/game_music_ii.mp3\"),\n /**\n * Creative Commons License: http://freemusicarchive.org/music/The_Insider/\n */\n TENSION_IS_RISING(\"music/tension_is_rising.mp3\");\n\n private String fileName;\n private Music musicResource;\n\n private TriviazoMusic(final String pFileName) {\n fileName = pFileName;\n }\n\n public String getFileName() {\n return fileName;\n }\n\n public Music getMusicResource() {\n return musicResource;\n }\n\n public void setMusicResource(final Music musicBeingPlayed) {\n musicResource = musicBeingPlayed;\n }\n}", "public enum TriviazoSound {\n CLICK(\"sounds/click.wav\"),\n TICK(\"sounds/tick.wav\"),\n CHIMP(\"sounds/chimp.wav\");\n\n private final String fileName;\n\n private TriviazoSound(final String pFileName) {\n fileName = pFileName;\n }\n\n public String getFileName() {\n return fileName;\n }\n}", "public abstract class DefaultButtonListener extends InputListener {\n /**\n * This method have to return true for a correct working.\n */\n @Override\n public final boolean touchDown(final InputEvent event, final float x,\n final float y,\n final int pointer, final int button) {\n return true;\n }\n}" ]
import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.utils.Drawable; import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable; import com.torrosoft.triviazo.TriviazoGame; import com.torrosoft.triviazo.core.data.wrappers.Question; import com.torrosoft.triviazo.core.enums.Difficulty; import com.torrosoft.triviazo.core.enums.Discipline; import com.torrosoft.triviazo.core.enums.GameMode; import com.torrosoft.triviazo.core.enums.Language; import com.torrosoft.triviazo.services.music.TriviazoMusic; import com.torrosoft.triviazo.services.music.TriviazoSound; import com.torrosoft.triviazo.util.DefaultButtonListener;
/* * This file is part of Triviazo project. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 3 of the License, or (at your * option) any later version. This program is distributed in the hope that * it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with triviazo-project. If not, see <http://www.gnu.org/licenses/>. * * Copyright 2013 Sergio Torró. */ package com.torrosoft.triviazo.screens; /** * Abstract class witch defines the default behavior of the game screen. * * @author Sergio Torró * @since 04/06/2013 * @version 0.3 */ public abstract class GameScreen extends AbstractScreen { private static final int BUTTON_SIZE_MOD = 60; protected static final int QUESTION_VALUE = 50; /** * The main skin used by all the UI components. */ protected final Skin mainSkin; /** * The questions of the current game. */ protected final List<Question> questions = new ArrayList<Question>(); /** * The current index of the list. */ protected int index = 0; protected int correct = 0; protected int incorrect = 0; /** * The main table of the super class. */ private Table mainTable; private Label lblQuestion; private TextButton btnAns1; private TextButton btnAns2; private TextButton btnAns3; private TextButton btnAns4; protected Label lblCorrect; protected Label lblIncorrect; protected Label lblTimer; protected int maxQuestions; public GameScreen(final TriviazoGame game) { super(game); game.getMusicManager().play(TriviazoMusic.IN_GAME); mainSkin = super.getSkin(); } /** * The method for show the UI. It handles the main {@link Table}. */ @Override public final void show() { super.show(); mainTable = super.getTable(); final Texture texture = new Texture( Gdx.files.internal("images/default.png")); final Drawable drawable = new TextureRegionDrawable(new TextureRegion( texture)); mainTable.setBackground(drawable); createUI(); createScoreboard(); createTimerTable(); loadQuestions(); nextQuestion(); // Start game } private void createScoreboard() { final Table tableScore = new Table(mainSkin); tableScore.setFillParent(true); lblCorrect = new Label("", mainSkin); lblIncorrect = new Label("", mainSkin); setScore(null); tableScore.add(lblCorrect); tableScore.row(); tableScore.add(lblIncorrect); tableScore.bottom().left().pad(0, 10, 10, 0); stage.addActor(tableScore); } private void createTimerTable() { final Table timerTable = new Table(mainSkin); timerTable.setFillParent(true); lblTimer = new Label("", mainSkin); timerTable.add(lblTimer); timerTable.row(); timerTable.top().right().pad(0, 0, 10, 10); stage.addActor(timerTable); if (gameConfig.getGameMode() == GameMode.INTELLECTUS_MACHINA) lblTimer.setVisible(false); } private void createUI() { final Table tableUI = new Table(mainSkin); tableUI.setFillParent(true); lblQuestion = new Label("", getSkin()); btnAns1 = new TextButton("", getSkin()); btnAns1.setName("0"); btnAns2 = new TextButton("", getSkin()); btnAns2.setName("1"); btnAns3 = new TextButton("", getSkin()); btnAns3.setName("2"); btnAns4 = new TextButton("", getSkin()); btnAns4.setName("3"); btnAns1.addListener(btnListener); btnAns2.addListener(btnListener); btnAns3.addListener(btnListener); btnAns4.addListener(btnListener); tableUI.add(lblQuestion).center().colspan(2); tableUI.row(); tableUI.add("\n\n").colspan(2); tableUI.row(); tableUI.add(btnAns1).size(BUTTON_WIDTH + BUTTON_SIZE_MOD, BUTTON_HEIGHT + BUTTON_SIZE_MOD); tableUI.add(btnAns2).size(BUTTON_WIDTH + BUTTON_SIZE_MOD, BUTTON_HEIGHT + BUTTON_SIZE_MOD); tableUI.row(); tableUI.add(btnAns3).size(BUTTON_WIDTH + BUTTON_SIZE_MOD, BUTTON_HEIGHT + BUTTON_SIZE_MOD); tableUI.add(btnAns4).size(BUTTON_WIDTH + BUTTON_SIZE_MOD, BUTTON_HEIGHT + BUTTON_SIZE_MOD); tableUI.row(); tableUI.add("\n\n").colspan(2); tableUI.row(); tableUI.center(); stage.addActor(tableUI); } /** * It loads all the questions and keeps a certain number of them in * "questions" List (mixed). Never keeps repeated questions. */ private void loadQuestions() {
final List<Discipline> selectedDis = new ArrayList<Discipline>();
3
urbanairship/datacube
src/main/java/com/urbanairship/datacube/idservices/HBaseIdService.java
[ "public interface IdService {\n byte[] getOrCreateId(int dimensionNum, byte[] input, int numIdBytes) throws IOException, InterruptedException;\n\n Optional<byte[]> getId(int dimensionNum, byte[] input, int numIdBytes) throws IOException, InterruptedException;\n\n /**\n * Utilities to make implementation of IdService easier.\n */\n class Validate {\n /**\n * @throws IllegalArgumentException if dimensionNum is ridiculously large or <0.\n */\n public static void validateDimensionNum(int dimensionNum) {\n if (dimensionNum > Short.MAX_VALUE) {\n throw new IllegalArgumentException(\"More than \" + Short.MAX_VALUE +\n \" dimensions are not supported, saw \" + dimensionNum);\n } else if (dimensionNum < 0) {\n throw new IllegalArgumentException(\"dimensionNum should be non-negative, saw \" +\n dimensionNum);\n }\n }\n\n public static void validateNumIdBytes(int numIdBytes) {\n if (numIdBytes <= 0 || numIdBytes > 7) {\n throw new IllegalArgumentException(\"Strange numIdBytes key \" + numIdBytes);\n }\n }\n }\n}", "public class Util {\n public static byte[] longToBytes(long l) {\n return ByteBuffer.allocate(8).putLong(l).array();\n }\n\n /**\n * Write a big-endian integer into the least significant bytes of a byte array.\n */\n public static byte[] intToBytesWithLen(int x, int len) {\n if(len <= 4) {\n return trailingBytes(intToBytes(x), len);\n } else {\n ByteBuffer bb = ByteBuffer.allocate(len);\n bb.position(len-4);\n bb.putInt(x);\n assert bb.remaining() == 0;\n return bb.array();\n }\n }\n\n public static long bytesToLong(byte[] bytes) {\n if(bytes.length < 8) {\n throw new IllegalArgumentException(\"Input array was too small: \" +\n Arrays.toString(bytes));\n }\n \n return ByteBuffer.wrap(bytes).getLong();\n }\n \n /**\n * Call this if you have a byte array to convert to long, but your array might need\n * to be left-padded with zeros (if it is less than 8 bytes long). \n */\n public static long bytesToLongPad(byte[] bytes) {\n final int padZeros = Math.max(8-bytes.length, 0);\n ByteBuffer bb = ByteBuffer.allocate(8);\n for(int i=0; i<padZeros; i++) {\n bb.put((byte)0);\n }\n bb.put(bytes, 0, 8-padZeros);\n bb.flip();\n return bb.getLong();\n }\n \n public static byte[] intToBytes(int x) {\n ByteBuffer bb = ByteBuffer.allocate(4);\n bb.putInt(x);\n return bb.array();\n }\n\n public static int bytesToInt(byte[] bytes) {\n return ByteBuffer.wrap(bytes).getInt();\n }\n\n public static byte[] leastSignificantBytes(long l, int numBytes) {\n byte[] all8Bytes = Util.longToBytes(l);\n return trailingBytes(all8Bytes, numBytes);\n }\n\n public static byte[] trailingBytes(byte[] bs, int numBytes) {\n return Arrays.copyOfRange(bs, bs.length-numBytes, bs.length);\n }\n\n /**\n * A utility to allow hashing of a portion of an array without having to copy it.\n * @param array\n * @param startInclusive\n * @param endExclusive\n * @return hash byte\n */\n public static byte hashByteArray(byte[] array, int startInclusive, int endExclusive) {\n if (array == null) {\n return 0;\n }\n\n int range = endExclusive - startInclusive;\n if (range < 0) {\n throw new IllegalArgumentException(startInclusive + \" > \" + endExclusive);\n }\n\n int result = 1;\n for (int i=startInclusive; i<endExclusive; i++){\n result = 31 * result + array[i];\n }\n\n return (byte)result;\n }\n \n /**\n * Only use this for testing/debugging. Inefficient.\n */\n public static long countRows(Configuration conf, byte[] tableName) throws IOException {\n HTable hTable = null;\n ResultScanner rs = null;\n long count = 0;\n try {\n hTable = new HTable(conf, tableName);\n rs = hTable.getScanner(new Scan());\n for(@SuppressWarnings(\"unused\") Result r: rs) {\n count++;\n }\n return count;\n } finally {\n if(hTable != null) {\n hTable.close();\n }\n if(rs != null) {\n rs.close();\n }\n }\n }\n}", "public class WithHTable {\n\n /**\n * Take an htable from the pool, use it with the given HTableRunnable, and return it to\n * the pool. This is the \"loan pattern\" where the htable resource is used temporarily by\n * the runnable.\n */\n public static <T> T run(HTablePool pool, byte[] tableName, HTableRunnable<T> runnable)\n throws IOException {\n HTableInterface hTable = null;\n try {\n hTable = pool.getTable(tableName);\n return runnable.runWith(hTable);\n } catch (Exception e) {\n if (e instanceof IOException) {\n throw (IOException) e;\n } else {\n throw new RuntimeException(e);\n }\n } finally {\n if (hTable != null) {\n pool.putTable(hTable);\n }\n }\n }\n\n public interface HTableRunnable<T> {\n T runWith(HTableInterface hTable) throws IOException;\n }\n\n /**\n * Do an HBase put and return null.\n *\n * @throws IOException if the underlying HBase operation throws an IOException\n */\n public static void put(HTablePool pool, byte[] tableName, final Put put) throws IOException {\n run(pool, tableName, new HTableRunnable<Object>() {\n @Override\n public Object runWith(HTableInterface hTable) throws IOException {\n hTable.put(put);\n return null;\n }\n });\n }\n\n public static Result get(HTablePool pool, byte[] tableName, final Get get) throws IOException {\n return run(pool, tableName, new HTableRunnable<Result>() {\n @Override\n public Result runWith(HTableInterface hTable) throws IOException {\n return hTable.get(get);\n }\n });\n }\n\n public static long increment(HTablePool pool, byte[] tableName, final byte[] row,\n final byte[] cf, final byte[] qual, final long amount) throws IOException {\n return run(pool, tableName, new HTableRunnable<Long>() {\n @Override\n public Long runWith(HTableInterface hTable) throws IOException {\n return hTable.incrementColumnValue(row, cf, qual, amount);\n }\n });\n }\n\n public static boolean checkAndPut(HTablePool pool, byte[] tableName, final byte[] row,\n final byte[] cf, final byte[] qual, final byte[] value, final Put put)\n throws IOException {\n return run(pool, tableName, new HTableRunnable<Boolean>() {\n @Override\n public Boolean runWith(HTableInterface hTable) throws IOException {\n return hTable.checkAndPut(row, cf, qual, value, put);\n }\n });\n }\n\n public static boolean checkAndDelete(HTablePool pool, byte[] tableName, final byte[] row,\n final byte[] cf, final byte[] qual, final byte[] value, final Delete delete)\n throws IOException {\n return run(pool, tableName, new HTableRunnable<Boolean>() {\n @Override\n public Boolean runWith(HTableInterface hTable) throws IOException {\n return hTable.checkAndDelete(row, cf, qual, value, delete);\n }\n });\n }\n\n static class WrappedInterruptedException extends RuntimeException {\n private static final long serialVersionUID = 1L;\n public final InterruptedException wrappedException;\n\n public WrappedInterruptedException(InterruptedException ie) {\n this.wrappedException = ie;\n }\n }\n\n public static Object[] batch(HTablePool pool, byte[] tableName, final List<Row> actions)\n throws IOException, InterruptedException {\n try {\n return run(pool, tableName, new HTableRunnable<Object[]>() {\n @Override\n public Object[] runWith(HTableInterface hTable) throws IOException {\n try {\n return hTable.batch(actions);\n } catch (InterruptedException e) {\n throw new WrappedInterruptedException(e);\n }\n }\n });\n } catch (WrappedInterruptedException e) {\n throw e.wrappedException;\n }\n }\n\n public static Result[] get(HTablePool pool, byte[] tableName, final List<Get> gets)\n throws IOException {\n return run(pool, tableName, new HTableRunnable<Result[]>() {\n @Override\n public Result[] runWith(HTableInterface hTable) throws IOException {\n return hTable.get(gets);\n }\n });\n }\n\n public interface ScanRunnable<T> {\n T run(ResultScanner rs) throws IOException;\n }\n\n public static <T> T scan(HTablePool pool, byte[] tableName, final Scan scan,\n final ScanRunnable<T> scanRunnable) throws IOException {\n return run(pool, tableName, new HTableRunnable<T>() {\n @Override\n public T runWith(HTableInterface hTable) throws IOException {\n ResultScanner rs = null;\n try {\n rs = hTable.getScanner(scan);\n return scanRunnable.run(rs);\n } finally {\n if (rs != null) {\n rs.close();\n }\n }\n }\n });\n }\n}", "public interface ScanRunnable<T> {\n T run(ResultScanner rs) throws IOException;\n}", "public final class Metrics {\n\n private Metrics() {\n //no instances\n }\n\n private static final MetricRegistry registry = new MetricRegistry();\n\n //UA default is to use MS for durations and rates so we configure that here\n //The reporter can be accessed or the registry can be reported on using\n //another\n\n private static final JmxReporter reporter = JmxReporter.forRegistry(registry)\n .convertDurationsTo(TimeUnit.MILLISECONDS)\n .convertRatesTo(TimeUnit.SECONDS)\n .createsObjectNamesWith(new ObjectNameFactoryImpl())\n .build();\n\n static {\n reporter.start();\n }\n\n public static MetricRegistry getRegistry() {\n return registry;\n }\n\n public static JmxReporter getReporter() {\n return reporter;\n }\n\n public static MetricNameDetails name(Class clazz, String name) {\n return MetricNameDetails.newBuilder()\n .setGroup(clazz.getPackage() == null ? \"\" : clazz.getPackage().getName())\n .setType(clazz.getSimpleName().replaceAll(\"\\\\$$\", \"\"))\n .setName(name)\n .build();\n }\n\n public static MetricNameDetails name(Class clazz, String name, String scope) {\n return MetricNameDetails.newBuilder()\n .setGroup(clazz.getPackage() == null ? \"\" : clazz.getPackage().getName())\n .setType(clazz.getSimpleName().replaceAll(\"\\\\$$\", \"\"))\n .setName(name)\n .setScope(scope)\n .build();\n }\n\n public static MetricNameDetails name(String group, String type, String name) {\n return MetricNameDetails.newBuilder()\n .setGroup(group)\n .setType(type)\n .setName(name)\n .build();\n }\n\n public static Meter meter(MetricNameDetails nameDetails) {\n return registry.meter(nameDetails.getFormattedJmxName());\n }\n\n public static Meter meter(Class clazz, String name) {\n return meter(name(clazz, name));\n }\n\n public static Meter meter(Class clazz, String name, String scope) {\n return meter(name(clazz, name, scope));\n }\n\n public static Counter counter(MetricNameDetails nameDetails) {\n return registry.counter(nameDetails.getFormattedJmxName());\n }\n\n public static Counter counter(Class clazz, String name) {\n return counter(name(clazz, name));\n }\n\n public static Counter counter(Class clazz, String name, String scope) {\n return counter(name(clazz, name, scope));\n }\n\n public static Histogram histogram(MetricNameDetails nameDetails) {\n return registry.histogram(nameDetails.getFormattedJmxName());\n }\n\n public static Histogram histogram(Class clazz, String name) {\n return histogram(name(clazz, name));\n }\n\n public static Histogram histogram(Class clazz, String name, String scope) {\n return histogram(name(clazz, name, scope));\n }\n\n public static Timer timer(MetricNameDetails nameDetails) {\n return registry.timer(nameDetails.getFormattedJmxName());\n }\n\n public static Timer timer(Class clazz, String name) {\n return timer(name(clazz, name));\n }\n\n public static Timer timer(Class clazz, String name, String scope) {\n return timer(name(clazz, name, scope));\n }\n\n public static <T> void gauge(MetricNameDetails nameDetails, Gauge<T> impl) {\n final String newGaugeName = nameDetails.getFormattedJmxName();\n SortedMap<String, Gauge> found = registry.getGauges(new MetricFilter() {\n @Override\n public boolean matches(String name, Metric metric) {\n return newGaugeName.equals(name);\n }\n });\n\n if (found.isEmpty()) {\n registry.register(newGaugeName, impl);\n }\n }\n\n /**\n * This doesn't make a ton of sense given the above but it will\n * likely be cleaner in Java8. Also avoids having to catch an exception\n * in a Gauge implementation.\n */\n public static <T> void gauge(MetricNameDetails nameDetails, final Callable<T> impl) {\n gauge(nameDetails, new Gauge<T>() {\n @Override\n public T getValue() {\n try {\n return impl.call();\n }\n catch (Exception ex) {\n throw new RuntimeException(ex);\n }\n }\n });\n }\n\n public static <T> void gauge(Class clazz, String name, Gauge<T> impl) {\n gauge(name(clazz, name), impl);\n }\n\n public static <T> void gauge(Class clazz, String name, String scope, Gauge<T> impl) {\n gauge(name(clazz, name, scope), impl);\n }\n}" ]
import com.codahale.metrics.Gauge; import com.codahale.metrics.Meter; import com.codahale.metrics.Timer; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import com.google.common.math.LongMath; import com.urbanairship.datacube.IdService; import com.urbanairship.datacube.Util; import com.urbanairship.datacube.dbharnesses.WithHTable; import com.urbanairship.datacube.dbharnesses.WithHTable.ScanRunnable; import com.urbanairship.datacube.metrics.Metrics; import org.apache.commons.codec.binary.Hex; import org.apache.commons.lang.ArrayUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.HTablePool; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.util.Bytes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Collection; import java.util.Map.Entry; import java.util.Optional; import java.util.Set;
/* Copyright 2012 Urban Airship and Contributors */ package com.urbanairship.datacube.idservices; public class HBaseIdService implements IdService { private static final Logger log = LoggerFactory.getLogger(HBaseIdService.class); public static final byte[] QUALIFIER = ArrayUtils.EMPTY_BYTE_ARRAY; public static final int MAX_COMPAT_TRIES = 20; public static final int COMPAT_RETRY_SLEEP = 2000; private enum Status {@Deprecated ALLOCATING, ALLOCATED} // don't change ordinals private static final byte[] ALLOCATED_BYTES = new byte[]{(byte) Status.ALLOCATED.ordinal()}; private static final byte[] NULL_BYTE_ARRAY = null; private final HTablePool pool; private final byte[] counterTable; private final byte[] lookupTable; private final byte[] uniqueCubeName; private final byte[] cf; private final Meter allocatingSleeps; private final Meter wastedIdNumbers; private final Timer idCreationTime; private final Timer idGetTime; private final Set<Integer> dimensionsApproachingExhaustion; public HBaseIdService(Configuration configuration, byte[] lookupTable, byte[] counterTable, byte[] cf, byte[] uniqueCubeName) { this(new HTablePool(configuration, Integer.MAX_VALUE), lookupTable, counterTable, cf, uniqueCubeName); } public HBaseIdService(HTablePool pool, byte[] lookupTable, byte[] counterTable, byte[] cf, byte[] uniqueCubeName) { this.pool = pool; this.lookupTable = lookupTable; this.counterTable = counterTable; this.uniqueCubeName = uniqueCubeName; this.cf = cf; this.dimensionsApproachingExhaustion = Sets.newConcurrentHashSet(); this.allocatingSleeps = Metrics.meter(HBaseIdService.class, "ALLOCATING_sleeps", Bytes.toString(uniqueCubeName)); this.wastedIdNumbers = Metrics.meter(HBaseIdService.class, "wasted_id_numbers", Bytes.toString(uniqueCubeName)); this.idCreationTime = Metrics.timer(HBaseIdService.class, "id_create", Bytes.toString(uniqueCubeName)); this.idGetTime = Metrics.timer(HBaseIdService.class, "id_get", Bytes.toString(uniqueCubeName)); Metrics.gauge(HBaseIdService.class, "ids_approaching_exhaustion", Bytes.toString(uniqueCubeName), new Gauge<String>() { @Override public String getValue() { return dimensionsApproachingExhaustion.toString(); } }); } @Override public byte[] getOrCreateId(int dimensionNum, byte[] input, int numIdBytes) throws IOException, InterruptedException { Validate.validateDimensionNum(dimensionNum); Validate.validateNumIdBytes(numIdBytes); // First check if the ID exists already final byte[] lookupKey = makeLookupKey(dimensionNum, input); final Optional<byte[]> existingId = getId(lookupKey, numIdBytes); if (existingId.isPresent()) { return existingId.get(); } final Timer.Context timer = idCreationTime.time(); // If not, we need to create it. First get a new id # from the counter table... byte[] counterKey = makeCounterKey(dimensionNum);
final long id = WithHTable.increment(pool, counterTable, counterKey, cf, QUALIFIER, 1L);
2
moxious/neoprofiler
src/main/java/org/mitre/neoprofiler/markdown/MarkdownMaker.java
[ "public class DBProfile extends NeoProfile {\n\tprotected List<NeoProfile> profiles = new ArrayList<NeoProfile>();\n\t\t\n\tpublic DBProfile(String storageLoc) {\t\t\n\t\tDateFormat dateFormat = new SimpleDateFormat(\"yyyy/MM/dd HH:mm:ss\");\n\t\tDate date = new Date();\n\t\t\n\t\tname = \"Profile of \" + storageLoc + \" generated \" + dateFormat.format(date);\n\t\tdescription = storageLoc;\n\t}\n\t\n\tpublic List<NeoProfile> getProfiles() { return profiles; } \n\t\n\tpublic List<LabelProfile> getLabels() { \n\t\tArrayList<LabelProfile> arr = new ArrayList<LabelProfile>();\n\t\t\n\t\tfor(NeoProfile p : getProfiles())\n\t\t\tif(p instanceof LabelProfile)\n\t\t\t\tarr.add((LabelProfile)p);\n\t\t\n\t\treturn arr;\n\t}\n\t\n\tpublic List<RelationshipTypeProfile> getRelationshipTypes() { \n\t\tArrayList<RelationshipTypeProfile> arr = new ArrayList<RelationshipTypeProfile>();\n\t\t\n\t\tfor(NeoProfile p : getProfiles())\n\t\t\tif(p instanceof RelationshipTypeProfile)\n\t\t\t\tarr.add((RelationshipTypeProfile)p);\n\t\t\n\t\treturn arr;\n\t}\n\t\n\tpublic RelationshipTypeProfile getRelationshipTypeProfile(String type) { \n\t\tfor(NeoProfile p : getProfiles()) { \n\t\t\tif(!(p instanceof RelationshipTypeProfile)) continue;\n\t\t\t\n\t\t\tif(type.equals(((RelationshipTypeProfile)p).getParameter(\"type\"))) \n\t\t\t\treturn ((RelationshipTypeProfile)p);\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n\t\n\tpublic LabelProfile getLabelProfile(String label) { \n\t\tfor(NeoProfile p : getProfiles()) { \n\t\t\tif(!(p instanceof LabelProfile)) continue;\n\t\t\t\n\t\t\tif(label.equals(((LabelProfile)p).getParameter(\"label\"))) \n\t\t\t\treturn ((LabelProfile)p);\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n\t\t\n\tpublic void addProfile(NeoProfile profile) { \n\t\tprofiles.add(profile);\n\t}\n\t\n\tpublic String toString() { \n\t\tStringBuffer b = new StringBuffer(\"\");\n\t\t\n\t\tb.append(\"DBProfile \" + name + \"\\n\");\n\t\tb.append(\"DBProfile \" + description + \"\\n\\n\");\n\t\t\n\t\tfor(NeoProfile profile : profiles) { \n\t\t\tb.append(profile.toString() + \"\\n\"); \n\t\t}\n\t\t\n\t\treturn b.toString();\n\t}\n} // End DBProfile", "public class NeoConstraint {\n\tprotected String description;\n\tprotected boolean index;\n\n\tpublic NeoConstraint(String description) {\n\t\tthis(description, false);\n\t}\n\n\tpublic NeoConstraint(String description, boolean index) {\n\t\tthis.description = description;\n\t\tthis.index = index;\n\t}\n\n\tpublic String toString() {\n\t\treturn \"NeoConstraint constraint=\" + description;\n\t}\n\n\tpublic boolean isIndex() { return index == true; }\n\tpublic String getDescription() { return description; }\n} // End NeoConstraint", "public abstract class NeoProfile {\n\tpublic static final String OB_COUNT = \"Total\";\n\tpublic static final String OB_SAMPLE_PROPERTIES = \"Sample properties\";\n\tpublic static final String OB_VALUE_NA = \"N/A\";\n\t\n\tprotected String name;\n\tprotected String description;\n\tprotected HashMap<String,Object> observations = new HashMap<String,Object>();\n\t\n\tpublic String getName() { return name; } \n\tpublic String getDescription() { return description; } \n\tpublic Map<String,Object> getObservations() { return observations; } \n\tpublic void addObservation(String name, Object observation) { observations.put(name, observation); } \n\t\n\tpublic boolean has(String observationName) { \n\t\treturn observations.containsKey(observationName);\n\t}\n\t\n\tpublic String toString() { \n\t\tStringBuffer b = new StringBuffer(\"\");\n\t\tb.append(name + \": \" + description + \"\\n\");\n\t\t\n\t\tArrayList<String> keys = new ArrayList<String>(getObservations().keySet());\n\t\tCollections.sort(keys);\n\t\t\n\t\tfor(String key : keys) {\n\t\t\tb.append(key + \": \" + observations.get(key) + \"\\n\"); \n\t\t}\n\t\t\n\t\treturn b.toString();\n\t} // End toString\n}", "public class ParameterizedNeoProfile extends NeoProfile {\n\tprotected Map<String,Object> params = new HashMap<String,Object>();\n\t\n\tpublic Object getParameter(String name) { return params.get(name); } \n\tpublic void setParameter(String name, Object param) { params.put(name, param); } \n\t\n\tpublic Map<String,Object> getParameters() { return params; } \n}", "public class SchemaProfile extends NeoProfile {\n\tList<NeoConstraint> constraints;\n\t\n\tpublic SchemaProfile() {\n\t\tname=\"Schema\";\n\t\tdescription=\"Information about Neo4J's database schema\";\n\t\t\n\t\tconstraints = new ArrayList<NeoConstraint>();\n\t}\n\t\n\tpublic void addConstraint(NeoConstraint constraint) { \n\t\tconstraints.add(constraint);\n\t}\n\t\n\tpublic List<NeoConstraint> getConstraints() { \n\t\treturn constraints;\n\t}\n\t\n\tpublic List<NeoConstraint> getNonIndexes() {\n\t\tList<NeoConstraint> idxs = new ArrayList<NeoConstraint>();\n\t\t\n\t\tfor(NeoConstraint c : constraints) { \n\t\t\tif(!c.index) idxs.add(c);\n\t\t}\n\t\t\n\t\treturn idxs;\n\t}\n\t\n\tpublic List<NeoConstraint> getIndexes() {\n\t\tList<NeoConstraint> idxs = new ArrayList<NeoConstraint>();\n\t\t\n\t\tfor(NeoConstraint c : constraints) { \n\t\t\tif(c.index) idxs.add(c);\n\t\t}\n\t\t\n\t\treturn idxs;\n\t}\n} // End SchemaProfile" ]
import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import org.mitre.neoprofiler.profile.DBProfile; import org.mitre.neoprofiler.profile.NeoConstraint; import org.mitre.neoprofiler.profile.NeoProfile; import org.mitre.neoprofiler.profile.ParameterizedNeoProfile; import org.mitre.neoprofiler.profile.SchemaProfile;
package org.mitre.neoprofiler.markdown; /** * A class to write profiles as Markdown. * @author moxious */ public class MarkdownMaker { public MarkdownMaker() { } public String link(String text, String url) { return "[" + text + "](" + url + ")"; } public String h1(String content) { return "\n# " + content + "\n"; } public String h2(String content) { return "\n## " + content + "\n"; } public String h3(String content) { return "\n### " + content + "\n"; } public String h4(String content) { return "\n#### " + content + "\n"; } protected String observations(Map<String,Object>observations) { if(observations.isEmpty()) return ""; StringBuffer b = new StringBuffer(""); b.append(h3("Observations")); ArrayList<String>keys = new ArrayList<String>(observations.keySet()); Collections.sort(keys); for(String key : keys) { b.append("* " + key + ": " + observation(observations.get(key))); if(b.charAt(b.length() - 1) != '\n') b.append("\n"); } return b.toString(); } protected String observation(Object ob) { if(ob == null) return "N/A"; if(ob instanceof String || ob instanceof Number) return ""+ob; if(ob instanceof Collection) { StringBuffer b = new StringBuffer("\n"); for(Object o : ((Collection)ob)) { b.append(" * " + o + "\n"); } return b.toString(); } return ""+ob; } // End observation public String constraints(String title, List<NeoConstraint> constraints) { StringBuffer b = new StringBuffer(""); b.append(h3(title)); if(constraints.isEmpty()) b.append("**None found**"); else { for(NeoConstraint con : constraints) { b.append("* " + (con.isIndex() ? "Index" : "Constraint") + " " + con.getDescription() + "\n"); } } return b.toString(); } public String parameters(Map<String,Object>parameters) { if(parameters.isEmpty()) return ""; StringBuffer b = new StringBuffer(""); b.append(h3("Parameters")); ArrayList<String>keys = new ArrayList<String>(parameters.keySet()); Collections.sort(keys); for(String key : keys) { b.append("* " + key + ": " + observation(parameters.get(key)) + "\n"); } b.append("\n"); return b.toString(); } public void markdownComponentProfile(NeoProfile profile, Writer writer) throws IOException { writer.write(h2(profile.getName()) + "*" + profile.getDescription() + "*\n"); //if(profile instanceof ParameterizedNeoProfile) { // writer.write(parameters(((ParameterizedNeoProfile)profile).getParameters())); //}
if(profile instanceof SchemaProfile) {
4
StumbleUponArchive/hbase
src/test/java/org/apache/hadoop/hbase/MiniHBaseCluster.java
[ "@SuppressWarnings(\"serial\")\npublic class HConnectionManager {\n // An LRU Map of HConnectionKey -> HConnection (TableServer). All\n // access must be synchronized. This map is not private because tests\n // need to be able to tinker with it.\n static final Map<HConnectionKey, HConnectionImplementation> HBASE_INSTANCES;\n\n public static final int MAX_CACHED_HBASE_INSTANCES;\n\n private static Log LOG = LogFactory.getLog(HConnectionManager.class);\n\n static {\n // We set instances to one more than the value specified for {@link\n // HConstants#ZOOKEEPER_MAX_CLIENT_CNXNS}. By default, the zk default max\n // connections to the ensemble from the one client is 30, so in that case we\n // should run into zk issues before the LRU hit this value of 31.\n MAX_CACHED_HBASE_INSTANCES = HBaseConfiguration.create().getInt(\n HConstants.ZOOKEEPER_MAX_CLIENT_CNXNS,\n HConstants.DEFAULT_ZOOKEPER_MAX_CLIENT_CNXNS) + 1;\n HBASE_INSTANCES = new LinkedHashMap<HConnectionKey, HConnectionImplementation>(\n (int) (MAX_CACHED_HBASE_INSTANCES / 0.75F) + 1, 0.75F, true) {\n @Override\n protected boolean removeEldestEntry(\n Map.Entry<HConnectionKey, HConnectionImplementation> eldest) {\n return size() > MAX_CACHED_HBASE_INSTANCES;\n }\n };\n }\n\n /*\n * Non-instantiable.\n */\n protected HConnectionManager() {\n super();\n }\n\n /**\n * Get the connection that goes with the passed <code>conf</code>\n * configuration instance.\n * If no current connection exists, method creates a new connection for the\n * passed <code>conf</code> instance.\n * @param conf configuration\n * @return HConnection object for <code>conf</code>\n * @throws ZooKeeperConnectionException\n */\n public static HConnection getConnection(Configuration conf)\n throws ZooKeeperConnectionException {\n HConnectionKey connectionKey = new HConnectionKey(conf);\n synchronized (HBASE_INSTANCES) {\n HConnectionImplementation connection = HBASE_INSTANCES.get(connectionKey);\n if (connection == null) {\n connection = new HConnectionImplementation(conf, true);\n HBASE_INSTANCES.put(connectionKey, connection);\n }\n connection.incCount();\n return connection;\n }\n }\n\n /**\n * Create a new HConnection instance using the passed <code>conf</code>\n * instance.\n * Note: This bypasses the usual HConnection life cycle management!\n * Use this with caution, the caller is responsible for closing the\n * created connection.\n * @param conf configuration\n * @return HConnection object for <code>conf</code>\n * @throws ZooKeeperConnectionException\n */\n public static HConnection createConnection(Configuration conf)\n throws ZooKeeperConnectionException {\n return new HConnectionImplementation(conf, false);\n }\n\n /**\n * Delete connection information for the instance specified by configuration.\n * If there are no more references to it, this will then close connection to\n * the zookeeper ensemble and let go of all resources.\n *\n * @param conf\n * configuration whose identity is used to find {@link HConnection}\n * instance.\n * @param stopProxy\n * Shuts down all the proxy's put up to cluster members including to\n * cluster HMaster. Calls\n * {@link HBaseRPC#stopProxy(org.apache.hadoop.hbase.ipc.VersionedProtocol)}\n * .\n */\n public static void deleteConnection(Configuration conf, boolean stopProxy) {\n deleteConnection(new HConnectionKey(conf), stopProxy, false);\n }\n\n /**\n * Delete stale connection information for the instance specified by configuration.\n * This will then close connection to\n * the zookeeper ensemble and let go of all resources.\n *\n * @param connection\n */\n public static void deleteStaleConnection(HConnection connection) {\n deleteConnection(connection, true, true);\n }\n\n /**\n * Delete information for all connections.\n * @param stopProxy stop the proxy as well\n * @throws IOException\n */\n public static void deleteAllConnections(boolean stopProxy) {\n synchronized (HBASE_INSTANCES) {\n Set<HConnectionKey> connectionKeys = new HashSet<HConnectionKey>();\n connectionKeys.addAll(HBASE_INSTANCES.keySet());\n for (HConnectionKey connectionKey : connectionKeys) {\n deleteConnection(connectionKey, stopProxy, false);\n }\n HBASE_INSTANCES.clear();\n }\n }\n\n private static void deleteConnection(HConnection connection, boolean stopProxy,\n boolean staleConnection) {\n synchronized (HBASE_INSTANCES) {\n for (Entry<HConnectionKey, HConnectionImplementation> connectionEntry : HBASE_INSTANCES\n .entrySet()) {\n if (connectionEntry.getValue() == connection) {\n deleteConnection(connectionEntry.getKey(), stopProxy, staleConnection);\n break;\n }\n }\n }\n }\n\n private static void deleteConnection(HConnectionKey connectionKey,\n boolean stopProxy, boolean staleConnection) {\n synchronized (HBASE_INSTANCES) {\n HConnectionImplementation connection = HBASE_INSTANCES\n .get(connectionKey);\n if (connection != null) {\n connection.decCount();\n if (connection.isZeroReference() || staleConnection) {\n HBASE_INSTANCES.remove(connectionKey);\n connection.close(stopProxy);\n } else if (stopProxy) {\n connection.stopProxyOnClose(stopProxy);\n }\n }else {\n LOG.error(\"Connection not found in the list, can't delete it \"+\n \"(connection key=\"+connectionKey+\"). May be the key was modified?\");\n }\n }\n }\n\n /**\n * It is provided for unit test cases which verify the behavior of region\n * location cache prefetch.\n * @return Number of cached regions for the table.\n * @throws ZooKeeperConnectionException\n */\n static int getCachedRegionCount(Configuration conf,\n final byte[] tableName)\n throws IOException {\n return execute(new HConnectable<Integer>(conf) {\n @Override\n public Integer connect(HConnection connection) {\n return ((HConnectionImplementation) connection)\n .getNumberOfCachedRegionLocations(tableName);\n }\n });\n }\n\n /**\n * It's provided for unit test cases which verify the behavior of region\n * location cache prefetch.\n * @return true if the region where the table and row reside is cached.\n * @throws ZooKeeperConnectionException\n */\n static boolean isRegionCached(Configuration conf,\n final byte[] tableName, final byte[] row) throws IOException {\n return execute(new HConnectable<Boolean>(conf) {\n @Override\n public Boolean connect(HConnection connection) {\n return ((HConnectionImplementation) connection).isRegionCached(tableName, row);\n }\n });\n }\n\n /**\n * This class makes it convenient for one to execute a command in the context\n * of a {@link HConnection} instance based on the given {@link Configuration}.\n *\n * <p>\n * If you find yourself wanting to use a {@link HConnection} for a relatively\n * short duration of time, and do not want to deal with the hassle of creating\n * and cleaning up that resource, then you should consider using this\n * convenience class.\n *\n * @param <T>\n * the return type of the {@link HConnectable#connect(HConnection)}\n * method.\n */\n public static abstract class HConnectable<T> {\n public Configuration conf;\n\n public HConnectable(Configuration conf) {\n this.conf = conf;\n }\n\n public abstract T connect(HConnection connection) throws IOException;\n }\n\n /**\n * This convenience method invokes the given {@link HConnectable#connect}\n * implementation using a {@link HConnection} instance that lasts just for the\n * duration of that invocation.\n *\n * @param <T> the return type of the connect method\n * @param connectable the {@link HConnectable} instance\n * @return the value returned by the connect method\n * @throws IOException\n */\n public static <T> T execute(HConnectable<T> connectable) throws IOException {\n if (connectable == null || connectable.conf == null) {\n return null;\n }\n Configuration conf = connectable.conf;\n HConnection connection = HConnectionManager.getConnection(conf);\n boolean connectSucceeded = false;\n try {\n T returnValue = connectable.connect(connection);\n connectSucceeded = true;\n return returnValue;\n } finally {\n try {\n connection.close();\n } catch (Exception e) {\n if (connectSucceeded) {\n throw new IOException(\"The connection to \" + connection\n + \" could not be deleted.\", e);\n }\n }\n }\n }\n\n /**\n * Denotes a unique key to a {@link HConnection} instance.\n *\n * In essence, this class captures the properties in {@link Configuration}\n * that may be used in the process of establishing a connection. In light of\n * that, if any new such properties are introduced into the mix, they must be\n * added to the {@link HConnectionKey#properties} list.\n *\n */\n public static class HConnectionKey {\n public static String[] CONNECTION_PROPERTIES = new String[] {\n HConstants.ZOOKEEPER_QUORUM, HConstants.ZOOKEEPER_ZNODE_PARENT,\n HConstants.ZOOKEEPER_CLIENT_PORT,\n HConstants.ZOOKEEPER_RECOVERABLE_WAITTIME,\n HConstants.HBASE_CLIENT_PAUSE, HConstants.HBASE_CLIENT_RETRIES_NUMBER,\n HConstants.HBASE_CLIENT_RPC_MAXATTEMPTS,\n HConstants.HBASE_RPC_TIMEOUT_KEY,\n HConstants.HBASE_CLIENT_PREFETCH_LIMIT,\n HConstants.HBASE_META_SCANNER_CACHING,\n HConstants.HBASE_CLIENT_INSTANCE_ID };\n\n private Map<String, String> properties;\n private String username;\n\n public HConnectionKey(Configuration conf) {\n Map<String, String> m = new HashMap<String, String>();\n if (conf != null) {\n for (String property : CONNECTION_PROPERTIES) {\n String value = conf.get(property);\n if (value != null) {\n m.put(property, value);\n }\n }\n }\n this.properties = Collections.unmodifiableMap(m);\n\n try {\n User currentUser = User.getCurrent();\n if (currentUser != null) {\n username = currentUser.getName();\n }\n } catch (IOException ioe) {\n LOG.warn(\"Error obtaining current user, skipping username in HConnectionKey\",\n ioe);\n }\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n if (username != null) {\n result = username.hashCode();\n }\n for (String property : CONNECTION_PROPERTIES) {\n String value = properties.get(property);\n if (value != null) {\n result = prime * result + value.hashCode();\n }\n }\n\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n HConnectionKey that = (HConnectionKey) obj;\n if (this.username != null && !this.username.equals(that.username)) {\n return false;\n } else if (this.username == null && that.username != null) {\n return false;\n }\n if (this.properties == null) {\n if (that.properties != null) {\n return false;\n }\n } else {\n if (that.properties == null) {\n return false;\n }\n for (String property : CONNECTION_PROPERTIES) {\n String thisValue = this.properties.get(property);\n String thatValue = that.properties.get(property);\n if (thisValue == thatValue) {\n continue;\n }\n if (thisValue == null || !thisValue.equals(thatValue)) {\n return false;\n }\n }\n }\n return true;\n }\n\n @Override\n public String toString() {\n return \"HConnectionKey{\" +\n \"properties=\" + properties +\n \", username='\" + username + '\\'' +\n '}';\n }\n }\n\n /* Encapsulates connection to zookeeper and regionservers.*/\n static class HConnectionImplementation implements HConnection, Closeable {\n static final Log LOG = LogFactory.getLog(HConnectionImplementation.class);\n private final Class<? extends HRegionInterface> serverInterfaceClass;\n private final long pause;\n private final int numRetries;\n private final int maxRPCAttempts;\n private final int rpcTimeout;\n private final int prefetchRegionLimit;\n\n private final Object masterLock = new Object();\n private volatile boolean closed;\n private volatile boolean aborted;\n private volatile HMasterInterface master;\n private volatile boolean masterChecked;\n // ZooKeeper reference\n private volatile ZooKeeperWatcher zooKeeper;\n // ZooKeeper-based master address tracker\n private volatile MasterAddressTracker masterAddressTracker;\n private volatile RootRegionTracker rootRegionTracker;\n private volatile ClusterId clusterId;\n\n private final Object metaRegionLock = new Object();\n\n private final Object userRegionLock = new Object();\n\n private final Configuration conf;\n // Known region HServerAddress.toString() -> HRegionInterface\n\n private final Map<String, HRegionInterface> servers =\n new ConcurrentHashMap<String, HRegionInterface>();\n private final ConcurrentHashMap<String, String> connectionLock =\n new ConcurrentHashMap<String, String>();\n\n /**\n * Map of table to table {@link HRegionLocation}s. The table key is made\n * by doing a {@link Bytes#mapKey(byte[])} of the table's name.\n */\n private final Map<Integer, SoftValueSortedMap<byte [], HRegionLocation>>\n cachedRegionLocations =\n new HashMap<Integer, SoftValueSortedMap<byte [], HRegionLocation>>();\n\n // The presence of a server in the map implies it's likely that there is an\n // entry in cachedRegionLocations that map to this server; but the absence\n // of a server in this map guarentees that there is no entry in cache that\n // maps to the absent server.\n private final Set<String> cachedServers =\n new HashSet<String>();\n\n // region cache prefetch is enabled by default. this set contains all\n // tables whose region cache prefetch are disabled.\n private final Set<Integer> regionCachePrefetchDisabledTables =\n new CopyOnWriteArraySet<Integer>();\n\n private boolean stopProxy;\n private int refCount;\n\n // indicates whether this connection's life cycle is managed\n private final boolean managed;\n /**\n * constructor\n * @param conf Configuration object\n */\n @SuppressWarnings(\"unchecked\")\n public HConnectionImplementation(Configuration conf, boolean managed)\n throws ZooKeeperConnectionException {\n this.conf = conf;\n this.managed = managed;\n String serverClassName = conf.get(HConstants.REGION_SERVER_CLASS,\n HConstants.DEFAULT_REGION_SERVER_CLASS);\n this.closed = false;\n try {\n this.serverInterfaceClass =\n (Class<? extends HRegionInterface>) Class.forName(serverClassName);\n } catch (ClassNotFoundException e) {\n throw new UnsupportedOperationException(\n \"Unable to find region server interface \" + serverClassName, e);\n }\n this.pause = conf.getLong(HConstants.HBASE_CLIENT_PAUSE,\n HConstants.DEFAULT_HBASE_CLIENT_PAUSE);\n this.numRetries = conf.getInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER,\n HConstants.DEFAULT_HBASE_CLIENT_RETRIES_NUMBER);\n this.maxRPCAttempts = conf.getInt(\n HConstants.HBASE_CLIENT_RPC_MAXATTEMPTS,\n HConstants.DEFAULT_HBASE_CLIENT_RPC_MAXATTEMPTS);\n this.rpcTimeout = conf.getInt(\n HConstants.HBASE_RPC_TIMEOUT_KEY,\n HConstants.DEFAULT_HBASE_RPC_TIMEOUT);\n this.prefetchRegionLimit = conf.getInt(\n HConstants.HBASE_CLIENT_PREFETCH_LIMIT,\n HConstants.DEFAULT_HBASE_CLIENT_PREFETCH_LIMIT);\n\n this.master = null;\n this.masterChecked = false;\n }\n\n private synchronized void ensureZookeeperTrackers()\n throws ZooKeeperConnectionException {\n // initialize zookeeper and master address manager\n if (zooKeeper == null) {\n zooKeeper = getZooKeeperWatcher();\n }\n if (clusterId == null) {\n clusterId = new ClusterId(zooKeeper, this);\n }\n if (masterAddressTracker == null) {\n masterAddressTracker = new MasterAddressTracker(zooKeeper, this);\n masterAddressTracker.start();\n }\n if (rootRegionTracker == null) {\n rootRegionTracker = new RootRegionTracker(zooKeeper, this);\n rootRegionTracker.start();\n }\n }\n\n private synchronized void resetZooKeeperTrackers() {\n if (masterAddressTracker != null) {\n masterAddressTracker.stop();\n masterAddressTracker = null;\n }\n if (rootRegionTracker != null) {\n rootRegionTracker.stop();\n rootRegionTracker = null;\n }\n clusterId = null;\n if (zooKeeper != null) {\n zooKeeper.close();\n zooKeeper = null;\n }\n }\n\n public Configuration getConfiguration() {\n return this.conf;\n }\n\n public HMasterInterface getMaster()\n throws MasterNotRunningException, ZooKeeperConnectionException {\n // TODO: REMOVE. MOVE TO HBaseAdmin and redo as a Callable!!!\n\n // Check if we already have a good master connection\n try {\n if (master != null && master.isMasterRunning()) {\n return master;\n }\n } catch (UndeclaredThrowableException ute) {\n // log, but ignore, the loop below will attempt to reconnect\n LOG.info(\"Exception contacting master. Retrying...\", ute.getCause());\n }\n\n ensureZookeeperTrackers();\n checkIfBaseNodeAvailable();\n ServerName sn = null;\n synchronized (this.masterLock) {\n try {\n if (master != null && master.isMasterRunning()) {\n return master;\n }\n } catch (UndeclaredThrowableException ute) {\n // log, but ignore, the loop below will attempt to reconnect\n LOG.info(\"Exception contacting master. Retrying...\", ute.getCause());\n }\n this.master = null;\n\n for (int tries = 0;\n !this.closed &&\n !this.masterChecked && this.master == null &&\n tries < numRetries;\n tries++) {\n\n try {\n sn = masterAddressTracker.getMasterAddress();\n if (sn == null) {\n LOG.info(\"ZooKeeper available but no active master location found\");\n throw new MasterNotRunningException();\n }\n\n if (clusterId.hasId()) {\n conf.set(HConstants.CLUSTER_ID, clusterId.getId());\n }\n InetSocketAddress isa =\n new InetSocketAddress(sn.getHostname(), sn.getPort());\n HMasterInterface tryMaster = (HMasterInterface)HBaseRPC.getProxy(\n HMasterInterface.class, HMasterInterface.VERSION, isa, this.conf,\n this.rpcTimeout);\n\n if (tryMaster.isMasterRunning()) {\n this.master = tryMaster;\n this.masterLock.notifyAll();\n break;\n }\n\n } catch (IOException e) {\n if (tries == numRetries - 1) {\n // This was our last chance - don't bother sleeping\n LOG.info(\"getMaster attempt \" + tries + \" of \" + numRetries +\n \" failed; no more retrying.\", e);\n break;\n }\n LOG.info(\"getMaster attempt \" + tries + \" of \" + numRetries +\n \" failed; retrying after sleep of \" +\n ConnectionUtils.getPauseTime(this.pause, tries), e);\n }\n\n // Cannot connect to master or it is not running. Sleep & retry\n try {\n this.masterLock.wait(ConnectionUtils.getPauseTime(this.pause, tries));\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n throw new RuntimeException(\"Thread was interrupted while trying to connect to master.\");\n }\n }\n // Avoid re-checking in the future if this is a managed HConnection,\n // even if we failed to acquire a master.\n // (this is to retain the existing behavior before HBASE-5058)\n this.masterChecked = managed;\n\n if (this.master == null) {\n if (sn == null) {\n throw new MasterNotRunningException();\n }\n throw new MasterNotRunningException(sn.toString());\n }\n return this.master;\n }\n }\n\n private void checkIfBaseNodeAvailable() throws MasterNotRunningException {\n if (false == masterAddressTracker.checkIfBaseNodeAvailable()) {\n String errorMsg = \"Check the value configured in 'zookeeper.znode.parent'. \"\n + \"There could be a mismatch with the one configured in the master.\";\n LOG.error(errorMsg);\n throw new MasterNotRunningException(errorMsg);\n }\n }\n\n public boolean isMasterRunning()\n throws MasterNotRunningException, ZooKeeperConnectionException {\n if (this.master == null) {\n getMaster();\n }\n boolean isRunning = master.isMasterRunning();\n if(isRunning) {\n return true;\n }\n throw new MasterNotRunningException();\n }\n\n public HRegionLocation getRegionLocation(final byte [] name,\n final byte [] row, boolean reload)\n throws IOException {\n return reload? relocateRegion(name, row): locateRegion(name, row);\n }\n\n public boolean isTableEnabled(byte[] tableName) throws IOException {\n return testTableOnlineState(tableName, true);\n }\n\n public boolean isTableDisabled(byte[] tableName) throws IOException {\n return testTableOnlineState(tableName, false);\n }\n\n public boolean isTableAvailable(final byte[] tableName) throws IOException {\n final AtomicBoolean available = new AtomicBoolean(true);\n final AtomicInteger regionCount = new AtomicInteger(0);\n MetaScannerVisitor visitor = new MetaScannerVisitorBase() {\n @Override\n public boolean processRow(Result row) throws IOException {\n byte[] value = row.getValue(HConstants.CATALOG_FAMILY,\n HConstants.REGIONINFO_QUALIFIER);\n HRegionInfo info = Writables.getHRegionInfoOrNull(value);\n if (info != null) {\n if (Bytes.equals(tableName, info.getTableName())) {\n value = row.getValue(HConstants.CATALOG_FAMILY,\n HConstants.SERVER_QUALIFIER);\n if (value == null) {\n available.set(false);\n return false;\n }\n regionCount.incrementAndGet();\n }\n }\n return true;\n }\n };\n MetaScanner.metaScan(conf, visitor);\n return available.get() && (regionCount.get() > 0);\n }\n\n /*\n * @param True if table is online\n */\n private boolean testTableOnlineState(byte [] tableName, boolean online)\n throws IOException {\n if (Bytes.equals(tableName, HConstants.ROOT_TABLE_NAME)) {\n // The root region is always enabled\n return online;\n }\n ZooKeeperWatcher zkw = getZooKeeperWatcher();\n String tableNameStr = Bytes.toString(tableName);\n try {\n if (online) {\n return ZKTableReadOnly.isEnabledTable(zkw, tableNameStr);\n }\n return ZKTableReadOnly.isDisabledTable(zkw, tableNameStr);\n } catch (KeeperException e) {\n throw new IOException(\"Enable/Disable failed\", e);\n }\n }\n\n @Override\n public HRegionLocation locateRegion(final byte [] regionName)\n throws IOException {\n // TODO implement. use old stuff or new stuff?\n return null;\n }\n\n @Override\n public List<HRegionLocation> locateRegions(final byte [] tableName)\n throws IOException {\n // TODO implement. use old stuff or new stuff?\n return null;\n }\n\n public HRegionLocation locateRegion(final byte [] tableName,\n final byte [] row)\n throws IOException{\n return locateRegion(tableName, row, true, true);\n }\n\n public HRegionLocation relocateRegion(final byte [] tableName,\n final byte [] row)\n throws IOException{\n return locateRegion(tableName, row, false, true);\n }\n\n private HRegionLocation locateRegion(final byte [] tableName,\n final byte [] row, boolean useCache, boolean retry)\n throws IOException {\n if (this.closed) throw new IOException(toString() + \" closed\");\n if (tableName == null || tableName.length == 0) {\n throw new IllegalArgumentException(\n \"table name cannot be null or zero length\");\n }\n ensureZookeeperTrackers();\n if (Bytes.equals(tableName, HConstants.ROOT_TABLE_NAME)) {\n try {\n ServerName servername = this.rootRegionTracker.waitRootRegionLocation(this.rpcTimeout);\n LOG.debug(\"Looked up root region location, connection=\" + this +\n \"; serverName=\" + ((servername == null)? \"\": servername.toString()));\n if (servername == null) return null;\n return new HRegionLocation(HRegionInfo.ROOT_REGIONINFO,\n servername.getHostname(), servername.getPort());\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n return null;\n }\n } else if (Bytes.equals(tableName, HConstants.META_TABLE_NAME)) {\n return locateRegionInMeta(HConstants.ROOT_TABLE_NAME, tableName, row,\n useCache, metaRegionLock, retry);\n } else {\n // Region not in the cache - have to go to the meta RS\n return locateRegionInMeta(HConstants.META_TABLE_NAME, tableName, row,\n useCache, userRegionLock, retry);\n }\n }\n\n /*\n * Search .META. for the HRegionLocation info that contains the table and\n * row we're seeking. It will prefetch certain number of regions info and\n * save them to the global region cache.\n */\n private void prefetchRegionCache(final byte[] tableName,\n final byte[] row) {\n // Implement a new visitor for MetaScanner, and use it to walk through\n // the .META.\n MetaScannerVisitor visitor = new MetaScannerVisitorBase() {\n public boolean processRow(Result result) throws IOException {\n try {\n byte[] value = result.getValue(HConstants.CATALOG_FAMILY,\n HConstants.REGIONINFO_QUALIFIER);\n HRegionInfo regionInfo = null;\n\n if (value != null) {\n // convert the row result into the HRegionLocation we need!\n regionInfo = Writables.getHRegionInfo(value);\n\n // possible we got a region of a different table...\n if (!Bytes.equals(regionInfo.getTableName(),\n tableName)) {\n return false; // stop scanning\n }\n if (regionInfo.isOffline()) {\n // don't cache offline regions\n return true;\n }\n value = result.getValue(HConstants.CATALOG_FAMILY,\n HConstants.SERVER_QUALIFIER);\n if (value == null) {\n return true; // don't cache it\n }\n final String hostAndPort = Bytes.toString(value);\n String hostname = Addressing.parseHostname(hostAndPort);\n int port = Addressing.parsePort(hostAndPort);\n value = result.getValue(HConstants.CATALOG_FAMILY,\n HConstants.STARTCODE_QUALIFIER);\n // instantiate the location\n HRegionLocation loc =\n new HRegionLocation(regionInfo, hostname, port);\n // cache this meta entry\n cacheLocation(tableName, loc);\n }\n return true;\n } catch (RuntimeException e) {\n throw new IOException(e);\n }\n }\n };\n try {\n // pre-fetch certain number of regions info at region cache.\n MetaScanner.metaScan(conf, visitor, tableName, row,\n this.prefetchRegionLimit);\n } catch (IOException e) {\n LOG.warn(\"Encountered problems when prefetch META table: \", e);\n }\n }\n\n /*\n * Search one of the meta tables (-ROOT- or .META.) for the HRegionLocation\n * info that contains the table and row we're seeking.\n */\n private HRegionLocation locateRegionInMeta(final byte [] parentTable,\n final byte [] tableName, final byte [] row, boolean useCache,\n Object regionLockObject, boolean retry)\n throws IOException {\n HRegionLocation location;\n // If we are supposed to be using the cache, look in the cache to see if\n // we already have the region.\n if (useCache) {\n location = getCachedLocation(tableName, row);\n if (location != null) {\n return location;\n }\n }\n\n int localNumRetries = retry ? numRetries : 1;\n // build the key of the meta region we should be looking for.\n // the extra 9's on the end are necessary to allow \"exact\" matches\n // without knowing the precise region names.\n byte [] metaKey = HRegionInfo.createRegionName(tableName, row,\n HConstants.NINES, false);\n for (int tries = 0; true; tries++) {\n if (tries >= localNumRetries) {\n throw new NoServerForRegionException(\"Unable to find region for \"\n + Bytes.toStringBinary(row) + \" after \" + numRetries + \" tries.\");\n }\n\n HRegionLocation metaLocation = null;\n try {\n // locate the root or meta region\n metaLocation = locateRegion(parentTable, metaKey, true, false);\n // If null still, go around again.\n if (metaLocation == null) continue;\n HRegionInterface server =\n getHRegionConnection(metaLocation.getHostname(), metaLocation.getPort());\n\n Result regionInfoRow = null;\n // This block guards against two threads trying to load the meta\n // region at the same time. The first will load the meta region and\n // the second will use the value that the first one found.\n synchronized (regionLockObject) {\n // If the parent table is META, we may want to pre-fetch some\n // region info into the global region cache for this table.\n /*if (Bytes.equals(parentTable, HConstants.META_TABLE_NAME) &&\n (getRegionCachePrefetch(tableName)) ) {\n prefetchRegionCache(tableName, row);\n }*/\n\n // Check the cache again for a hit in case some other thread made the\n // same query while we were waiting on the lock. If not supposed to\n // be using the cache, delete any existing cached location so it won't\n // interfere.\n if (useCache) {\n location = getCachedLocation(tableName, row);\n if (location != null) {\n return location;\n }\n } else {\n deleteCachedLocation(tableName, row);\n }\n\n // Query the root or meta region for the location of the meta region\n regionInfoRow = server.getClosestRowBefore(\n metaLocation.getRegionInfo().getRegionName(), metaKey,\n HConstants.CATALOG_FAMILY);\n }\n if (regionInfoRow == null) {\n throw new TableNotFoundException(Bytes.toString(tableName));\n }\n byte [] value = regionInfoRow.getValue(HConstants.CATALOG_FAMILY,\n HConstants.REGIONINFO_QUALIFIER);\n if (value == null || value.length == 0) {\n throw new IOException(\"HRegionInfo was null or empty in \" +\n Bytes.toString(parentTable) + \", row=\" + regionInfoRow);\n }\n // convert the row result into the HRegionLocation we need!\n HRegionInfo regionInfo = (HRegionInfo) Writables.getWritable(\n value, new HRegionInfo());\n // possible we got a region of a different table...\n if (!Bytes.equals(regionInfo.getTableName(), tableName)) {\n throw new TableNotFoundException(\n \"Table '\" + Bytes.toString(tableName) + \"' was not found, got: \" +\n Bytes.toString(regionInfo.getTableName()) + \".\");\n }\n if (regionInfo.isSplit()) {\n throw new RegionOfflineException(\"the only available region for\" +\n \" the required row is a split parent,\" +\n \" the daughters should be online soon: \" +\n regionInfo.getRegionNameAsString());\n }\n if (regionInfo.isOffline()) {\n throw new RegionOfflineException(\"the region is offline, could\" +\n \" be caused by a disable table call: \" +\n regionInfo.getRegionNameAsString());\n }\n\n value = regionInfoRow.getValue(HConstants.CATALOG_FAMILY,\n HConstants.SERVER_QUALIFIER);\n String hostAndPort = \"\";\n if (value != null) {\n hostAndPort = Bytes.toString(value);\n }\n if (hostAndPort.equals(\"\")) {\n throw new NoServerForRegionException(\"No server address listed \" +\n \"in \" + Bytes.toString(parentTable) + \" for region \" +\n regionInfo.getRegionNameAsString() + \" containing row \" +\n Bytes.toStringBinary(row));\n }\n\n // Instantiate the location\n String hostname = Addressing.parseHostname(hostAndPort);\n int port = Addressing.parsePort(hostAndPort);\n location = new HRegionLocation(regionInfo, hostname, port);\n cacheLocation(tableName, location);\n return location;\n } catch (TableNotFoundException e) {\n // if we got this error, probably means the table just plain doesn't\n // exist. rethrow the error immediately. this should always be coming\n // from the HTable constructor.\n throw e;\n } catch (IOException e) {\n if (e instanceof RemoteException) {\n e = RemoteExceptionHandler.decodeRemoteException((RemoteException) e);\n }\n if (tries < numRetries - 1) {\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"locateRegionInMeta parentTable=\" +\n Bytes.toString(parentTable) + \", metaLocation=\" +\n ((metaLocation == null)? \"null\": \"{\" + metaLocation + \"}\") +\n \", attempt=\" + tries + \" of \" +\n this.numRetries + \" failed; retrying after sleep of \" +\n ConnectionUtils.getPauseTime(this.pause, tries) + \" because: \" + e.getMessage());\n }\n } else {\n throw e;\n }\n // Only relocate the parent region if necessary\n if(!(e instanceof RegionOfflineException ||\n e instanceof NoServerForRegionException)) {\n relocateRegion(parentTable, metaKey);\n }\n }\n try{\n Thread.sleep(ConnectionUtils.getPauseTime(this.pause, tries));\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n throw new IOException(\"Giving up trying to location region in \" +\n \"meta: thread is interrupted.\");\n }\n }\n }\n\n /*\n * Search the cache for a location that fits our table and row key.\n * Return null if no suitable region is located. TODO: synchronization note\n *\n * <p>TODO: This method during writing consumes 15% of CPU doing lookup\n * into the Soft Reference SortedMap. Improve.\n *\n * @param tableName\n * @param row\n * @return Null or region location found in cache.\n */\n HRegionLocation getCachedLocation(final byte [] tableName,\n final byte [] row) {\n SoftValueSortedMap<byte [], HRegionLocation> tableLocations =\n getTableLocations(tableName);\n\n // start to examine the cache. we can only do cache actions\n // if there's something in the cache for this table.\n if (tableLocations.isEmpty()) {\n return null;\n }\n\n HRegionLocation possibleRegion = tableLocations.get(row);\n if (possibleRegion != null) {\n return possibleRegion;\n }\n\n possibleRegion = tableLocations.lowerValueByKey(row);\n if (possibleRegion == null) {\n return null;\n }\n\n // make sure that the end key is greater than the row we're looking\n // for, otherwise the row actually belongs in the next region, not\n // this one. the exception case is when the endkey is\n // HConstants.EMPTY_END_ROW, signifying that the region we're\n // checking is actually the last region in the table.\n byte[] endKey = possibleRegion.getRegionInfo().getEndKey();\n if (Bytes.equals(endKey, HConstants.EMPTY_END_ROW) ||\n KeyValue.getRowComparator(tableName).compareRows(\n endKey, 0, endKey.length, row, 0, row.length) > 0) {\n return possibleRegion;\n }\n\n // Passed all the way through, so we got nothin - complete cache miss\n return null;\n }\n\n /**\n * Delete a cached location\n * @param tableName tableName\n * @param row\n */\n void deleteCachedLocation(final byte [] tableName, final byte [] row) {\n synchronized (this.cachedRegionLocations) {\n Map<byte[], HRegionLocation> tableLocations =\n getTableLocations(tableName);\n // start to examine the cache. we can only do cache actions\n // if there's something in the cache for this table.\n if (!tableLocations.isEmpty()) {\n HRegionLocation rl = getCachedLocation(tableName, row);\n if (rl != null) {\n tableLocations.remove(rl.getRegionInfo().getStartKey());\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"Removed \" +\n rl.getRegionInfo().getRegionNameAsString() +\n \" for tableName=\" + Bytes.toString(tableName) +\n \" from cache \" + \"because of \" + Bytes.toStringBinary(row));\n }\n }\n }\n }\n }\n\n @Override\n public void clearCaches(String sn) {\n clearCachedLocationForServer(sn);\n }\n\n /*\n * Delete all cached entries of a table that maps to a specific location.\n *\n * @param tablename\n * @param server\n */\n private void clearCachedLocationForServer(final String server) {\n boolean deletedSomething = false;\n synchronized (this.cachedRegionLocations) {\n if (!cachedServers.contains(server)) {\n return;\n }\n for (Map<byte[], HRegionLocation> tableLocations :\n cachedRegionLocations.values()) {\n for (Entry<byte[], HRegionLocation> e : tableLocations.entrySet()) {\n if (e.getValue().getHostnamePort().equals(server)) {\n tableLocations.remove(e.getKey());\n deletedSomething = true;\n }\n }\n }\n cachedServers.remove(server);\n }\n if (deletedSomething && LOG.isDebugEnabled()) {\n LOG.debug(\"Removed all cached region locations that map to \" + server);\n }\n }\n\n /*\n * @param tableName\n * @return Map of cached locations for passed <code>tableName</code>\n */\n private SoftValueSortedMap<byte [], HRegionLocation> getTableLocations(\n final byte [] tableName) {\n // find the map of cached locations for this table\n Integer key = Bytes.mapKey(tableName);\n SoftValueSortedMap<byte [], HRegionLocation> result;\n synchronized (this.cachedRegionLocations) {\n result = this.cachedRegionLocations.get(key);\n // if tableLocations for this table isn't built yet, make one\n if (result == null) {\n result = new SoftValueSortedMap<byte [], HRegionLocation>(\n Bytes.BYTES_COMPARATOR);\n this.cachedRegionLocations.put(key, result);\n }\n }\n return result;\n }\n\n @Override\n public void clearRegionCache() {\n synchronized(this.cachedRegionLocations) {\n this.cachedRegionLocations.clear();\n this.cachedServers.clear();\n }\n }\n\n @Override\n public void clearRegionCache(final byte [] tableName) {\n synchronized (this.cachedRegionLocations) {\n this.cachedRegionLocations.remove(Bytes.mapKey(tableName));\n }\n }\n\n /*\n * Put a newly discovered HRegionLocation into the cache.\n */\n private void cacheLocation(final byte [] tableName,\n final HRegionLocation location) {\n byte [] startKey = location.getRegionInfo().getStartKey();\n Map<byte [], HRegionLocation> tableLocations =\n getTableLocations(tableName);\n boolean hasNewCache = false;\n synchronized (this.cachedRegionLocations) {\n cachedServers.add(location.getHostnamePort());\n hasNewCache = (tableLocations.put(startKey, location) == null);\n }\n if (hasNewCache) {\n LOG.debug(\"Cached location for \" +\n location.getRegionInfo().getRegionNameAsString() +\n \" is \" + location.getHostnamePort());\n }\n }\n\n public HRegionInterface getHRegionConnection(HServerAddress hsa)\n throws IOException {\n return getHRegionConnection(hsa, false);\n }\n\n @Override\n public HRegionInterface getHRegionConnection(final String hostname,\n final int port)\n throws IOException {\n return getHRegionConnection(hostname, port, false);\n }\n\n public HRegionInterface getHRegionConnection(HServerAddress hsa,\n boolean master)\n throws IOException {\n return getHRegionConnection(null, -1, hsa.getInetSocketAddress(), master);\n }\n\n @Override\n public HRegionInterface getHRegionConnection(final String hostname,\n final int port, final boolean master)\n throws IOException {\n return getHRegionConnection(hostname, port, null, master);\n }\n\n /**\n * Either the passed <code>isa</code> is null or <code>hostname</code>\n * can be but not both.\n * @param hostname\n * @param port\n * @param isa\n * @param master\n * @return Proxy.\n * @throws IOException\n */\n HRegionInterface getHRegionConnection(final String hostname, final int port,\n final InetSocketAddress isa, final boolean master)\n throws IOException {\n if (master) getMaster();\n HRegionInterface server;\n String rsName = null;\n if (isa != null) {\n rsName = Addressing.createHostAndPortStr(isa.getHostName(),\n isa.getPort());\n } else {\n rsName = Addressing.createHostAndPortStr(hostname, port);\n }\n ensureZookeeperTrackers();\n // See if we already have a connection (common case)\n server = this.servers.get(rsName);\n if (server == null) {\n // create a unique lock for this RS (if necessary)\n this.connectionLock.putIfAbsent(rsName, rsName);\n // get the RS lock\n synchronized (this.connectionLock.get(rsName)) {\n // do one more lookup in case we were stalled above\n server = this.servers.get(rsName);\n if (server == null) {\n try {\n if (clusterId.hasId()) {\n conf.set(HConstants.CLUSTER_ID, clusterId.getId());\n }\n // Only create isa when we need to.\n InetSocketAddress address = isa != null? isa:\n new InetSocketAddress(hostname, port);\n // definitely a cache miss. establish an RPC for this RS\n server = (HRegionInterface) HBaseRPC.waitForProxy(\n serverInterfaceClass, HRegionInterface.VERSION,\n address, this.conf,\n this.maxRPCAttempts, this.rpcTimeout, this.rpcTimeout);\n this.servers.put(Addressing.createHostAndPortStr(\n address.getHostName(), address.getPort()), server);\n } catch (RemoteException e) {\n LOG.warn(\"RemoteException connecting to RS\", e);\n // Throw what the RemoteException was carrying.\n throw e.unwrapRemoteException();\n }\n }\n }\n }\n return server;\n }\n\n /**\n * Get the ZooKeeper instance for this TableServers instance.\n *\n * If ZK has not been initialized yet, this will connect to ZK.\n * @returns zookeeper reference\n * @throws ZooKeeperConnectionException if there's a problem connecting to zk\n */\n public synchronized ZooKeeperWatcher getZooKeeperWatcher()\n throws ZooKeeperConnectionException {\n if(zooKeeper == null) {\n try {\n this.zooKeeper = new ZooKeeperWatcher(conf, \"hconnection\", this);\n } catch(ZooKeeperConnectionException zce) {\n throw zce;\n } catch (IOException e) {\n throw new ZooKeeperConnectionException(\"An error is preventing\" +\n \" HBase from connecting to ZooKeeper\", e);\n }\n }\n return zooKeeper;\n }\n\n public <T> T getRegionServerWithRetries(ServerCallable<T> callable)\n throws IOException, RuntimeException {\n return callable.withRetries();\n }\n\n public <T> T getRegionServerWithoutRetries(ServerCallable<T> callable)\n throws IOException, RuntimeException {\n return callable.withoutRetries();\n }\n\n private <R> Callable<MultiResponse> createCallable(final HRegionLocation loc,\n final MultiAction<R> multi, final byte [] tableName) {\n // TODO: This does not belong in here!!! St.Ack HConnections should\n // not be dealing in Callables; Callables have HConnections, not other\n // way around.\n final HConnection connection = this;\n return new Callable<MultiResponse>() {\n public MultiResponse call() throws IOException {\n ServerCallable<MultiResponse> callable =\n new ServerCallable<MultiResponse>(connection, tableName, null) {\n public MultiResponse call() throws IOException {\n return server.multi(multi);\n }\n @Override\n public void connect(boolean reload) throws IOException {\n server = connection.getHRegionConnection(loc.getHostname(), loc.getPort());\n }\n };\n return callable.withoutRetries();\n }\n };\n }\n\n public void processBatch(List<? extends Row> list,\n final byte[] tableName,\n ExecutorService pool,\n Object[] results) throws IOException, InterruptedException {\n // This belongs in HTable!!! Not in here. St.Ack\n\n // results must be the same size as list\n if (results.length != list.size()) {\n throw new IllegalArgumentException(\"argument results must be the same size as argument list\");\n }\n\n processBatchCallback(list, tableName, pool, results, null);\n }\n\n /**\n * Executes the given\n * {@link org.apache.hadoop.hbase.client.coprocessor.Batch.Call}\n * callable for each row in the\n * given list and invokes\n * {@link org.apache.hadoop.hbase.client.coprocessor.Batch.Callback#update(byte[], byte[], Object)}\n * for each result returned.\n *\n * @param protocol the protocol interface being called\n * @param rows a list of row keys for which the callable should be invoked\n * @param tableName table name for the coprocessor invoked\n * @param pool ExecutorService used to submit the calls per row\n * @param callable instance on which to invoke\n * {@link org.apache.hadoop.hbase.client.coprocessor.Batch.Call#call(Object)}\n * for each row\n * @param callback instance on which to invoke\n * {@link org.apache.hadoop.hbase.client.coprocessor.Batch.Callback#update(byte[], byte[], Object)}\n * for each result\n * @param <T> the protocol interface type\n * @param <R> the callable's return type\n * @throws IOException\n */\n public <T extends CoprocessorProtocol,R> void processExecs(\n final Class<T> protocol,\n List<byte[]> rows,\n final byte[] tableName,\n ExecutorService pool,\n final Batch.Call<T,R> callable,\n final Batch.Callback<R> callback)\n throws IOException, Throwable {\n\n Map<byte[],Future<R>> futures =\n new TreeMap<byte[],Future<R>>(Bytes.BYTES_COMPARATOR);\n for (final byte[] r : rows) {\n final ExecRPCInvoker invoker =\n new ExecRPCInvoker(conf, this, protocol, tableName, r);\n Future<R> future = pool.submit(\n new Callable<R>() {\n public R call() throws Exception {\n T instance = (T)Proxy.newProxyInstance(conf.getClassLoader(),\n new Class[]{protocol},\n invoker);\n R result = callable.call(instance);\n byte[] region = invoker.getRegionName();\n if (callback != null) {\n callback.update(region, r, result);\n }\n return result;\n }\n });\n futures.put(r, future);\n }\n for (Map.Entry<byte[],Future<R>> e : futures.entrySet()) {\n try {\n e.getValue().get();\n } catch (ExecutionException ee) {\n LOG.warn(\"Error executing for row \"+Bytes.toStringBinary(e.getKey()), ee);\n throw ee.getCause();\n } catch (InterruptedException ie) {\n Thread.currentThread().interrupt();\n throw new IOException(\"Interrupted executing for row \" +\n Bytes.toStringBinary(e.getKey()), ie);\n }\n }\n }\n\n /**\n * Parameterized batch processing, allowing varying return types for\n * different {@link Row} implementations.\n */\n public <R> void processBatchCallback(\n List<? extends Row> list,\n byte[] tableName,\n ExecutorService pool,\n Object[] results,\n Batch.Callback<R> callback)\n throws IOException, InterruptedException {\n // This belongs in HTable!!! Not in here. St.Ack\n\n // results must be the same size as list\n if (results.length != list.size()) {\n throw new IllegalArgumentException(\n \"argument results must be the same size as argument list\");\n }\n if (list.isEmpty()) {\n return;\n }\n\n // Keep track of the most recent servers for any given item for better\n // exceptional reporting. We keep HRegionLocation to save on parsing.\n // Later below when we use lastServers, we'll pull what we need from\n // lastServers.\n HRegionLocation [] lastServers = new HRegionLocation[results.length];\n List<Row> workingList = new ArrayList<Row>(list);\n boolean retry = true;\n // count that helps presize actions array\n int actionCount = 0;\n\n for (int tries = 0; tries < numRetries && retry; ++tries) {\n\n // sleep first, if this is a retry\n if (tries >= 1) {\n long sleepTime = ConnectionUtils.getPauseTime(this.pause, tries);\n LOG.debug(\"Retry \" +tries+ \", sleep for \" +sleepTime+ \"ms!\");\n Thread.sleep(sleepTime);\n }\n // step 1: break up into regionserver-sized chunks and build the data structs\n Map<HRegionLocation, MultiAction<R>> actionsByServer =\n new HashMap<HRegionLocation, MultiAction<R>>();\n for (int i = 0; i < workingList.size(); i++) {\n Row row = workingList.get(i);\n if (row != null) {\n HRegionLocation loc = locateRegion(tableName, row.getRow());\n byte[] regionName = loc.getRegionInfo().getRegionName();\n\n MultiAction<R> actions = actionsByServer.get(loc);\n if (actions == null) {\n actions = new MultiAction<R>();\n actionsByServer.put(loc, actions);\n }\n\n Action<R> action = new Action<R>(row, i);\n lastServers[i] = loc;\n actions.add(regionName, action);\n }\n }\n\n // step 2: make the requests\n\n Map<HRegionLocation, Future<MultiResponse>> futures =\n new HashMap<HRegionLocation, Future<MultiResponse>>(\n actionsByServer.size());\n\n for (Entry<HRegionLocation, MultiAction<R>> e: actionsByServer.entrySet()) {\n futures.put(e.getKey(), pool.submit(createCallable(e.getKey(), e.getValue(), tableName)));\n }\n\n // step 3: collect the failures and successes and prepare for retry\n\n for (Entry<HRegionLocation, Future<MultiResponse>> responsePerServer\n : futures.entrySet()) {\n HRegionLocation loc = responsePerServer.getKey();\n\n try {\n Future<MultiResponse> future = responsePerServer.getValue();\n MultiResponse resp = future.get();\n\n if (resp == null) {\n // Entire server failed\n LOG.debug(\"Failed all for server: \" + loc.getHostnamePort() +\n \", removing from cache\");\n continue;\n }\n\n for (Entry<byte[], List<Pair<Integer,Object>>> e : resp.getResults().entrySet()) {\n byte[] regionName = e.getKey();\n List<Pair<Integer, Object>> regionResults = e.getValue();\n for (Pair<Integer, Object> regionResult : regionResults) {\n if (regionResult == null) {\n // if the first/only record is 'null' the entire region failed.\n LOG.debug(\"Failures for region: \" +\n Bytes.toStringBinary(regionName) +\n \", removing from cache\");\n } else {\n // Result might be an Exception, including DNRIOE\n results[regionResult.getFirst()] = regionResult.getSecond();\n if (callback != null && !(regionResult.getSecond() instanceof Throwable)) {\n callback.update(e.getKey(),\n list.get(regionResult.getFirst()).getRow(),\n (R)regionResult.getSecond());\n }\n }\n }\n }\n } catch (ExecutionException e) {\n LOG.warn(\"Failed all from \" + loc, e);\n }\n }\n\n // step 4: identify failures and prep for a retry (if applicable).\n\n // Find failures (i.e. null Result), and add them to the workingList (in\n // order), so they can be retried.\n retry = false;\n workingList.clear();\n actionCount = 0;\n for (int i = 0; i < results.length; i++) {\n // if null (fail) or instanceof Throwable && not instanceof DNRIOE\n // then retry that row. else dont.\n if (results[i] == null ||\n (results[i] instanceof Throwable &&\n !(results[i] instanceof DoNotRetryIOException))) {\n\n retry = true;\n actionCount++;\n Row row = list.get(i);\n workingList.add(row);\n deleteCachedLocation(tableName, row.getRow());\n } else {\n if (results[i] != null && results[i] instanceof Throwable) {\n actionCount++;\n }\n // add null to workingList, so the order remains consistent with the original list argument.\n workingList.add(null);\n }\n }\n }\n\n List<Throwable> exceptions = new ArrayList<Throwable>(actionCount);\n List<Row> actions = new ArrayList<Row>(actionCount);\n List<String> addresses = new ArrayList<String>(actionCount);\n\n for (int i = 0 ; i < results.length; i++) {\n if (results[i] == null || results[i] instanceof Throwable) {\n exceptions.add((Throwable)results[i]);\n actions.add(list.get(i));\n addresses.add(lastServers[i].getHostnamePort());\n }\n }\n\n if (!exceptions.isEmpty()) {\n throw new RetriesExhaustedWithDetailsException(exceptions,\n actions,\n addresses);\n }\n }\n\n /*\n * Return the number of cached region for a table. It will only be called\n * from a unit test.\n */\n int getNumberOfCachedRegionLocations(final byte[] tableName) {\n Integer key = Bytes.mapKey(tableName);\n synchronized (this.cachedRegionLocations) {\n Map<byte[], HRegionLocation> tableLocs =\n this.cachedRegionLocations.get(key);\n\n if (tableLocs == null) {\n return 0;\n }\n return tableLocs.values().size();\n }\n }\n\n /**\n * Check the region cache to see whether a region is cached yet or not.\n * Called by unit tests.\n * @param tableName tableName\n * @param row row\n * @return Region cached or not.\n */\n boolean isRegionCached(final byte[] tableName, final byte[] row) {\n HRegionLocation location = getCachedLocation(tableName, row);\n return location != null;\n }\n\n public void setRegionCachePrefetch(final byte[] tableName,\n final boolean enable) {\n if (!enable) {\n regionCachePrefetchDisabledTables.add(Bytes.mapKey(tableName));\n }\n else {\n regionCachePrefetchDisabledTables.remove(Bytes.mapKey(tableName));\n }\n }\n\n public boolean getRegionCachePrefetch(final byte[] tableName) {\n return !regionCachePrefetchDisabledTables.contains(Bytes.mapKey(tableName));\n }\n\n @Override\n public void prewarmRegionCache(byte[] tableName,\n Map<HRegionInfo, HServerAddress> regions) {\n for (Map.Entry<HRegionInfo, HServerAddress> e : regions.entrySet()) {\n HServerAddress hsa = e.getValue();\n if (hsa == null || hsa.getInetSocketAddress() == null) continue;\n cacheLocation(tableName,\n new HRegionLocation(e.getKey(), hsa.getHostname(), hsa.getPort()));\n }\n }\n\n @Override\n public void abort(final String msg, Throwable t) {\n if (t instanceof KeeperException) {\n LOG.info(\"This client just lost it's session with ZooKeeper, will\"\n + \" automatically reconnect when needed.\");\n if (t instanceof KeeperException.SessionExpiredException) {\n LOG.info(\"ZK session expired. This disconnect could have been\" +\n \" caused by a network partition or a long-running GC pause,\" +\n \" either way it's recommended that you verify your environment.\");\n resetZooKeeperTrackers();\n }\n return;\n }\n if (t != null) LOG.fatal(msg, t);\n else LOG.fatal(msg);\n this.aborted = true;\n close();\n }\n\n @Override\n public boolean isClosed() {\n return this.closed;\n }\n\n @Override\n public boolean isAborted(){\n return this.aborted;\n }\n\n public int getCurrentNrHRS() throws IOException {\n try {\n ZooKeeperWatcher zkw = getZooKeeperWatcher();\n // We go to zk rather than to master to get count of regions to avoid\n // HTable having a Master dependency. See HBase-2828\n return ZKUtil.getNumberOfChildren(zkw,\n zkw.rsZNode);\n } catch (KeeperException ke) {\n throw new IOException(\"Unexpected ZooKeeper exception\", ke);\n }\n }\n\n public void stopProxyOnClose(boolean stopProxy) {\n this.stopProxy = stopProxy;\n }\n\n /**\n * Increment this client's reference count.\n */\n void incCount() {\n ++refCount;\n }\n\n /**\n * Decrement this client's reference count.\n */\n void decCount() {\n if (refCount > 0) {\n --refCount;\n }\n }\n\n /**\n * Return if this client has no reference\n *\n * @return true if this client has no reference; false otherwise\n */\n boolean isZeroReference() {\n return refCount == 0;\n }\n\n void close(boolean stopProxy) {\n if (this.closed) {\n return;\n }\n if (master != null) {\n if (stopProxy) {\n HBaseRPC.stopProxy(master);\n }\n master = null;\n masterChecked = false;\n }\n if (stopProxy) {\n for (HRegionInterface i : servers.values()) {\n HBaseRPC.stopProxy(i);\n }\n }\n this.servers.clear();\n if (this.zooKeeper != null) {\n LOG.info(\"Closed zookeeper sessionid=0x\" +\n Long.toHexString(this.zooKeeper.getRecoverableZooKeeper().getSessionId()));\n this.zooKeeper.close();\n this.zooKeeper = null;\n }\n this.closed = true;\n }\n\n public void close() {\n if (managed) {\n HConnectionManager.deleteConnection((HConnection)this, stopProxy, false);\n } else {\n close(true);\n }\n if (LOG.isTraceEnabled()) LOG.debug(\"\" + this.zooKeeper + \" closed.\");\n }\n\n /**\n * Close the connection for good, regardless of what the current value of\n * {@link #refCount} is. Ideally, {@link refCount} should be zero at this\n * point, which would be the case if all of its consumers close the\n * connection. However, on the off chance that someone is unable to close\n * the connection, perhaps because it bailed out prematurely, the method\n * below will ensure that this {@link Connection} instance is cleaned up.\n * Caveat: The JVM may take an unknown amount of time to call finalize on an\n * unreachable object, so our hope is that every consumer cleans up after\n * itself, like any good citizen.\n */\n @Override\n protected void finalize() throws Throwable {\n // Pretend as if we are about to release the last remaining reference\n refCount = 1;\n close();\n LOG.debug(\"The connection to \" + this.zooKeeper\n + \" was closed by the finalize method.\");\n }\n\n public HTableDescriptor[] listTables() throws IOException {\n if (this.master == null) {\n this.master = getMaster();\n }\n HTableDescriptor[] htd = master.getHTableDescriptors();\n return htd;\n }\n\n public HTableDescriptor[] getHTableDescriptors(List<String> tableNames) throws IOException {\n if (tableNames == null || tableNames.isEmpty()) return new HTableDescriptor[0];\n if (tableNames == null || tableNames.size() == 0) return null;\n if (this.master == null) {\n this.master = getMaster();\n }\n return master.getHTableDescriptors(tableNames);\n }\n\n public HTableDescriptor getHTableDescriptor(final byte[] tableName)\n throws IOException {\n if (tableName == null || tableName.length == 0) return null;\n if (Bytes.equals(tableName, HConstants.ROOT_TABLE_NAME)) {\n return new UnmodifyableHTableDescriptor(HTableDescriptor.ROOT_TABLEDESC);\n }\n if (Bytes.equals(tableName, HConstants.META_TABLE_NAME)) {\n return HTableDescriptor.META_TABLEDESC;\n }\n if (this.master == null) {\n this.master = getMaster();\n }\n HTableDescriptor hTableDescriptor = null;\n HTableDescriptor[] htds = master.getHTableDescriptors();\n if (htds != null && htds.length > 0) {\n for (HTableDescriptor htd: htds) {\n if (Bytes.equals(tableName, htd.getName())) {\n hTableDescriptor = htd;\n }\n }\n }\n //HTableDescriptor htd = master.getHTableDescriptor(tableName);\n if (hTableDescriptor == null) {\n throw new TableNotFoundException(Bytes.toString(tableName));\n }\n return hTableDescriptor;\n }\n }\n\n /**\n * Set the number of retries to use serverside when trying to communicate\n * with another server over {@link HConnection}. Used updating catalog\n * tables, etc. Call this method before we create any Connections.\n * @param c The Configuration instance to set the retries into.\n * @param log Used to log what we set in here.\n */\n public static void setServerSideHConnectionRetries(final Configuration c,\n final Log log) {\n int hcRetries = c.getInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER,\n HConstants.DEFAULT_HBASE_CLIENT_RETRIES_NUMBER);\n // Go big. Multiply by 10. If we can't get to meta after this many retries\n // then something seriously wrong.\n int serversideMultiplier =\n c.getInt(\"hbase.client.serverside.retries.multiplier\", 10);\n int retries = hcRetries * serversideMultiplier;\n c.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, retries);\n log.debug(\"Set serverside HConnection retries=\" + retries);\n }\n}", "public class HMaster extends HasThread\nimplements HMasterInterface, HMasterRegionInterface, MasterServices,\nServer {\n private static final Log LOG = LogFactory.getLog(HMaster.class.getName());\n\n // MASTER is name of the webapp and the attribute name used stuffing this\n //instance into web context.\n public static final String MASTER = \"master\";\n\n // The configuration for the Master\n private final Configuration conf;\n // server for the web ui\n private InfoServer infoServer;\n\n // Our zk client.\n private ZooKeeperWatcher zooKeeper;\n // Manager and zk listener for master election\n private ActiveMasterManager activeMasterManager;\n // Region server tracker\n private RegionServerTracker regionServerTracker;\n // Draining region server tracker\n private DrainingServerTracker drainingServerTracker;\n\n // RPC server for the HMaster\n private final RpcServer rpcServer;\n\n /**\n * This servers address.\n */\n private final InetSocketAddress isa;\n\n // Metrics for the HMaster\n private final MasterMetrics metrics;\n // file system manager for the master FS operations\n private MasterFileSystem fileSystemManager;\n\n // server manager to deal with region server info\n private ServerManager serverManager;\n\n // manager of assignment nodes in zookeeper\n AssignmentManager assignmentManager;\n // manager of catalog regions\n private CatalogTracker catalogTracker;\n // Cluster status zk tracker and local setter\n private ClusterStatusTracker clusterStatusTracker;\n \n // buffer for \"fatal error\" notices from region servers\n // in the cluster. This is only used for assisting\n // operations/debugging.\n private MemoryBoundedLogMessageBuffer rsFatals;\n\n // This flag is for stopping this Master instance. Its set when we are\n // stopping or aborting\n private volatile boolean stopped = false;\n // Set on abort -- usually failure of our zk session.\n private volatile boolean abort = false;\n // flag set after we become the active master (used for testing)\n private volatile boolean isActiveMaster = false;\n // flag set after we complete initialization once active (used for testing)\n private volatile boolean initialized = false;\n // flag set after we complete assignRootAndMeta.\n private volatile boolean serverShutdownHandlerEnabled = false;\n\n // Instance of the hbase executor service.\n ExecutorService executorService;\n\n private LoadBalancer balancer;\n private Thread balancerChore;\n // If 'true', the balancer is 'on'. If 'false', the balancer will not run.\n private volatile boolean balanceSwitch = true;\n\n private CatalogJanitor catalogJanitorChore;\n private LogCleaner logCleaner;\n\n private MasterCoprocessorHost cpHost;\n private final ServerName serverName;\n\n private TableDescriptors tableDescriptors;\n\n // Time stamps for when a hmaster was started and when it became active\n private long masterStartTime;\n private long masterActiveTime;\n\n /**\n * MX Bean for MasterInfo\n */\n private ObjectName mxBean = null;\n\n /**\n * Initializes the HMaster. The steps are as follows:\n * <p>\n * <ol>\n * <li>Initialize HMaster RPC and address\n * <li>Connect to ZooKeeper.\n * </ol>\n * <p>\n * Remaining steps of initialization occur in {@link #run()} so that they\n * run in their own thread rather than within the context of the constructor.\n * @throws InterruptedException\n */\n public HMaster(final Configuration conf)\n throws IOException, KeeperException, InterruptedException {\n this.conf = new Configuration(conf);\n // Disable the block cache on the master\n this.conf.setFloat(HConstants.HFILE_BLOCK_CACHE_SIZE_KEY, 0.0f);\n // Set how many times to retry talking to another server over HConnection.\n HConnectionManager.setServerSideHConnectionRetries(this.conf, LOG);\n // Server to handle client requests.\n String hostname = Strings.domainNamePointerToHostName(DNS.getDefaultHost(\n conf.get(\"hbase.master.dns.interface\", \"default\"),\n conf.get(\"hbase.master.dns.nameserver\", \"default\")));\n int port = conf.getInt(HConstants.MASTER_PORT, HConstants.DEFAULT_MASTER_PORT);\n // Creation of a HSA will force a resolve.\n InetSocketAddress initialIsa = new InetSocketAddress(hostname, port);\n if (initialIsa.getAddress() == null) {\n throw new IllegalArgumentException(\"Failed resolve of \" + this.isa);\n }\n int numHandlers = conf.getInt(\"hbase.master.handler.count\",\n conf.getInt(\"hbase.regionserver.handler.count\", 25));\n this.rpcServer = HBaseRPC.getServer(this,\n new Class<?>[]{HMasterInterface.class, HMasterRegionInterface.class},\n initialIsa.getHostName(), // BindAddress is IP we got for this server.\n initialIsa.getPort(),\n numHandlers,\n 0, // we dont use high priority handlers in master\n conf.getBoolean(\"hbase.rpc.verbose\", false), conf,\n 0); // this is a DNC w/o high priority handlers\n // Set our address.\n this.isa = this.rpcServer.getListenerAddress();\n this.serverName = new ServerName(this.isa.getHostName(),\n this.isa.getPort(), System.currentTimeMillis());\n this.rsFatals = new MemoryBoundedLogMessageBuffer(\n conf.getLong(\"hbase.master.buffer.for.rs.fatals\", 1*1024*1024));\n\n // initialize server principal (if using secure Hadoop)\n User.login(conf, \"hbase.master.keytab.file\",\n \"hbase.master.kerberos.principal\", this.isa.getHostName());\n\n // set the thread name now we have an address\n setName(MASTER + \"-\" + this.serverName.toString());\n\n Replication.decorateMasterConfiguration(this.conf);\n\n // Hack! Maps DFSClient => Master for logs. HDFS made this\n // config param for task trackers, but we can piggyback off of it.\n if (this.conf.get(\"mapred.task.id\") == null) {\n this.conf.set(\"mapred.task.id\", \"hb_m_\" + this.serverName.toString());\n }\n\n this.zooKeeper = new ZooKeeperWatcher(conf, MASTER + \":\" + isa.getPort(), this, true);\n this.rpcServer.startThreads();\n this.metrics = new MasterMetrics(getServerName().toString());\n }\n\n /**\n * Stall startup if we are designated a backup master; i.e. we want someone\n * else to become the master before proceeding.\n * @param c\n * @param amm\n * @throws InterruptedException\n */\n private static void stallIfBackupMaster(final Configuration c,\n final ActiveMasterManager amm)\n throws InterruptedException {\n // If we're a backup master, stall until a primary to writes his address\n if (!c.getBoolean(HConstants.MASTER_TYPE_BACKUP,\n HConstants.DEFAULT_MASTER_TYPE_BACKUP)) {\n return;\n }\n LOG.debug(\"HMaster started in backup mode. \" +\n \"Stalling until master znode is written.\");\n // This will only be a minute or so while the cluster starts up,\n // so don't worry about setting watches on the parent znode\n while (!amm.isActiveMaster()) {\n LOG.debug(\"Waiting for master address ZNode to be written \" +\n \"(Also watching cluster state node)\");\n Thread.sleep(c.getInt(\"zookeeper.session.timeout\", 180 * 1000));\n }\n \n }\n\n /**\n * Main processing loop for the HMaster.\n * <ol>\n * <li>Block until becoming active master\n * <li>Finish initialization via finishInitialization(MonitoredTask)\n * <li>Enter loop until we are stopped\n * <li>Stop services and perform cleanup once stopped\n * </ol>\n */\n @Override\n public void run() {\n MonitoredTask startupStatus =\n TaskMonitor.get().createStatus(\"Master startup\");\n startupStatus.setDescription(\"Master startup\");\n masterStartTime = System.currentTimeMillis();\n try {\n /*\n * Block on becoming the active master.\n *\n * We race with other masters to write our address into ZooKeeper. If we\n * succeed, we are the primary/active master and finish initialization.\n *\n * If we do not succeed, there is another active master and we should\n * now wait until it dies to try and become the next active master. If we\n * do not succeed on our first attempt, this is no longer a cluster startup.\n */\n becomeActiveMaster(startupStatus);\n\n // We are either the active master or we were asked to shutdown\n if (!this.stopped) {\n finishInitialization(startupStatus, false);\n loop();\n }\n } catch (Throwable t) {\n // HBASE-5680: Likely hadoop23 vs hadoop 20.x/1.x incompatibility\n if (t instanceof NoClassDefFoundError && \n t.getMessage().contains(\"org/apache/hadoop/hdfs/protocol/FSConstants$SafeModeAction\")) {\n // improved error message for this special case\n abort(\"HBase is having a problem with its Hadoop jars. You may need to \"\n + \"recompile HBase against Hadoop version \"\n + org.apache.hadoop.util.VersionInfo.getVersion()\n + \" or change your hadoop jars to start properly\", t);\n } else {\n abort(\"Unhandled exception. Starting shutdown.\", t);\n }\n } finally {\n startupStatus.cleanup();\n \n stopChores();\n // Wait for all the remaining region servers to report in IFF we were\n // running a cluster shutdown AND we were NOT aborting.\n if (!this.abort && this.serverManager != null &&\n this.serverManager.isClusterShutdown()) {\n this.serverManager.letRegionServersShutdown();\n }\n stopServiceThreads();\n // Stop services started for both backup and active masters\n if (this.activeMasterManager != null) this.activeMasterManager.stop();\n if (this.catalogTracker != null) this.catalogTracker.stop();\n if (this.serverManager != null) this.serverManager.stop();\n if (this.assignmentManager != null) this.assignmentManager.stop();\n if (this.fileSystemManager != null) this.fileSystemManager.stop();\n this.zooKeeper.close();\n }\n LOG.info(\"HMaster main thread exiting\");\n }\n\n /**\n * Try becoming active master.\n * @param startupStatus \n * @return True if we could successfully become the active master.\n * @throws InterruptedException\n */\n private boolean becomeActiveMaster(MonitoredTask startupStatus)\n throws InterruptedException {\n // TODO: This is wrong!!!! Should have new servername if we restart ourselves,\n // if we come back to life.\n this.activeMasterManager = new ActiveMasterManager(zooKeeper, this.serverName,\n this);\n this.zooKeeper.registerListener(activeMasterManager);\n stallIfBackupMaster(this.conf, this.activeMasterManager);\n\n // The ClusterStatusTracker is setup before the other\n // ZKBasedSystemTrackers because it's needed by the activeMasterManager\n // to check if the cluster should be shutdown.\n this.clusterStatusTracker = new ClusterStatusTracker(getZooKeeper(), this);\n this.clusterStatusTracker.start();\n return this.activeMasterManager.blockUntilBecomingActiveMaster(startupStatus,\n this.clusterStatusTracker);\n }\n\n /**\n * Initialize all ZK based system trackers.\n * @throws IOException\n * @throws InterruptedException\n */\n private void initializeZKBasedSystemTrackers() throws IOException,\n InterruptedException, KeeperException {\n this.catalogTracker = new CatalogTracker(this.zooKeeper, this.conf,\n this, conf.getInt(\"hbase.master.catalog.timeout\", Integer.MAX_VALUE));\n this.catalogTracker.start();\n\n this.balancer = LoadBalancerFactory.getLoadBalancer(conf);\n this.assignmentManager = new AssignmentManager(this, serverManager,\n this.catalogTracker, this.balancer, this.executorService);\n zooKeeper.registerListenerFirst(assignmentManager);\n\n this.regionServerTracker = new RegionServerTracker(zooKeeper, this,\n this.serverManager);\n this.regionServerTracker.start();\n\n this.drainingServerTracker = new DrainingServerTracker(zooKeeper, this,\n this.serverManager);\n this.drainingServerTracker.start();\n\n // Set the cluster as up. If new RSs, they'll be waiting on this before\n // going ahead with their startup.\n boolean wasUp = this.clusterStatusTracker.isClusterUp();\n if (!wasUp) this.clusterStatusTracker.setClusterUp();\n\n LOG.info(\"Server active/primary master; \" + this.serverName +\n \", sessionid=0x\" +\n Long.toHexString(this.zooKeeper.getRecoverableZooKeeper().getSessionId()) +\n \", cluster-up flag was=\" + wasUp);\n }\n\n // Check if we should stop every second.\n private Sleeper stopSleeper = new Sleeper(1000, this);\n private void loop() {\n while (!this.stopped) {\n stopSleeper.sleep();\n }\n }\n\n /**\n * Finish initialization of HMaster after becoming the primary master.\n *\n * <ol>\n * <li>Initialize master components - file system manager, server manager,\n * assignment manager, region server tracker, catalog tracker, etc</li>\n * <li>Start necessary service threads - rpc server, info server,\n * executor services, etc</li>\n * <li>Set cluster as UP in ZooKeeper</li>\n * <li>Wait for RegionServers to check-in</li>\n * <li>Split logs and perform data recovery, if necessary</li>\n * <li>Ensure assignment of root and meta regions<li>\n * <li>Handle either fresh cluster start or master failover</li>\n * </ol>\n * @param masterRecovery \n *\n * @throws IOException\n * @throws InterruptedException\n * @throws KeeperException\n */\n private void finishInitialization(MonitoredTask status, boolean masterRecovery)\n throws IOException, InterruptedException, KeeperException {\n\n isActiveMaster = true;\n\n /*\n * We are active master now... go initialize components we need to run.\n * Note, there may be dross in zk from previous runs; it'll get addressed\n * below after we determine if cluster startup or failover.\n */\n\n status.setStatus(\"Initializing Master file system\");\n this.masterActiveTime = System.currentTimeMillis();\n // TODO: Do this using Dependency Injection, using PicoContainer, Guice or Spring.\n this.fileSystemManager = new MasterFileSystem(this, this, metrics, masterRecovery);\n\n this.tableDescriptors =\n new FSTableDescriptors(this.fileSystemManager.getFileSystem(),\n this.fileSystemManager.getRootDir());\n\n // publish cluster ID\n status.setStatus(\"Publishing Cluster ID in ZooKeeper\");\n ClusterId.setClusterId(this.zooKeeper, fileSystemManager.getClusterId());\n if (!masterRecovery) {\n this.executorService = new ExecutorService(getServerName().toString());\n this.serverManager = new ServerManager(this, this);\n }\n\n\n status.setStatus(\"Initializing ZK system trackers\");\n initializeZKBasedSystemTrackers();\n \n if (!masterRecovery) {\n // initialize master side coprocessors before we start handling requests\n status.setStatus(\"Initializing master coprocessors\");\n this.cpHost = new MasterCoprocessorHost(this, this.conf);\n\n // start up all service threads.\n status.setStatus(\"Initializing master service threads\");\n startServiceThreads();\n }\n\n // Wait for region servers to report in.\n this.serverManager.waitForRegionServers(status);\n // Check zk for regionservers that are up but didn't register\n for (ServerName sn: this.regionServerTracker.getOnlineServers()) {\n if (!this.serverManager.isServerOnline(sn)) {\n // Not registered; add it.\n LOG.info(\"Registering server found up in zk but who has not yet \" +\n \"reported in: \" + sn);\n this.serverManager.recordNewServer(sn, HServerLoad.EMPTY_HSERVERLOAD);\n }\n }\n if (!masterRecovery) {\n this.assignmentManager.startTimeOutMonitor();\n }\n // TODO: Should do this in background rather than block master startup\n status.setStatus(\"Splitting logs after master startup\");\n splitLogAfterStartup(this.fileSystemManager);\n\n // Make sure root and meta assigned before proceeding.\n assignRootAndMeta(status);\n enableServerShutdownHandler();\n\n // Update meta with new HRI if required. i.e migrate all HRI with HTD to\n // HRI with out HTD in meta and update the status in ROOT. This must happen\n // before we assign all user regions or else the assignment will fail.\n // TODO: Remove this when we do 0.94.\n org.apache.hadoop.hbase.catalog.MetaMigrationRemovingHTD.\n updateMetaWithNewHRI(this);\n\n // Fixup assignment manager status\n status.setStatus(\"Starting assignment manager\");\n this.assignmentManager.joinCluster();\n\n this.balancer.setClusterStatus(getClusterStatus());\n this.balancer.setMasterServices(this);\n\n // Fixing up missing daughters if any\n status.setStatus(\"Fixing up missing daughters\");\n fixupDaughters(status);\n\n if (!masterRecovery) {\n // Start balancer and meta catalog janitor after meta and regions have\n // been assigned.\n status.setStatus(\"Starting balancer and catalog janitor\");\n this.balancerChore = getAndStartBalancerChore(this);\n this.catalogJanitorChore = new CatalogJanitor(this, this);\n startCatalogJanitorChore();\n registerMBean();\n }\n\n status.markComplete(\"Initialization successful\");\n LOG.info(\"Master has completed initialization\");\n initialized = true;\n\n // clear the dead servers with same host name and port of online server because we are not\n // removing dead server with same hostname and port of rs which is trying to check in before\n // master initialization. See HBASE-5916.\n this.serverManager.clearDeadServersWithSameHostNameAndPortOfOnlineServer();\n \n if (!masterRecovery) {\n if (this.cpHost != null) {\n // don't let cp initialization errors kill the master\n try {\n this.cpHost.postStartMaster();\n } catch (IOException ioe) {\n LOG.error(\"Coprocessor postStartMaster() hook failed\", ioe);\n }\n }\n }\n }\n \n /**\n * If ServerShutdownHandler is disabled, we enable it and expire those dead\n * but not expired servers.\n * \n * @throws IOException\n */\n private void enableServerShutdownHandler() throws IOException {\n if (!serverShutdownHandlerEnabled) {\n serverShutdownHandlerEnabled = true;\n this.serverManager.expireDeadNotExpiredServers();\n }\n }\n \n /**\n * Useful for testing purpose also where we have\n * master restart scenarios.\n */\n protected void startCatalogJanitorChore() {\n Threads.setDaemonThreadRunning(catalogJanitorChore.getThread());\n }\n\n /**\n * Override to change master's splitLogAfterStartup. Used testing\n * @param mfs\n */\n protected void splitLogAfterStartup(final MasterFileSystem mfs) {\n mfs.splitLogAfterStartup();\n }\n\n /**\n * Check <code>-ROOT-</code> and <code>.META.</code> are assigned. If not,\n * assign them.\n * @throws InterruptedException\n * @throws IOException\n * @throws KeeperException\n * @return Count of regions we assigned.\n */\n int assignRootAndMeta(MonitoredTask status)\n throws InterruptedException, IOException, KeeperException {\n int assigned = 0;\n long timeout = this.conf.getLong(\"hbase.catalog.verification.timeout\", 1000);\n\n // Work on ROOT region. Is it in zk in transition?\n status.setStatus(\"Assigning ROOT region\");\n boolean rit = this.assignmentManager.\n processRegionInTransitionAndBlockUntilAssigned(HRegionInfo.ROOT_REGIONINFO);\n ServerName currentRootServer = null;\n boolean rootRegionLocation = catalogTracker.verifyRootRegionLocation(timeout);\n if (!rit && !rootRegionLocation) {\n currentRootServer = this.catalogTracker.getRootLocation();\n splitLogAndExpireIfOnline(currentRootServer);\n this.assignmentManager.assignRoot();\n waitForRootAssignment();\n assigned++;\n } else if (rit && !rootRegionLocation) {\n waitForRootAssignment();\n assigned++;\n } else {\n // Region already assigned. We didn't assign it. Add to in-memory state.\n this.assignmentManager.regionOnline(HRegionInfo.ROOT_REGIONINFO,\n this.catalogTracker.getRootLocation());\n }\n // Enable the ROOT table if on process fail over the RS containing ROOT\n // was active.\n enableCatalogTables(Bytes.toString(HConstants.ROOT_TABLE_NAME));\n LOG.info(\"-ROOT- assigned=\" + assigned + \", rit=\" + rit +\n \", location=\" + catalogTracker.getRootLocation());\n\n // Work on meta region\n status.setStatus(\"Assigning META region\");\n rit = this.assignmentManager.\n processRegionInTransitionAndBlockUntilAssigned(HRegionInfo.FIRST_META_REGIONINFO);\n boolean metaRegionLocation = this.catalogTracker.verifyMetaRegionLocation(timeout);\n if (!rit && !metaRegionLocation) {\n ServerName currentMetaServer =\n this.catalogTracker.getMetaLocationOrReadLocationFromRoot();\n if (currentMetaServer != null\n && !currentMetaServer.equals(currentRootServer)) {\n splitLogAndExpireIfOnline(currentMetaServer);\n }\n assignmentManager.assignMeta();\n enableSSHandWaitForMeta();\n assigned++;\n } else if (rit && !metaRegionLocation) {\n enableSSHandWaitForMeta();\n assigned++;\n } else {\n // Region already assigned. We didnt' assign it. Add to in-memory state.\n this.assignmentManager.regionOnline(HRegionInfo.FIRST_META_REGIONINFO,\n this.catalogTracker.getMetaLocation());\n }\n enableCatalogTables(Bytes.toString(HConstants.META_TABLE_NAME));\n LOG.info(\".META. assigned=\" + assigned + \", rit=\" + rit +\n \", location=\" + catalogTracker.getMetaLocation());\n status.setStatus(\"META and ROOT assigned.\");\n return assigned;\n }\n\n private void enableSSHandWaitForMeta() throws IOException,\n InterruptedException {\n enableServerShutdownHandler();\n this.catalogTracker.waitForMeta();\n // Above check waits for general meta availability but this does not\n // guarantee that the transition has completed\n this.assignmentManager\n .waitForAssignment(HRegionInfo.FIRST_META_REGIONINFO);\n }\n\n private void waitForRootAssignment() throws InterruptedException {\n this.catalogTracker.waitForRoot();\n // This guarantees that the transition has completed\n this.assignmentManager.waitForAssignment(HRegionInfo.ROOT_REGIONINFO);\n }\n\n private void enableCatalogTables(String catalogTableName) {\n if (!this.assignmentManager.getZKTable().isEnabledTable(catalogTableName)) {\n this.assignmentManager.setEnabledTable(catalogTableName);\n }\n }\n\n void fixupDaughters(final MonitoredTask status) throws IOException {\n final Map<HRegionInfo, Result> offlineSplitParents =\n new HashMap<HRegionInfo, Result>();\n // This visitor collects offline split parents in the .META. table\n MetaReader.Visitor visitor = new MetaReader.Visitor() {\n @Override\n public boolean visit(Result r) throws IOException {\n if (r == null || r.isEmpty()) return true;\n HRegionInfo info =\n MetaReader.parseHRegionInfoFromCatalogResult(\n r, HConstants.REGIONINFO_QUALIFIER);\n if (info == null) return true; // Keep scanning\n if (info.isOffline() && info.isSplit()) {\n offlineSplitParents.put(info, r);\n }\n // Returning true means \"keep scanning\"\n return true;\n }\n };\n // Run full scan of .META. catalog table passing in our custom visitor\n MetaReader.fullScan(this.catalogTracker, visitor);\n // Now work on our list of found parents. See if any we can clean up.\n int fixups = 0;\n for (Map.Entry<HRegionInfo, Result> e : offlineSplitParents.entrySet()) {\n fixups += ServerShutdownHandler.fixupDaughters(\n e.getValue(), assignmentManager, catalogTracker);\n }\n if (fixups != 0) {\n LOG.info(\"Scanned the catalog and fixed up \" + fixups +\n \" missing daughter region(s)\");\n }\n }\n\n /**\n * Split a server's log and expire it if we find it is one of the online\n * servers.\n * @param sn ServerName to check.\n * @throws IOException\n */\n private void splitLogAndExpireIfOnline(final ServerName sn)\n throws IOException {\n if (sn == null || !serverManager.isServerOnline(sn)) {\n return;\n }\n LOG.info(\"Forcing splitLog and expire of \" + sn);\n fileSystemManager.splitLog(sn);\n serverManager.expireServer(sn);\n }\n\n @Override\n public ProtocolSignature getProtocolSignature(\n String protocol, long version, int clientMethodsHashCode)\n throws IOException {\n if (HMasterInterface.class.getName().equals(protocol)) {\n return new ProtocolSignature(HMasterInterface.VERSION, null);\n } else if (HMasterRegionInterface.class.getName().equals(protocol)) {\n return new ProtocolSignature(HMasterRegionInterface.VERSION, null);\n }\n throw new IOException(\"Unknown protocol: \" + protocol);\n }\n\n public long getProtocolVersion(String protocol, long clientVersion) {\n if (HMasterInterface.class.getName().equals(protocol)) {\n return HMasterInterface.VERSION;\n } else if (HMasterRegionInterface.class.getName().equals(protocol)) {\n return HMasterRegionInterface.VERSION;\n }\n // unknown protocol\n LOG.warn(\"Version requested for unimplemented protocol: \"+protocol);\n return -1;\n }\n\n @Override\n public TableDescriptors getTableDescriptors() {\n return this.tableDescriptors;\n }\n\n /** @return InfoServer object. Maybe null.*/\n public InfoServer getInfoServer() {\n return this.infoServer;\n }\n\n @Override\n public Configuration getConfiguration() {\n return this.conf;\n }\n\n @Override\n public ServerManager getServerManager() {\n return this.serverManager;\n }\n\n @Override\n public ExecutorService getExecutorService() {\n return this.executorService;\n }\n\n @Override\n public MasterFileSystem getMasterFileSystem() {\n return this.fileSystemManager;\n }\n\n /**\n * Get the ZK wrapper object - needed by master_jsp.java\n * @return the zookeeper wrapper\n */\n public ZooKeeperWatcher getZooKeeperWatcher() {\n return this.zooKeeper;\n }\n\n /*\n * Start up all services. If any of these threads gets an unhandled exception\n * then they just die with a logged message. This should be fine because\n * in general, we do not expect the master to get such unhandled exceptions\n * as OOMEs; it should be lightly loaded. See what HRegionServer does if\n * need to install an unexpected exception handler.\n */\n private void startServiceThreads() throws IOException{\n \n // Start the executor service pools\n this.executorService.startExecutorService(ExecutorType.MASTER_OPEN_REGION,\n conf.getInt(\"hbase.master.executor.openregion.threads\", 5));\n this.executorService.startExecutorService(ExecutorType.MASTER_CLOSE_REGION,\n conf.getInt(\"hbase.master.executor.closeregion.threads\", 5));\n this.executorService.startExecutorService(ExecutorType.MASTER_SERVER_OPERATIONS,\n conf.getInt(\"hbase.master.executor.serverops.threads\", 3));\n this.executorService.startExecutorService(ExecutorType.MASTER_META_SERVER_OPERATIONS,\n conf.getInt(\"hbase.master.executor.serverops.threads\", 5));\n \n // We depend on there being only one instance of this executor running\n // at a time. To do concurrency, would need fencing of enable/disable of\n // tables.\n this.executorService.startExecutorService(ExecutorType.MASTER_TABLE_OPERATIONS, 1);\n\n // Start log cleaner thread\n String n = Thread.currentThread().getName();\n this.logCleaner =\n new LogCleaner(conf.getInt(\"hbase.master.cleaner.interval\", 60 * 1000),\n this, conf, getMasterFileSystem().getFileSystem(),\n getMasterFileSystem().getOldLogDir());\n Threads.setDaemonThreadRunning(logCleaner.getThread(), n + \".oldLogCleaner\");\n\n // Put up info server.\n int port = this.conf.getInt(\"hbase.master.info.port\", 60010);\n if (port >= 0) {\n String a = this.conf.get(\"hbase.master.info.bindAddress\", \"0.0.0.0\");\n this.infoServer = new InfoServer(MASTER, a, port, false, this.conf);\n this.infoServer.addServlet(\"status\", \"/master-status\", MasterStatusServlet.class);\n this.infoServer.addServlet(\"dump\", \"/dump\", MasterDumpServlet.class);\n this.infoServer.setAttribute(MASTER, this);\n this.infoServer.start();\n }\n \n // Start allowing requests to happen.\n this.rpcServer.openServer();\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"Started service threads\");\n }\n\n }\n\n private void stopServiceThreads() {\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"Stopping service threads\");\n }\n if (this.rpcServer != null) this.rpcServer.stop();\n // Clean up and close up shop\n if (this.logCleaner!= null) this.logCleaner.interrupt();\n if (this.infoServer != null) {\n LOG.info(\"Stopping infoServer\");\n try {\n this.infoServer.stop();\n } catch (Exception ex) {\n ex.printStackTrace();\n }\n }\n if (this.executorService != null) this.executorService.shutdown();\n }\n\n private static Thread getAndStartBalancerChore(final HMaster master) {\n String name = master.getServerName() + \"-BalancerChore\";\n int balancerPeriod =\n master.getConfiguration().getInt(\"hbase.balancer.period\", 300000);\n // Start up the load balancer chore\n Chore chore = new Chore(name, balancerPeriod, master) {\n @Override\n protected void chore() {\n master.balance();\n }\n };\n return Threads.setDaemonThreadRunning(chore.getThread());\n }\n\n private void stopChores() {\n if (this.balancerChore != null) {\n this.balancerChore.interrupt();\n }\n if (this.catalogJanitorChore != null) {\n this.catalogJanitorChore.interrupt();\n }\n }\n\n @Override\n public MapWritable regionServerStartup(final int port,\n final long serverStartCode, final long serverCurrentTime)\n throws IOException {\n // Register with server manager\n InetAddress ia = HBaseServer.getRemoteIp();\n ServerName rs = this.serverManager.regionServerStartup(ia, port,\n serverStartCode, serverCurrentTime);\n // Send back some config info\n MapWritable mw = createConfigurationSubset();\n mw.put(new Text(HConstants.KEY_FOR_HOSTNAME_SEEN_BY_MASTER),\n new Text(rs.getHostname()));\n return mw;\n }\n\n /**\n * @return Subset of configuration to pass initializing regionservers: e.g.\n * the filesystem to use and root directory to use.\n */\n protected MapWritable createConfigurationSubset() {\n MapWritable mw = addConfig(new MapWritable(), HConstants.HBASE_DIR);\n return addConfig(mw, \"fs.default.name\");\n }\n\n private MapWritable addConfig(final MapWritable mw, final String key) {\n mw.put(new Text(key), new Text(this.conf.get(key)));\n return mw;\n }\n\n @Override\n public void regionServerReport(final byte [] sn, final HServerLoad hsl)\n throws IOException {\n this.serverManager.regionServerReport(ServerName.parseVersionedServerName(sn), hsl);\n if (hsl != null && this.metrics != null) {\n // Up our metrics.\n this.metrics.incrementRequests(hsl.getTotalNumberOfRequests());\n }\n }\n\n @Override\n public void reportRSFatalError(byte [] sn, String errorText) {\n String msg = \"Region server \" + Bytes.toString(sn) +\n \" reported a fatal error:\\n\" + errorText;\n LOG.error(msg);\n rsFatals.add(msg);\n }\n\n public boolean isMasterRunning() {\n return !isStopped();\n }\n\n /**\n * @return Maximum time we should run balancer for\n */\n private int getBalancerCutoffTime() {\n int balancerCutoffTime =\n getConfiguration().getInt(\"hbase.balancer.max.balancing\", -1);\n if (balancerCutoffTime == -1) {\n // No time period set so create one -- do half of balancer period.\n int balancerPeriod =\n getConfiguration().getInt(\"hbase.balancer.period\", 300000);\n balancerCutoffTime = balancerPeriod / 2;\n // If nonsense period, set it to balancerPeriod\n if (balancerCutoffTime <= 0) balancerCutoffTime = balancerPeriod;\n }\n return balancerCutoffTime;\n }\n\n @Override\n public boolean balance() {\n // if master not initialized, don't run balancer.\n if (!this.initialized) {\n LOG.debug(\"Master has not been initialized, don't run balancer.\");\n return false;\n }\n // If balance not true, don't run balancer.\n if (!this.balanceSwitch) return false;\n // Do this call outside of synchronized block.\n int maximumBalanceTime = getBalancerCutoffTime();\n long cutoffTime = System.currentTimeMillis() + maximumBalanceTime;\n boolean balancerRan;\n synchronized (this.balancer) {\n // Only allow one balance run at at time.\n if (this.assignmentManager.isRegionsInTransition()) {\n LOG.debug(\"Not running balancer because \" +\n this.assignmentManager.getRegionsInTransition().size() +\n \" region(s) in transition: \" +\n org.apache.commons.lang.StringUtils.\n abbreviate(this.assignmentManager.getRegionsInTransition().toString(), 256));\n return false;\n }\n if (this.serverManager.areDeadServersInProgress()) {\n LOG.debug(\"Not running balancer because processing dead regionserver(s): \" +\n this.serverManager.getDeadServers());\n return false;\n }\n\n if (this.cpHost != null) {\n try {\n if (this.cpHost.preBalance()) {\n LOG.debug(\"Coprocessor bypassing balancer request\");\n return false;\n }\n } catch (IOException ioe) {\n LOG.error(\"Error invoking master coprocessor preBalance()\", ioe);\n return false;\n }\n }\n\n Map<String, Map<ServerName, List<HRegionInfo>>> assignmentsByTable =\n this.assignmentManager.getAssignmentsByTable();\n\n List<RegionPlan> plans = new ArrayList<RegionPlan>();\n for (Map<ServerName, List<HRegionInfo>> assignments : assignmentsByTable.values()) {\n List<RegionPlan> partialPlans = this.balancer.balanceCluster(assignments);\n if (partialPlans != null) plans.addAll(partialPlans);\n }\n int rpCount = 0; // number of RegionPlans balanced so far\n long totalRegPlanExecTime = 0;\n balancerRan = plans != null;\n if (plans != null && !plans.isEmpty()) {\n for (RegionPlan plan: plans) {\n LOG.info(\"balance \" + plan);\n long balStartTime = System.currentTimeMillis();\n this.assignmentManager.balance(plan);\n totalRegPlanExecTime += System.currentTimeMillis()-balStartTime;\n rpCount++;\n if (rpCount < plans.size() &&\n // if performing next balance exceeds cutoff time, exit the loop\n (System.currentTimeMillis() + (totalRegPlanExecTime / rpCount)) > cutoffTime) {\n LOG.debug(\"No more balancing till next balance run; maximumBalanceTime=\" +\n maximumBalanceTime);\n break;\n }\n }\n }\n if (this.cpHost != null) {\n try {\n this.cpHost.postBalance();\n } catch (IOException ioe) {\n // balancing already succeeded so don't change the result\n LOG.error(\"Error invoking master coprocessor postBalance()\", ioe);\n }\n }\n }\n return balancerRan;\n }\n\n enum BalanceSwitchMode {\n SYNC,\n ASYNC\n }\n /**\n * Assigns balancer switch according to BalanceSwitchMode\n * @param b new balancer switch\n * @param mode BalanceSwitchMode\n * @return old balancer switch\n */\n public boolean switchBalancer(final boolean b, BalanceSwitchMode mode) {\n boolean oldValue = this.balanceSwitch;\n boolean newValue = b;\n try {\n if (this.cpHost != null) {\n newValue = this.cpHost.preBalanceSwitch(newValue);\n }\n if (mode == BalanceSwitchMode.SYNC) {\n synchronized (this.balancer) { \n this.balanceSwitch = newValue;\n }\n } else {\n this.balanceSwitch = newValue; \n }\n LOG.info(\"BalanceSwitch=\" + newValue);\n if (this.cpHost != null) {\n this.cpHost.postBalanceSwitch(oldValue, newValue);\n }\n } catch (IOException ioe) {\n LOG.warn(\"Error flipping balance switch\", ioe);\n }\n return oldValue; \n }\n \n @Override\n public boolean synchronousBalanceSwitch(final boolean b) {\n return switchBalancer(b, BalanceSwitchMode.SYNC);\n }\n \n @Override\n public boolean balanceSwitch(final boolean b) {\n return switchBalancer(b, BalanceSwitchMode.ASYNC);\n }\n\n /**\n * Switch for the background CatalogJanitor thread.\n * Used for testing. The thread will continue to run. It will just be a noop\n * if disabled.\n * @param b If false, the catalog janitor won't do anything.\n */\n public void setCatalogJanitorEnabled(final boolean b) {\n ((CatalogJanitor)this.catalogJanitorChore).setEnabled(b);\n }\n\n @Override\n public void move(final byte[] encodedRegionName, final byte[] destServerName)\n throws UnknownRegionException {\n Pair<HRegionInfo, ServerName> p =\n this.assignmentManager.getAssignment(encodedRegionName);\n if (p == null)\n throw new UnknownRegionException(Bytes.toStringBinary(encodedRegionName));\n ServerName dest = null;\n if (destServerName == null || destServerName.length == 0) {\n LOG.info(\"Passed destination servername is null or empty so choosing a server at random\");\n List<ServerName> destServers = this.serverManager.getOnlineServersList();\n destServers.remove(p.getSecond());\n // If i have only one RS then destination can be null.\n dest = balancer.randomAssignment(destServers);\n } else {\n dest = new ServerName(Bytes.toString(destServerName));\n }\n \n // Now we can do the move\n RegionPlan rp = new RegionPlan(p.getFirst(), p.getSecond(), dest);\n \n try {\n if (this.cpHost != null) {\n if (this.cpHost.preMove(p.getFirst(), p.getSecond(), dest)) {\n return;\n }\n }\n LOG.info(\"Added move plan \" + rp + \", running balancer\");\n this.assignmentManager.balance(rp);\n if (this.cpHost != null) {\n this.cpHost.postMove(p.getFirst(), p.getSecond(), dest);\n }\n } catch (IOException ioe) {\n UnknownRegionException ure = new UnknownRegionException(\n Bytes.toStringBinary(encodedRegionName));\n ure.initCause(ioe);\n throw ure;\n }\n\n }\n\n public void createTable(HTableDescriptor hTableDescriptor,\n byte [][] splitKeys)\n throws IOException {\n if (!isMasterRunning()) {\n throw new MasterNotRunningException();\n }\n\n HRegionInfo [] newRegions = getHRegionInfos(hTableDescriptor, splitKeys);\n checkInitialized();\n if (cpHost != null) {\n cpHost.preCreateTable(hTableDescriptor, newRegions);\n }\n\n this.executorService.submit(new CreateTableHandler(this,\n this.fileSystemManager, this.serverManager, hTableDescriptor, conf,\n newRegions, catalogTracker, assignmentManager));\n\n if (cpHost != null) {\n cpHost.postCreateTable(hTableDescriptor, newRegions);\n }\n }\n\n private HRegionInfo[] getHRegionInfos(HTableDescriptor hTableDescriptor,\n byte[][] splitKeys) {\n HRegionInfo[] hRegionInfos = null;\n if (splitKeys == null || splitKeys.length == 0) {\n hRegionInfos = new HRegionInfo[]{\n new HRegionInfo(hTableDescriptor.getName(), null, null)};\n } else {\n int numRegions = splitKeys.length + 1;\n hRegionInfos = new HRegionInfo[numRegions];\n byte[] startKey = null;\n byte[] endKey = null;\n for (int i = 0; i < numRegions; i++) {\n endKey = (i == splitKeys.length) ? null : splitKeys[i];\n hRegionInfos[i] =\n new HRegionInfo(hTableDescriptor.getName(), startKey, endKey);\n startKey = endKey;\n }\n }\n return hRegionInfos;\n }\n\n private static boolean isCatalogTable(final byte [] tableName) {\n return Bytes.equals(tableName, HConstants.ROOT_TABLE_NAME) ||\n Bytes.equals(tableName, HConstants.META_TABLE_NAME);\n }\n\n @Override\n public void deleteTable(final byte [] tableName) throws IOException {\n checkInitialized();\n if (cpHost != null) {\n cpHost.preDeleteTable(tableName);\n }\n this.executorService.submit(new DeleteTableHandler(tableName, this, this));\n if (cpHost != null) {\n cpHost.postDeleteTable(tableName);\n }\n }\n\n /**\n * Get the number of regions of the table that have been updated by the alter.\n *\n * @return Pair indicating the number of regions updated Pair.getFirst is the\n * regions that are yet to be updated Pair.getSecond is the total number\n * of regions of the table\n * @throws IOException \n */\n public Pair<Integer, Integer> getAlterStatus(byte[] tableName)\n throws IOException {\n return this.assignmentManager.getReopenStatus(tableName);\n }\n\n public void addColumn(byte [] tableName, HColumnDescriptor column)\n throws IOException {\n checkInitialized();\n if (cpHost != null) {\n if (cpHost.preAddColumn(tableName, column)) {\n return;\n }\n }\n new TableAddFamilyHandler(tableName, column, this, this).process();\n if (cpHost != null) {\n cpHost.postAddColumn(tableName, column);\n }\n }\n\n public void modifyColumn(byte [] tableName, HColumnDescriptor descriptor)\n throws IOException {\n checkInitialized();\n if (cpHost != null) {\n if (cpHost.preModifyColumn(tableName, descriptor)) {\n return;\n }\n }\n new TableModifyFamilyHandler(tableName, descriptor, this, this).process();\n if (cpHost != null) {\n cpHost.postModifyColumn(tableName, descriptor);\n }\n }\n\n public void deleteColumn(final byte [] tableName, final byte [] c)\n throws IOException {\n checkInitialized();\n if (cpHost != null) {\n if (cpHost.preDeleteColumn(tableName, c)) {\n return;\n }\n }\n new TableDeleteFamilyHandler(tableName, c, this, this).process();\n if (cpHost != null) {\n cpHost.postDeleteColumn(tableName, c);\n }\n }\n\n public void enableTable(final byte [] tableName) throws IOException {\n checkInitialized();\n if (cpHost != null) {\n cpHost.preEnableTable(tableName);\n }\n this.executorService.submit(new EnableTableHandler(this, tableName,\n catalogTracker, assignmentManager, false));\n\n if (cpHost != null) {\n cpHost.postEnableTable(tableName);\n }\n }\n\n public void disableTable(final byte [] tableName) throws IOException {\n checkInitialized();\n if (cpHost != null) {\n cpHost.preDisableTable(tableName);\n }\n this.executorService.submit(new DisableTableHandler(this, tableName,\n catalogTracker, assignmentManager, false));\n\n if (cpHost != null) {\n cpHost.postDisableTable(tableName);\n }\n }\n\n /**\n * Return the region and current deployment for the region containing\n * the given row. If the region cannot be found, returns null. If it\n * is found, but not currently deployed, the second element of the pair\n * may be null.\n */\n Pair<HRegionInfo, ServerName> getTableRegionForRow(\n final byte [] tableName, final byte [] rowKey)\n throws IOException {\n final AtomicReference<Pair<HRegionInfo, ServerName>> result =\n new AtomicReference<Pair<HRegionInfo, ServerName>>(null);\n\n MetaScannerVisitor visitor =\n new MetaScannerVisitorBase() {\n @Override\n public boolean processRow(Result data) throws IOException {\n if (data == null || data.size() <= 0) {\n return true;\n }\n Pair<HRegionInfo, ServerName> pair = MetaReader.parseCatalogResult(data);\n if (pair == null) {\n return false;\n }\n if (!Bytes.equals(pair.getFirst().getTableName(), tableName)) {\n return false;\n }\n result.set(pair);\n return true;\n }\n };\n\n MetaScanner.metaScan(conf, visitor, tableName, rowKey, 1);\n return result.get();\n }\n\n @Override\n public void modifyTable(final byte[] tableName, HTableDescriptor htd)\n throws IOException {\n checkInitialized();\n if (cpHost != null) {\n cpHost.preModifyTable(tableName, htd);\n }\n this.executorService.submit(new ModifyTableHandler(tableName, htd, this, this));\n if (cpHost != null) {\n cpHost.postModifyTable(tableName, htd);\n }\n }\n\n @Override\n public void checkTableModifiable(final byte [] tableName)\n throws IOException {\n String tableNameStr = Bytes.toString(tableName);\n if (isCatalogTable(tableName)) {\n throw new IOException(\"Can't modify catalog tables\");\n }\n if (!MetaReader.tableExists(getCatalogTracker(), tableNameStr)) {\n throw new TableNotFoundException(tableNameStr);\n }\n if (!getAssignmentManager().getZKTable().\n isDisabledTable(Bytes.toString(tableName))) {\n throw new TableNotDisabledException(tableName);\n }\n }\n\n public void clearFromTransition(HRegionInfo hri) {\n if (this.assignmentManager.isRegionInTransition(hri) != null) {\n this.assignmentManager.regionOffline(hri);\n }\n }\n\n /**\n * @return cluster status\n */\n public ClusterStatus getClusterStatus() {\n // Build Set of backup masters from ZK nodes\n List<String> backupMasterStrings;\n try {\n backupMasterStrings = ZKUtil.listChildrenNoWatch(this.zooKeeper,\n this.zooKeeper.backupMasterAddressesZNode);\n } catch (KeeperException e) {\n LOG.warn(this.zooKeeper.prefix(\"Unable to list backup servers\"), e);\n backupMasterStrings = new ArrayList<String>(0);\n }\n List<ServerName> backupMasters = new ArrayList<ServerName>(\n backupMasterStrings.size());\n for (String s: backupMasterStrings) {\n try {\n byte[] bytes = ZKUtil.getData(this.zooKeeper, ZKUtil.joinZNode(this.zooKeeper.backupMasterAddressesZNode, s));\n if (bytes != null) {\n backupMasters.add(ServerName.parseVersionedServerName(bytes));\n }\n } catch (KeeperException e) {\n LOG.warn(this.zooKeeper.prefix(\"Unable to get information about \" +\n \"backup servers\"), e);\n }\n }\n Collections.sort(backupMasters, new Comparator<ServerName>() {\n public int compare(ServerName s1, ServerName s2) {\n return s1.getServerName().compareTo(s2.getServerName());\n }});\n\n return new ClusterStatus(VersionInfo.getVersion(),\n this.fileSystemManager.getClusterId(),\n this.serverManager.getOnlineServers(),\n this.serverManager.getDeadServers(),\n this.serverName,\n backupMasters,\n this.assignmentManager.getRegionsInTransition(),\n this.getCoprocessors());\n }\n\n public String getClusterId() {\n return fileSystemManager.getClusterId();\n }\n\n /**\n * The set of loaded coprocessors is stored in a static set. Since it's\n * statically allocated, it does not require that HMaster's cpHost be\n * initialized prior to accessing it.\n * @return a String representation of the set of names of the loaded\n * coprocessors.\n */\n public static String getLoadedCoprocessors() {\n return CoprocessorHost.getLoadedCoprocessors().toString();\n }\n\n /**\n * @return timestamp in millis when HMaster was started.\n */\n public long getMasterStartTime() {\n return masterStartTime;\n }\n\n /**\n * @return timestamp in millis when HMaster became the active master.\n */\n public long getMasterActiveTime() {\n return masterActiveTime;\n }\n\n /**\n * @return array of coprocessor SimpleNames.\n */\n public String[] getCoprocessors() {\n Set<String> masterCoprocessors =\n getCoprocessorHost().getCoprocessors();\n return masterCoprocessors.toArray(new String[0]);\n }\n\n @Override\n public void abort(final String msg, final Throwable t) {\n if (cpHost != null) {\n // HBASE-4014: dump a list of loaded coprocessors.\n LOG.fatal(\"Master server abort: loaded coprocessors are: \" +\n getLoadedCoprocessors());\n }\n\n if (abortNow(msg, t)) {\n if (t != null) LOG.fatal(msg, t);\n else LOG.fatal(msg);\n this.abort = true;\n stop(\"Aborting\");\n }\n }\n\n /**\n * We do the following in a different thread. If it is not completed\n * in time, we will time it out and assume it is not easy to recover.\n *\n * 1. Create a new ZK session. (since our current one is expired)\n * 2. Try to become a primary master again\n * 3. Initialize all ZK based system trackers.\n * 4. Assign root and meta. (they are already assigned, but we need to update our\n * internal memory state to reflect it)\n * 5. Process any RIT if any during the process of our recovery.\n *\n * @return True if we could successfully recover from ZK session expiry.\n * @throws InterruptedException\n * @throws IOException\n * @throws KeeperException\n * @throws ExecutionException\n */\n private boolean tryRecoveringExpiredZKSession() throws InterruptedException,\n IOException, KeeperException, ExecutionException {\n\n this.zooKeeper.reconnectAfterExpiration();\n\n Callable<Boolean> callable = new Callable<Boolean> () {\n public Boolean call() throws InterruptedException,\n IOException, KeeperException {\n MonitoredTask status =\n TaskMonitor.get().createStatus(\"Recovering expired ZK session\");\n try {\n if (!becomeActiveMaster(status)) {\n return Boolean.FALSE;\n }\n serverShutdownHandlerEnabled = false;\n initialized = false;\n finishInitialization(status, true);\n return Boolean.TRUE;\n } finally {\n status.cleanup();\n }\n }\n };\n\n long timeout =\n conf.getLong(\"hbase.master.zksession.recover.timeout\", 300000);\n java.util.concurrent.ExecutorService executor =\n Executors.newSingleThreadExecutor();\n Future<Boolean> result = executor.submit(callable);\n executor.shutdown();\n if (executor.awaitTermination(timeout, TimeUnit.MILLISECONDS)\n && result.isDone()) {\n Boolean recovered = result.get();\n if (recovered != null) {\n return recovered.booleanValue();\n }\n }\n executor.shutdownNow();\n return false;\n }\n\n /**\n * Check to see if the current trigger for abort is due to ZooKeeper session\n * expiry, and If yes, whether we can recover from ZK session expiry.\n *\n * @param msg Original abort message\n * @param t The cause for current abort request\n * @return true if we should proceed with abort operation, false other wise.\n */\n private boolean abortNow(final String msg, final Throwable t) {\n if (!this.isActiveMaster) {\n return true;\n }\n if (t != null && t instanceof KeeperException.SessionExpiredException) {\n try {\n LOG.info(\"Primary Master trying to recover from ZooKeeper session \" +\n \"expiry.\");\n return !tryRecoveringExpiredZKSession();\n } catch (Throwable newT) {\n LOG.error(\"Primary master encountered unexpected exception while \" +\n \"trying to recover from ZooKeeper session\" +\n \" expiry. Proceeding with server abort.\", newT);\n }\n }\n return true;\n }\n\n @Override\n public ZooKeeperWatcher getZooKeeper() {\n return zooKeeper;\n }\n\n public MasterCoprocessorHost getCoprocessorHost() {\n return cpHost;\n }\n\n @Override\n public ServerName getServerName() {\n return this.serverName;\n }\n\n @Override\n public CatalogTracker getCatalogTracker() {\n return catalogTracker;\n }\n\n @Override\n public AssignmentManager getAssignmentManager() {\n return this.assignmentManager;\n }\n \n public MemoryBoundedLogMessageBuffer getRegionServerFatalLogBuffer() {\n return rsFatals;\n }\n\n @SuppressWarnings(\"deprecation\")\n @Override\n public void shutdown() {\n if (cpHost != null) {\n try {\n cpHost.preShutdown();\n } catch (IOException ioe) {\n LOG.error(\"Error call master coprocessor preShutdown()\", ioe);\n }\n }\n if (mxBean != null) {\n MBeanUtil.unregisterMBean(mxBean);\n mxBean = null;\n }\n if (this.assignmentManager != null) this.assignmentManager.shutdown();\n if (this.serverManager != null) this.serverManager.shutdownCluster();\n try {\n if (this.clusterStatusTracker != null){\n this.clusterStatusTracker.setClusterDown();\n }\n } catch (KeeperException e) {\n LOG.error(\"ZooKeeper exception trying to set cluster as down in ZK\", e);\n }\n }\n\n @Override\n public void stopMaster() {\n if (cpHost != null) {\n try {\n cpHost.preStopMaster();\n } catch (IOException ioe) {\n LOG.error(\"Error call master coprocessor preStopMaster()\", ioe);\n }\n }\n stop(\"Stopped by \" + Thread.currentThread().getName());\n }\n\n @Override\n public void stop(final String why) {\n LOG.info(why);\n this.stopped = true;\n // We wake up the stopSleeper to stop immediately\n stopSleeper.skipSleepCycle();\n // If we are a backup master, we need to interrupt wait\n if (this.activeMasterManager != null) {\n synchronized (this.activeMasterManager.clusterHasActiveMaster) {\n this.activeMasterManager.clusterHasActiveMaster.notifyAll();\n }\n }\n }\n\n @Override\n public boolean isStopped() {\n return this.stopped;\n }\n\n public boolean isAborted() {\n return this.abort;\n }\n \n void checkInitialized() throws PleaseHoldException {\n if (!this.initialized) {\n throw new PleaseHoldException(\"Master is initializing\");\n }\n }\n \n /**\n * Report whether this master is currently the active master or not.\n * If not active master, we are parked on ZK waiting to become active.\n *\n * This method is used for testing.\n *\n * @return true if active master, false if not.\n */\n public boolean isActiveMaster() {\n return isActiveMaster;\n }\n\n /**\n * Report whether this master has completed with its initialization and is\n * ready. If ready, the master is also the active master. A standby master\n * is never ready.\n *\n * This method is used for testing.\n *\n * @return true if master is ready to go, false if not.\n */\n public boolean isInitialized() {\n return initialized;\n }\n\n /**\n * ServerShutdownHandlerEnabled is set false before completing\n * assignRootAndMeta to prevent processing of ServerShutdownHandler.\n * @return true if assignRootAndMeta has completed;\n */\n public boolean isServerShutdownHandlerEnabled() {\n return this.serverShutdownHandlerEnabled;\n }\n\n @Override\n @Deprecated\n public void assign(final byte[] regionName, final boolean force)\n throws IOException {\n assign(regionName);\n }\n\n @Override\n public void assign(final byte [] regionName)throws IOException {\n checkInitialized();\n Pair<HRegionInfo, ServerName> pair =\n MetaReader.getRegion(this.catalogTracker, regionName);\n if (pair == null) throw new UnknownRegionException(Bytes.toString(regionName));\n if (cpHost != null) {\n if (cpHost.preAssign(pair.getFirst())) {\n return;\n }\n }\n assignRegion(pair.getFirst());\n if (cpHost != null) {\n cpHost.postAssign(pair.getFirst());\n }\n }\n \n \n\n public void assignRegion(HRegionInfo hri) {\n assignmentManager.assign(hri, true);\n }\n\n @Override\n public void unassign(final byte [] regionName, final boolean force)\n throws IOException {\n checkInitialized();\n Pair<HRegionInfo, ServerName> pair =\n MetaReader.getRegion(this.catalogTracker, regionName);\n if (pair == null) throw new UnknownRegionException(Bytes.toString(regionName));\n HRegionInfo hri = pair.getFirst();\n if (cpHost != null) {\n if (cpHost.preUnassign(hri, force)) {\n return;\n }\n }\n if (force) {\n this.assignmentManager.regionOffline(hri);\n assignRegion(hri);\n } else {\n this.assignmentManager.unassign(hri, force);\n }\n if (cpHost != null) {\n cpHost.postUnassign(hri, force);\n }\n }\n\n /**\n * Get HTD array for given tables \n * @param tableNames\n * @return HTableDescriptor[]\n */\n public HTableDescriptor[] getHTableDescriptors(List<String> tableNames) {\n List<HTableDescriptor> list =\n new ArrayList<HTableDescriptor>(tableNames.size());\n for (String s: tableNames) {\n HTableDescriptor htd = null;\n try {\n htd = this.tableDescriptors.get(s);\n } catch (IOException e) {\n LOG.warn(\"Failed getting descriptor for \" + s, e);\n }\n if (htd == null) continue;\n list.add(htd);\n }\n return list.toArray(new HTableDescriptor [] {});\n }\n\n /**\n * Get all table descriptors\n * @return All descriptors or null if none.\n */\n public HTableDescriptor [] getHTableDescriptors() {\n Map<String, HTableDescriptor> descriptors = null;\n try {\n descriptors = this.tableDescriptors.getAll();\n } catch (IOException e) {\n LOG.warn(\"Failed getting all descriptors\", e);\n }\n return descriptors == null?\n null: descriptors.values().toArray(new HTableDescriptor [] {});\n }\n\n /**\n * Compute the average load across all region servers.\n * Currently, this uses a very naive computation - just uses the number of\n * regions being served, ignoring stats about number of requests.\n * @return the average load\n */\n public double getAverageLoad() {\n return this.assignmentManager.getAverageLoad();\n }\n\n /**\n * Special method, only used by hbck.\n */\n @Override\n public void offline(final byte[] regionName) throws IOException {\n Pair<HRegionInfo, ServerName> pair =\n MetaReader.getRegion(this.catalogTracker, regionName);\n if (pair == null) throw new UnknownRegionException(Bytes.toStringBinary(regionName));\n HRegionInfo hri = pair.getFirst();\n this.assignmentManager.regionOffline(hri);\n }\n\n /**\n * Utility for constructing an instance of the passed HMaster class.\n * @param masterClass\n * @param conf\n * @return HMaster instance.\n */\n public static HMaster constructMaster(Class<? extends HMaster> masterClass,\n final Configuration conf) {\n try {\n Constructor<? extends HMaster> c =\n masterClass.getConstructor(Configuration.class);\n return c.newInstance(conf);\n } catch (InvocationTargetException ite) {\n Throwable target = ite.getTargetException() != null?\n ite.getTargetException(): ite;\n if (target.getCause() != null) target = target.getCause();\n throw new RuntimeException(\"Failed construction of Master: \" +\n masterClass.toString(), target);\n } catch (Exception e) {\n throw new RuntimeException(\"Failed construction of Master: \" +\n masterClass.toString() + ((e.getCause() != null)?\n e.getCause().getMessage(): \"\"), e);\n }\n }\n\n /**\n * @see org.apache.hadoop.hbase.master.HMasterCommandLine\n */\n public static void main(String [] args) throws Exception {\n\tVersionInfo.logVersion();\n new HMasterCommandLine(HMaster.class).doMain(args);\n }\n\n /**\n * Register bean with platform management server\n */\n @SuppressWarnings(\"deprecation\")\n void registerMBean() {\n MXBeanImpl mxBeanInfo = MXBeanImpl.init(this);\n MBeanUtil.registerMBean(\"Master\", \"Master\", mxBeanInfo);\n LOG.info(\"Registered HMaster MXBean\");\n }\n}", "public class HRegion implements HeapSize { // , Writable{\n public static final Log LOG = LogFactory.getLog(HRegion.class);\n private static final String MERGEDIR = \".merges\";\n\n final AtomicBoolean closed = new AtomicBoolean(false);\n /* Closing can take some time; use the closing flag if there is stuff we don't\n * want to do while in closing state; e.g. like offer this region up to the\n * master as a region to close if the carrying regionserver is overloaded.\n * Once set, it is never cleared.\n */\n final AtomicBoolean closing = new AtomicBoolean(false);\n\n //////////////////////////////////////////////////////////////////////////////\n // Members\n //////////////////////////////////////////////////////////////////////////////\n\n private final ConcurrentHashMap<HashedBytes, CountDownLatch> lockedRows =\n new ConcurrentHashMap<HashedBytes, CountDownLatch>();\n private final ConcurrentHashMap<Integer, HashedBytes> lockIds =\n new ConcurrentHashMap<Integer, HashedBytes>();\n private final AtomicInteger lockIdGenerator = new AtomicInteger(1);\n static private Random rand = new Random();\n\n protected final Map<byte [], Store> stores =\n new ConcurrentSkipListMap<byte [], Store>(Bytes.BYTES_RAWCOMPARATOR);\n\n // Registered region protocol handlers\n private ClassToInstanceMap<CoprocessorProtocol>\n protocolHandlers = MutableClassToInstanceMap.create();\n\n private Map<String, Class<? extends CoprocessorProtocol>>\n protocolHandlerNames = Maps.newHashMap();\n\n /**\n * Temporary subdirectory of the region directory used for compaction output.\n */\n public static final String REGION_TEMP_SUBDIR = \".tmp\";\n\n //These variable are just used for getting data out of the region, to test on\n //client side\n // private int numStores = 0;\n // private int [] storeSize = null;\n // private byte [] name = null;\n\n final AtomicLong memstoreSize = new AtomicLong(0);\n\n // Debug possible data loss due to WAL off\n final AtomicLong numPutsWithoutWAL = new AtomicLong(0);\n final AtomicLong dataInMemoryWithoutWAL = new AtomicLong(0);\n\n final Counter readRequestsCount = new Counter();\n final Counter writeRequestsCount = new Counter();\n\n /**\n * The directory for the table this region is part of.\n * This directory contains the directory for this region.\n */\n final Path tableDir;\n\n final HLog log;\n final FileSystem fs;\n final Configuration conf;\n final int rowLockWaitDuration;\n static final int DEFAULT_ROWLOCK_WAIT_DURATION = 30000;\n final HRegionInfo regionInfo;\n final Path regiondir;\n KeyValue.KVComparator comparator;\n\n private ConcurrentHashMap<RegionScanner, Long> scannerReadPoints;\n\n /*\n * @return The smallest mvcc readPoint across all the scanners in this\n * region. Writes older than this readPoint, are included in every\n * read operation.\n */\n public long getSmallestReadPoint() {\n long minimumReadPoint;\n // We need to ensure that while we are calculating the smallestReadPoint\n // no new RegionScanners can grab a readPoint that we are unaware of.\n // We achieve this by synchronizing on the scannerReadPoints object.\n synchronized(scannerReadPoints) {\n minimumReadPoint = mvcc.memstoreReadPoint();\n\n for (Long readPoint: this.scannerReadPoints.values()) {\n if (readPoint < minimumReadPoint) {\n minimumReadPoint = readPoint;\n }\n }\n }\n return minimumReadPoint;\n }\n /*\n * Data structure of write state flags used coordinating flushes,\n * compactions and closes.\n */\n static class WriteState {\n // Set while a memstore flush is happening.\n volatile boolean flushing = false;\n // Set when a flush has been requested.\n volatile boolean flushRequested = false;\n // Number of compactions running.\n volatile int compacting = 0;\n // Gets set in close. If set, cannot compact or flush again.\n volatile boolean writesEnabled = true;\n // Set if region is read-only\n volatile boolean readOnly = false;\n\n /**\n * Set flags that make this region read-only.\n *\n * @param onOff flip value for region r/o setting\n */\n synchronized void setReadOnly(final boolean onOff) {\n this.writesEnabled = !onOff;\n this.readOnly = onOff;\n }\n\n boolean isReadOnly() {\n return this.readOnly;\n }\n\n boolean isFlushRequested() {\n return this.flushRequested;\n }\n\n static final long HEAP_SIZE = ClassSize.align(\n ClassSize.OBJECT + 5 * Bytes.SIZEOF_BOOLEAN);\n }\n\n final WriteState writestate = new WriteState();\n\n long memstoreFlushSize;\n final long timestampSlop;\n private volatile long lastFlushTime;\n final RegionServerServices rsServices;\n private RegionServerAccounting rsAccounting;\n private List<Pair<Long, Long>> recentFlushes = new ArrayList<Pair<Long,Long>>();\n private long blockingMemStoreSize;\n final long threadWakeFrequency;\n // Used to guard closes\n final ReentrantReadWriteLock lock =\n new ReentrantReadWriteLock();\n\n // Stop updates lock\n private final ReentrantReadWriteLock updatesLock =\n new ReentrantReadWriteLock();\n private boolean splitRequest;\n private byte[] explicitSplitPoint = null;\n\n private final MultiVersionConsistencyControl mvcc =\n new MultiVersionConsistencyControl();\n\n // Coprocessor host\n private RegionCoprocessorHost coprocessorHost;\n\n /**\n * Name of the region info file that resides just under the region directory.\n */\n public final static String REGIONINFO_FILE = \".regioninfo\";\n private HTableDescriptor htableDescriptor = null;\n private RegionSplitPolicy splitPolicy;\n private final OperationMetrics opMetrics;\n\n /**\n * Should only be used for testing purposes\n */\n public HRegion(){\n this.tableDir = null;\n this.blockingMemStoreSize = 0L;\n this.conf = null;\n this.rowLockWaitDuration = DEFAULT_ROWLOCK_WAIT_DURATION;\n this.rsServices = null;\n this.fs = null;\n this.timestampSlop = HConstants.LATEST_TIMESTAMP;\n this.memstoreFlushSize = 0L;\n this.log = null;\n this.regiondir = null;\n this.regionInfo = null;\n this.htableDescriptor = null;\n this.threadWakeFrequency = 0L;\n this.coprocessorHost = null;\n this.scannerReadPoints = new ConcurrentHashMap<RegionScanner, Long>();\n this.opMetrics = new OperationMetrics();\n }\n\n /**\n * HRegion constructor. his constructor should only be used for testing and\n * extensions. Instances of HRegion should be instantiated with the\n * {@link HRegion#newHRegion(Path, HLog, FileSystem, Configuration, HRegionInfo, HTableDescriptor, RegionServerServices)} method.\n *\n *\n * @param tableDir qualified path of directory where region should be located,\n * usually the table directory.\n * @param log The HLog is the outbound log for any updates to the HRegion\n * (There's a single HLog for all the HRegions on a single HRegionServer.)\n * The log file is a logfile from the previous execution that's\n * custom-computed for this HRegion. The HRegionServer computes and sorts the\n * appropriate log info for this HRegion. If there is a previous log file\n * (implying that the HRegion has been written-to before), then read it from\n * the supplied path.\n * @param fs is the filesystem.\n * @param conf is global configuration settings.\n * @param regionInfo - HRegionInfo that describes the region\n * is new), then read them from the supplied path.\n * @param rsServices reference to {@link RegionServerServices} or null\n *\n * @see HRegion#newHRegion(Path, HLog, FileSystem, Configuration, HRegionInfo, HTableDescriptor, RegionServerServices)\n */\n public HRegion(Path tableDir, HLog log, FileSystem fs, Configuration conf,\n final HRegionInfo regionInfo, final HTableDescriptor htd,\n RegionServerServices rsServices) {\n this.tableDir = tableDir;\n this.comparator = regionInfo.getComparator();\n this.log = log;\n this.fs = fs;\n this.conf = conf;\n this.rowLockWaitDuration = conf.getInt(\"hbase.rowlock.wait.duration\",\n DEFAULT_ROWLOCK_WAIT_DURATION);\n this.regionInfo = regionInfo;\n this.htableDescriptor = htd;\n this.rsServices = rsServices;\n this.threadWakeFrequency = conf.getLong(HConstants.THREAD_WAKE_FREQUENCY,\n 10 * 1000);\n String encodedNameStr = this.regionInfo.getEncodedName();\n setHTableSpecificConf();\n this.regiondir = getRegionDir(this.tableDir, encodedNameStr);\n this.scannerReadPoints = new ConcurrentHashMap<RegionScanner, Long>();\n this.opMetrics = new OperationMetrics(conf, this.regionInfo);\n\n /*\n * timestamp.slop provides a server-side constraint on the timestamp. This\n * assumes that you base your TS around currentTimeMillis(). In this case,\n * throw an error to the user if the user-specified TS is newer than now +\n * slop. LATEST_TIMESTAMP == don't use this functionality\n */\n this.timestampSlop = conf.getLong(\n \"hbase.hregion.keyvalue.timestamp.slop.millisecs\",\n HConstants.LATEST_TIMESTAMP);\n\n if (rsServices != null) {\n this.rsAccounting = this.rsServices.getRegionServerAccounting();\n // don't initialize coprocessors if not running within a regionserver\n // TODO: revisit if coprocessors should load in other cases\n this.coprocessorHost = new RegionCoprocessorHost(this, rsServices, conf);\n }\n if (LOG.isDebugEnabled()) {\n // Write out region name as string and its encoded name.\n LOG.debug(\"Instantiated \" + this);\n }\n }\n\n void setHTableSpecificConf() {\n if (this.htableDescriptor == null) return;\n LOG.info(\"Setting up tabledescriptor config now ...\");\n long flushSize = this.htableDescriptor.getMemStoreFlushSize();\n\n if (flushSize == HTableDescriptor.DEFAULT_MEMSTORE_FLUSH_SIZE) {\n flushSize = conf.getLong(HConstants.HREGION_MEMSTORE_FLUSH_SIZE,\n HTableDescriptor.DEFAULT_MEMSTORE_FLUSH_SIZE);\n }\n this.memstoreFlushSize = flushSize;\n this.blockingMemStoreSize = this.memstoreFlushSize *\n conf.getLong(\"hbase.hregion.memstore.block.multiplier\", 2);\n }\n\n /**\n * Initialize this region.\n * @return What the next sequence (edit) id should be.\n * @throws IOException e\n */\n public long initialize() throws IOException {\n return initialize(null);\n }\n\n /**\n * Initialize this region.\n *\n * @param reporter Tickle every so often if initialize is taking a while.\n * @return What the next sequence (edit) id should be.\n * @throws IOException e\n */\n public long initialize(final CancelableProgressable reporter)\n throws IOException {\n\n MonitoredTask status = TaskMonitor.get().createStatus(\n \"Initializing region \" + this);\n\n long nextSeqId = -1;\n try {\n nextSeqId = initializeRegionInternals(reporter, status);\n return nextSeqId;\n } finally {\n // nextSeqid will be -1 if the initialization fails.\n // At least it will be 0 otherwise.\n if (nextSeqId == -1) {\n status.abort(\"Exception during region \" + this.getRegionNameAsString()\n + \" initialization.\");\n }\n }\n }\n\n private long initializeRegionInternals(final CancelableProgressable reporter,\n MonitoredTask status) throws IOException, UnsupportedEncodingException {\n if (coprocessorHost != null) {\n status.setStatus(\"Running coprocessor pre-open hook\");\n coprocessorHost.preOpen();\n }\n\n // Write HRI to a file in case we need to recover .META.\n status.setStatus(\"Writing region info on filesystem\");\n checkRegioninfoOnFilesystem();\n\n // Remove temporary data left over from old regions\n status.setStatus(\"Cleaning up temporary data from old regions\");\n cleanupTmpDir();\n\n // Load in all the HStores.\n // Get minimum of the maxSeqId across all the store.\n //\n // Context: During replay we want to ensure that we do not lose any data. So, we\n // have to be conservative in how we replay logs. For each store, we calculate\n // the maxSeqId up to which the store was flushed. But, since different stores\n // could have a different maxSeqId, we choose the\n // minimum across all the stores.\n // This could potentially result in duplication of data for stores that are ahead\n // of others. ColumnTrackers in the ScanQueryMatchers do the de-duplication, so we\n // do not have to worry.\n // TODO: If there is a store that was never flushed in a long time, we could replay\n // a lot of data. Currently, this is not a problem because we flush all the stores at\n // the same time. If we move to per-cf flushing, we might want to revisit this and send\n // in a vector of maxSeqIds instead of sending in a single number, which has to be the\n // min across all the max.\n long minSeqId = -1;\n long maxSeqId = -1;\n // initialized to -1 so that we pick up MemstoreTS from column families\n long maxMemstoreTS = -1;\n\n if (this.htableDescriptor != null &&\n !htableDescriptor.getFamilies().isEmpty()) {\n // initialize the thread pool for opening stores in parallel.\n ThreadPoolExecutor storeOpenerThreadPool =\n getStoreOpenAndCloseThreadPool(\n \"StoreOpenerThread-\" + this.regionInfo.getRegionNameAsString());\n CompletionService<Store> completionService =\n new ExecutorCompletionService<Store>(storeOpenerThreadPool);\n\n // initialize each store in parallel\n for (final HColumnDescriptor family : htableDescriptor.getFamilies()) {\n status.setStatus(\"Instantiating store for column family \" + family);\n completionService.submit(new Callable<Store>() {\n public Store call() throws IOException {\n return instantiateHStore(tableDir, family);\n }\n });\n }\n try {\n for (int i = 0; i < htableDescriptor.getFamilies().size(); i++) {\n Future<Store> future = completionService.take();\n Store store = future.get();\n\n this.stores.put(store.getColumnFamilyName().getBytes(), store);\n long storeSeqId = store.getMaxSequenceId();\n if (minSeqId == -1 || storeSeqId < minSeqId) {\n minSeqId = storeSeqId;\n }\n if (maxSeqId == -1 || storeSeqId > maxSeqId) {\n maxSeqId = storeSeqId;\n }\n long maxStoreMemstoreTS = store.getMaxMemstoreTS();\n if (maxStoreMemstoreTS > maxMemstoreTS) {\n maxMemstoreTS = maxStoreMemstoreTS;\n }\n }\n } catch (InterruptedException e) {\n throw new IOException(e);\n } catch (ExecutionException e) {\n throw new IOException(e.getCause());\n } finally {\n storeOpenerThreadPool.shutdownNow();\n }\n }\n mvcc.initialize(maxMemstoreTS + 1);\n // Recover any edits if available.\n maxSeqId = Math.max(maxSeqId, replayRecoveredEditsIfAny(\n this.regiondir, minSeqId, reporter, status));\n\n status.setStatus(\"Cleaning up detritus from prior splits\");\n // Get rid of any splits or merges that were lost in-progress. Clean out\n // these directories here on open. We may be opening a region that was\n // being split but we crashed in the middle of it all.\n SplitTransaction.cleanupAnySplitDetritus(this);\n FSUtils.deleteDirectory(this.fs, new Path(regiondir, MERGEDIR));\n\n this.writestate.setReadOnly(this.htableDescriptor.isReadOnly());\n\n this.writestate.flushRequested = false;\n this.writestate.compacting = 0;\n\n // Initialize split policy\n this.splitPolicy = RegionSplitPolicy.create(this, conf);\n\n this.lastFlushTime = EnvironmentEdgeManager.currentTimeMillis();\n // Use maximum of log sequenceid or that which was found in stores\n // (particularly if no recovered edits, seqid will be -1).\n long nextSeqid = maxSeqId + 1;\n LOG.info(\"Onlined \" + this.toString() + \"; next sequenceid=\" + nextSeqid);\n\n // A region can be reopened if failed a split; reset flags\n this.closing.set(false);\n this.closed.set(false);\n\n if (coprocessorHost != null) {\n status.setStatus(\"Running coprocessor post-open hooks\");\n coprocessorHost.postOpen();\n }\n\n status.markComplete(\"Region opened successfully\");\n return nextSeqid;\n }\n\n /*\n * Move any passed HStore files into place (if any). Used to pick up split\n * files and any merges from splits and merges dirs.\n * @param initialFiles\n * @throws IOException\n */\n static void moveInitialFilesIntoPlace(final FileSystem fs,\n final Path initialFiles, final Path regiondir)\n throws IOException {\n if (initialFiles != null && fs.exists(initialFiles)) {\n if (!fs.rename(initialFiles, regiondir)) {\n LOG.warn(\"Unable to rename \" + initialFiles + \" to \" + regiondir);\n }\n }\n }\n\n /**\n * @return True if this region has references.\n */\n public boolean hasReferences() {\n for (Store store : this.stores.values()) {\n for (StoreFile sf : store.getStorefiles()) {\n // Found a reference, return.\n if (sf.isReference()) return true;\n }\n }\n return false;\n }\n\n /**\n * This function will return the HDFS blocks distribution based on the data\n * captured when HFile is created\n * @return The HDFS blocks distribution for the region.\n */\n public HDFSBlocksDistribution getHDFSBlocksDistribution() {\n HDFSBlocksDistribution hdfsBlocksDistribution =\n new HDFSBlocksDistribution();\n synchronized (this.stores) {\n for (Store store : this.stores.values()) {\n for (StoreFile sf : store.getStorefiles()) {\n HDFSBlocksDistribution storeFileBlocksDistribution =\n sf.getHDFSBlockDistribution();\n hdfsBlocksDistribution.add(storeFileBlocksDistribution);\n }\n }\n }\n return hdfsBlocksDistribution;\n }\n\n /**\n * This is a helper function to compute HDFS block distribution on demand\n * @param conf configuration\n * @param tableDescriptor HTableDescriptor of the table\n * @param regionEncodedName encoded name of the region\n * @return The HDFS blocks distribution for the given region.\n * @throws IOException\n */\n static public HDFSBlocksDistribution computeHDFSBlocksDistribution(\n Configuration conf, HTableDescriptor tableDescriptor,\n String regionEncodedName) throws IOException {\n HDFSBlocksDistribution hdfsBlocksDistribution =\n new HDFSBlocksDistribution();\n Path tablePath = FSUtils.getTablePath(FSUtils.getRootDir(conf),\n tableDescriptor.getName());\n FileSystem fs = tablePath.getFileSystem(conf);\n\n for (HColumnDescriptor family: tableDescriptor.getFamilies()) {\n Path storeHomeDir = Store.getStoreHomedir(tablePath, regionEncodedName,\n family.getName());\n if (!fs.exists(storeHomeDir))continue;\n\n FileStatus[] hfilesStatus = null;\n hfilesStatus = fs.listStatus(storeHomeDir);\n\n for (FileStatus hfileStatus : hfilesStatus) {\n HDFSBlocksDistribution storeFileBlocksDistribution =\n FSUtils.computeHDFSBlocksDistribution(fs, hfileStatus, 0,\n hfileStatus.getLen());\n hdfsBlocksDistribution.add(storeFileBlocksDistribution);\n }\n }\n return hdfsBlocksDistribution;\n }\n\n public AtomicLong getMemstoreSize() {\n return memstoreSize;\n }\n\n /**\n * Increase the size of mem store in this region and the size of global mem\n * store\n * @param memStoreSize\n * @return the size of memstore in this region\n */\n public long addAndGetGlobalMemstoreSize(long memStoreSize) {\n if (this.rsAccounting != null) {\n rsAccounting.addAndGetGlobalMemstoreSize(memStoreSize);\n } \n return this.memstoreSize.getAndAdd(memStoreSize);\n }\n\n /*\n * Write out an info file under the region directory. Useful recovering\n * mangled regions.\n * @throws IOException\n */\n private void checkRegioninfoOnFilesystem() throws IOException {\n Path regioninfoPath = new Path(this.regiondir, REGIONINFO_FILE);\n if (this.fs.exists(regioninfoPath) &&\n this.fs.getFileStatus(regioninfoPath).getLen() > 0) {\n return;\n }\n // Create in tmpdir and then move into place in case we crash after\n // create but before close. If we don't successfully close the file,\n // subsequent region reopens will fail the below because create is\n // registered in NN.\n\n // first check to get the permissions\n FsPermission perms = FSUtils.getFilePermissions(fs, conf,\n HConstants.DATA_FILE_UMASK_KEY);\n\n // and then create the file\n Path tmpPath = new Path(getTmpDir(), REGIONINFO_FILE);\n \n // if datanode crashes or if the RS goes down just before the close is called while trying to\n // close the created regioninfo file in the .tmp directory then on next\n // creation we will be getting AlreadyCreatedException.\n // Hence delete and create the file if exists.\n if (FSUtils.isExists(fs, tmpPath)) {\n FSUtils.delete(fs, tmpPath, true);\n }\n \n FSDataOutputStream out = FSUtils.create(fs, tmpPath, perms);\n\n try {\n this.regionInfo.write(out);\n out.write('\\n');\n out.write('\\n');\n out.write(Bytes.toBytes(this.regionInfo.toString()));\n } finally {\n out.close();\n }\n if (!fs.rename(tmpPath, regioninfoPath)) {\n throw new IOException(\"Unable to rename \" + tmpPath + \" to \" +\n regioninfoPath);\n }\n }\n\n /** @return a HRegionInfo object for this region */\n public HRegionInfo getRegionInfo() {\n return this.regionInfo;\n }\n\n /**\n * @return Instance of {@link RegionServerServices} used by this HRegion.\n * Can be null.\n */\n RegionServerServices getRegionServerServices() {\n return this.rsServices;\n }\n\n /** @return requestsCount for this region */\n public long getRequestsCount() {\n return this.readRequestsCount.get() + this.writeRequestsCount.get();\n }\n\n /** @return readRequestsCount for this region */\n public long getReadRequestsCount() {\n return this.readRequestsCount.get();\n }\n\n /** @return writeRequestsCount for this region */\n public long getWriteRequestsCount() {\n return this.writeRequestsCount.get();\n }\n\n /** @return true if region is closed */\n public boolean isClosed() {\n return this.closed.get();\n }\n\n /**\n * @return True if closing process has started.\n */\n public boolean isClosing() {\n return this.closing.get();\n }\n\n /** @return true if region is available (not closed and not closing) */\n public boolean isAvailable() {\n return !isClosed() && !isClosing();\n }\n\n /** @return true if region is splittable */\n public boolean isSplittable() {\n return isAvailable() && !hasReferences();\n }\n\n boolean areWritesEnabled() {\n synchronized(this.writestate) {\n return this.writestate.writesEnabled;\n }\n }\n\n public MultiVersionConsistencyControl getMVCC() {\n return mvcc;\n }\n\n /**\n * Close down this HRegion. Flush the cache, shut down each HStore, don't\n * service any more calls.\n *\n * <p>This method could take some time to execute, so don't call it from a\n * time-sensitive thread.\n *\n * @return Vector of all the storage files that the HRegion's component\n * HStores make use of. It's a list of all HStoreFile objects. Returns empty\n * vector if already closed and null if judged that it should not close.\n *\n * @throws IOException e\n */\n public List<StoreFile> close() throws IOException {\n return close(false);\n }\n\n private final Object closeLock = new Object();\n\n /**\n * Close down this HRegion. Flush the cache unless abort parameter is true,\n * Shut down each HStore, don't service any more calls.\n *\n * This method could take some time to execute, so don't call it from a\n * time-sensitive thread.\n *\n * @param abort true if server is aborting (only during testing)\n * @return Vector of all the storage files that the HRegion's component\n * HStores make use of. It's a list of HStoreFile objects. Can be null if\n * we are not to close at this time or we are already closed.\n *\n * @throws IOException e\n */\n public List<StoreFile> close(final boolean abort) throws IOException {\n // Only allow one thread to close at a time. Serialize them so dual\n // threads attempting to close will run up against each other.\n MonitoredTask status = TaskMonitor.get().createStatus(\n \"Closing region \" + this +\n (abort ? \" due to abort\" : \"\"));\n\n status.setStatus(\"Waiting for close lock\");\n try {\n synchronized (closeLock) {\n return doClose(abort, status);\n }\n } finally {\n status.cleanup();\n }\n }\n\n private List<StoreFile> doClose(\n final boolean abort, MonitoredTask status)\n throws IOException {\n if (isClosed()) {\n LOG.warn(\"Region \" + this + \" already closed\");\n return null;\n }\n\n if (coprocessorHost != null) {\n status.setStatus(\"Running coprocessor pre-close hooks\");\n this.coprocessorHost.preClose(abort);\n }\n\n status.setStatus(\"Disabling compacts and flushes for region\");\n boolean wasFlushing = false;\n synchronized (writestate) {\n // Disable compacting and flushing by background threads for this\n // region.\n writestate.writesEnabled = false;\n wasFlushing = writestate.flushing;\n LOG.debug(\"Closing \" + this + \": disabling compactions & flushes\");\n while (writestate.compacting > 0 || writestate.flushing) {\n LOG.debug(\"waiting for \" + writestate.compacting + \" compactions\" +\n (writestate.flushing ? \" & cache flush\" : \"\") +\n \" to complete for region \" + this);\n try {\n writestate.wait();\n } catch (InterruptedException iex) {\n // continue\n }\n }\n }\n // If we were not just flushing, is it worth doing a preflush...one\n // that will clear out of the bulk of the memstore before we put up\n // the close flag?\n if (!abort && !wasFlushing && worthPreFlushing()) {\n status.setStatus(\"Pre-flushing region before close\");\n LOG.info(\"Running close preflush of \" + this.getRegionNameAsString());\n internalFlushcache(status);\n }\n\n this.closing.set(true);\n status.setStatus(\"Disabling writes for close\");\n lock.writeLock().lock();\n try {\n if (this.isClosed()) {\n status.abort(\"Already got closed by another process\");\n // SplitTransaction handles the null\n return null;\n }\n LOG.debug(\"Updates disabled for region \" + this);\n // Don't flush the cache if we are aborting\n if (!abort) {\n internalFlushcache(status);\n }\n\n List<StoreFile> result = new ArrayList<StoreFile>();\n if (!stores.isEmpty()) {\n // initialize the thread pool for closing stores in parallel.\n ThreadPoolExecutor storeCloserThreadPool =\n getStoreOpenAndCloseThreadPool(\"StoreCloserThread-\"\n + this.regionInfo.getRegionNameAsString());\n CompletionService<ImmutableList<StoreFile>> completionService =\n new ExecutorCompletionService<ImmutableList<StoreFile>>(\n storeCloserThreadPool);\n\n // close each store in parallel\n for (final Store store : stores.values()) {\n completionService\n .submit(new Callable<ImmutableList<StoreFile>>() {\n public ImmutableList<StoreFile> call() throws IOException {\n return store.close();\n }\n });\n }\n try {\n for (int i = 0; i < stores.size(); i++) {\n Future<ImmutableList<StoreFile>> future = completionService\n .take();\n ImmutableList<StoreFile> storeFileList = future.get();\n result.addAll(storeFileList);\n }\n } catch (InterruptedException e) {\n throw new IOException(e);\n } catch (ExecutionException e) {\n throw new IOException(e.getCause());\n } finally {\n storeCloserThreadPool.shutdownNow();\n }\n }\n this.closed.set(true);\n\n if (coprocessorHost != null) {\n status.setStatus(\"Running coprocessor post-close hooks\");\n this.coprocessorHost.postClose(abort);\n }\n this.opMetrics.closeMetrics();\n status.markComplete(\"Closed\");\n LOG.info(\"Closed \" + this);\n return result;\n } finally {\n lock.writeLock().unlock();\n }\n }\n\n protected ThreadPoolExecutor getStoreOpenAndCloseThreadPool(\n final String threadNamePrefix) {\n int numStores = Math.max(1, this.htableDescriptor.getFamilies().size());\n int maxThreads = Math.min(numStores,\n conf.getInt(HConstants.HSTORE_OPEN_AND_CLOSE_THREADS_MAX,\n HConstants.DEFAULT_HSTORE_OPEN_AND_CLOSE_THREADS_MAX));\n return getOpenAndCloseThreadPool(maxThreads, threadNamePrefix);\n }\n\n protected ThreadPoolExecutor getStoreFileOpenAndCloseThreadPool(\n final String threadNamePrefix) {\n int numStores = Math.max(1, this.htableDescriptor.getFamilies().size());\n int maxThreads = Math.max(1,\n conf.getInt(HConstants.HSTORE_OPEN_AND_CLOSE_THREADS_MAX,\n HConstants.DEFAULT_HSTORE_OPEN_AND_CLOSE_THREADS_MAX)\n / numStores);\n return getOpenAndCloseThreadPool(maxThreads, threadNamePrefix);\n }\n\n private ThreadPoolExecutor getOpenAndCloseThreadPool(int maxThreads,\n final String threadNamePrefix) {\n ThreadPoolExecutor openAndCloseThreadPool = Threads\n .getBoundedCachedThreadPool(maxThreads, 30L, TimeUnit.SECONDS,\n new ThreadFactory() {\n private int count = 1;\n\n public Thread newThread(Runnable r) {\n Thread t = new Thread(r, threadNamePrefix + \"-\" + count++);\n return t;\n }\n });\n return openAndCloseThreadPool;\n }\n\n /**\n * @return True if its worth doing a flush before we put up the close flag.\n */\n private boolean worthPreFlushing() {\n return this.memstoreSize.get() >\n this.conf.getLong(\"hbase.hregion.preclose.flush.size\", 1024 * 1024 * 5);\n }\n\n //////////////////////////////////////////////////////////////////////////////\n // HRegion accessors\n //////////////////////////////////////////////////////////////////////////////\n\n /** @return start key for region */\n public byte [] getStartKey() {\n return this.regionInfo.getStartKey();\n }\n\n /** @return end key for region */\n public byte [] getEndKey() {\n return this.regionInfo.getEndKey();\n }\n\n /** @return region id */\n public long getRegionId() {\n return this.regionInfo.getRegionId();\n }\n\n /** @return region name */\n public byte [] getRegionName() {\n return this.regionInfo.getRegionName();\n }\n\n /** @return region name as string for logging */\n public String getRegionNameAsString() {\n return this.regionInfo.getRegionNameAsString();\n }\n\n /** @return HTableDescriptor for this region */\n public HTableDescriptor getTableDesc() {\n return this.htableDescriptor;\n }\n\n /** @return HLog in use for this region */\n public HLog getLog() {\n return this.log;\n }\n\n /** @return Configuration object */\n public Configuration getConf() {\n return this.conf;\n }\n\n /** @return region directory Path */\n public Path getRegionDir() {\n return this.regiondir;\n }\n\n /**\n * Computes the Path of the HRegion\n *\n * @param tabledir qualified path for table\n * @param name ENCODED region name\n * @return Path of HRegion directory\n */\n public static Path getRegionDir(final Path tabledir, final String name) {\n return new Path(tabledir, name);\n }\n\n /** @return FileSystem being used by this region */\n public FileSystem getFilesystem() {\n return this.fs;\n }\n\n /** @return the last time the region was flushed */\n public long getLastFlushTime() {\n return this.lastFlushTime;\n }\n\n /** @return info about the last flushes <time, size> */\n public List<Pair<Long,Long>> getRecentFlushInfo() {\n this.lock.readLock().lock();\n List<Pair<Long,Long>> ret = this.recentFlushes;\n this.recentFlushes = new ArrayList<Pair<Long,Long>>();\n this.lock.readLock().unlock();\n return ret;\n }\n\n //////////////////////////////////////////////////////////////////////////////\n // HRegion maintenance.\n //\n // These methods are meant to be called periodically by the HRegionServer for\n // upkeep.\n //////////////////////////////////////////////////////////////////////////////\n\n /** @return returns size of largest HStore. */\n public long getLargestHStoreSize() {\n long size = 0;\n for (Store h: stores.values()) {\n long storeSize = h.getSize();\n if (storeSize > size) {\n size = storeSize;\n }\n }\n return size;\n }\n\n /*\n * Do preparation for pending compaction.\n * @throws IOException\n */\n void doRegionCompactionPrep() throws IOException {\n }\n\n /*\n * Removes the temporary directory for this Store.\n */\n private void cleanupTmpDir() throws IOException {\n FSUtils.deleteDirectory(this.fs, getTmpDir());\n }\n\n /**\n * Get the temporary directory for this region. This directory\n * will have its contents removed when the region is reopened.\n */\n Path getTmpDir() {\n return new Path(getRegionDir(), REGION_TEMP_SUBDIR);\n }\n\n void triggerMajorCompaction() {\n for (Store h: stores.values()) {\n h.triggerMajorCompaction();\n }\n }\n\n /**\n * This is a helper function that compact all the stores synchronously\n * It is used by utilities and testing\n *\n * @param majorCompaction True to force a major compaction regardless of thresholds\n * @throws IOException e\n */\n public void compactStores(final boolean majorCompaction)\n throws IOException {\n if (majorCompaction) {\n this.triggerMajorCompaction();\n }\n compactStores();\n }\n\n /**\n * This is a helper function that compact all the stores synchronously\n * It is used by utilities and testing\n *\n * @throws IOException e\n */\n public void compactStores() throws IOException {\n for(Store s : getStores().values()) {\n CompactionRequest cr = s.requestCompaction();\n if(cr != null) {\n try {\n compact(cr);\n } finally {\n s.finishRequest(cr);\n }\n }\n }\n }\n\n /*\n * Called by compaction thread and after region is opened to compact the\n * HStores if necessary.\n *\n * <p>This operation could block for a long time, so don't call it from a\n * time-sensitive thread.\n *\n * Note that no locking is necessary at this level because compaction only\n * conflicts with a region split, and that cannot happen because the region\n * server does them sequentially and not in parallel.\n *\n * @param cr Compaction details, obtained by requestCompaction()\n * @return whether the compaction completed\n * @throws IOException e\n */\n public boolean compact(CompactionRequest cr)\n throws IOException {\n if (cr == null) {\n return false;\n }\n if (this.closing.get() || this.closed.get()) {\n LOG.debug(\"Skipping compaction on \" + this + \" because closing/closed\");\n return false;\n }\n Preconditions.checkArgument(cr.getHRegion().equals(this));\n lock.readLock().lock();\n MonitoredTask status = TaskMonitor.get().createStatus(\n \"Compacting \" + cr.getStore() + \" in \" + this);\n try {\n if (this.closed.get()) {\n LOG.debug(\"Skipping compaction on \" + this + \" because closed\");\n return false;\n }\n boolean decr = true;\n try {\n synchronized (writestate) {\n if (writestate.writesEnabled) {\n ++writestate.compacting;\n } else {\n String msg = \"NOT compacting region \" + this + \". Writes disabled.\";\n LOG.info(msg);\n status.abort(msg);\n decr = false;\n return false;\n }\n }\n LOG.info(\"Starting compaction on \" + cr.getStore() + \" in region \"\n + this + (cr.getCompactSelection().isOffPeakCompaction()?\" as an off-peak compaction\":\"\"));\n doRegionCompactionPrep();\n try {\n status.setStatus(\"Compacting store \" + cr.getStore());\n cr.getStore().compact(cr);\n } catch (InterruptedIOException iioe) {\n String msg = \"compaction interrupted by user\";\n LOG.info(msg, iioe);\n status.abort(msg);\n return false;\n }\n } finally {\n if (decr) {\n synchronized (writestate) {\n --writestate.compacting;\n if (writestate.compacting <= 0) {\n writestate.notifyAll();\n }\n }\n }\n }\n status.markComplete(\"Compaction complete\");\n return true;\n } finally {\n status.cleanup();\n lock.readLock().unlock();\n }\n }\n\n /**\n * Flush the cache.\n *\n * When this method is called the cache will be flushed unless:\n * <ol>\n * <li>the cache is empty</li>\n * <li>the region is closed.</li>\n * <li>a flush is already in progress</li>\n * <li>writes are disabled</li>\n * </ol>\n *\n * <p>This method may block for some time, so it should not be called from a\n * time-sensitive thread.\n *\n * @return true if cache was flushed\n *\n * @throws IOException general io exceptions\n * @throws DroppedSnapshotException Thrown when replay of hlog is required\n * because a Snapshot was not properly persisted.\n */\n public boolean flushcache() throws IOException {\n // fail-fast instead of waiting on the lock\n if (this.closing.get()) {\n LOG.debug(\"Skipping flush on \" + this + \" because closing\");\n return false;\n }\n MonitoredTask status = TaskMonitor.get().createStatus(\"Flushing \" + this);\n status.setStatus(\"Acquiring readlock on region\");\n lock.readLock().lock();\n try {\n if (this.closed.get()) {\n LOG.debug(\"Skipping flush on \" + this + \" because closed\");\n status.abort(\"Skipped: closed\");\n return false;\n }\n if (coprocessorHost != null) {\n status.setStatus(\"Running coprocessor pre-flush hooks\");\n coprocessorHost.preFlush();\n }\n if (numPutsWithoutWAL.get() > 0) {\n numPutsWithoutWAL.set(0);\n dataInMemoryWithoutWAL.set(0);\n }\n synchronized (writestate) {\n if (!writestate.flushing && writestate.writesEnabled) {\n this.writestate.flushing = true;\n } else {\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"NOT flushing memstore for region \" + this\n + \", flushing=\" + writestate.flushing + \", writesEnabled=\"\n + writestate.writesEnabled);\n }\n status.abort(\"Not flushing since \"\n + (writestate.flushing ? \"already flushing\"\n : \"writes not enabled\"));\n return false;\n }\n }\n try {\n boolean result = internalFlushcache(status);\n\n if (coprocessorHost != null) {\n status.setStatus(\"Running post-flush coprocessor hooks\");\n coprocessorHost.postFlush();\n }\n\n status.markComplete(\"Flush successful\");\n return result;\n } finally {\n synchronized (writestate) {\n writestate.flushing = false;\n this.writestate.flushRequested = false;\n writestate.notifyAll();\n }\n }\n } finally {\n lock.readLock().unlock();\n status.cleanup();\n }\n }\n\n /**\n * Flush the memstore.\n *\n * Flushing the memstore is a little tricky. We have a lot of updates in the\n * memstore, all of which have also been written to the log. We need to\n * write those updates in the memstore out to disk, while being able to\n * process reads/writes as much as possible during the flush operation. Also,\n * the log has to state clearly the point in time at which the memstore was\n * flushed. (That way, during recovery, we know when we can rely on the\n * on-disk flushed structures and when we have to recover the memstore from\n * the log.)\n *\n * <p>So, we have a three-step process:\n *\n * <ul><li>A. Flush the memstore to the on-disk stores, noting the current\n * sequence ID for the log.<li>\n *\n * <li>B. Write a FLUSHCACHE-COMPLETE message to the log, using the sequence\n * ID that was current at the time of memstore-flush.</li>\n *\n * <li>C. Get rid of the memstore structures that are now redundant, as\n * they've been flushed to the on-disk HStores.</li>\n * </ul>\n * <p>This method is protected, but can be accessed via several public\n * routes.\n *\n * <p> This method may block for some time.\n * @param status\n *\n * @return true if the region needs compacting\n *\n * @throws IOException general io exceptions\n * @throws DroppedSnapshotException Thrown when replay of hlog is required\n * because a Snapshot was not properly persisted.\n */\n protected boolean internalFlushcache(MonitoredTask status)\n throws IOException {\n return internalFlushcache(this.log, -1, status);\n }\n\n /**\n * @param wal Null if we're NOT to go via hlog/wal.\n * @param myseqid The seqid to use if <code>wal</code> is null writing out\n * flush file.\n * @param status\n * @return true if the region needs compacting\n * @throws IOException\n * @see #internalFlushcache(MonitoredTask)\n */\n protected boolean internalFlushcache(\n final HLog wal, final long myseqid, MonitoredTask status)\n throws IOException {\n final long startTime = EnvironmentEdgeManager.currentTimeMillis();\n // Clear flush flag.\n // Record latest flush time\n this.lastFlushTime = startTime;\n // If nothing to flush, return and avoid logging start/stop flush.\n if (this.memstoreSize.get() <= 0) {\n return false;\n }\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"Started memstore flush for \" + this +\n \", current region memstore size \" +\n StringUtils.humanReadableInt(this.memstoreSize.get()) +\n ((wal != null)? \"\": \"; wal is null, using passed sequenceid=\" + myseqid));\n }\n\n // Stop updates while we snapshot the memstore of all stores. We only have\n // to do this for a moment. Its quick. The subsequent sequence id that\n // goes into the HLog after we've flushed all these snapshots also goes\n // into the info file that sits beside the flushed files.\n // We also set the memstore size to zero here before we allow updates\n // again so its value will represent the size of the updates received\n // during the flush\n long sequenceId = -1L;\n long completeSequenceId = -1L;\n MultiVersionConsistencyControl.WriteEntry w = null;\n\n // We have to take a write lock during snapshot, or else a write could\n // end up in both snapshot and memstore (makes it difficult to do atomic\n // rows then)\n status.setStatus(\"Obtaining lock to block concurrent updates\");\n this.updatesLock.writeLock().lock();\n long flushsize = this.memstoreSize.get();\n status.setStatus(\"Preparing to flush by snapshotting stores\");\n List<StoreFlusher> storeFlushers = new ArrayList<StoreFlusher>(stores.size());\n try {\n // Record the mvcc for all transactions in progress.\n w = mvcc.beginMemstoreInsert();\n mvcc.advanceMemstore(w);\n\n sequenceId = (wal == null)? myseqid:\n wal.startCacheFlush(this.regionInfo.getEncodedNameAsBytes());\n completeSequenceId = this.getCompleteCacheFlushSequenceId(sequenceId);\n\n for (Store s : stores.values()) {\n storeFlushers.add(s.getStoreFlusher(completeSequenceId));\n }\n\n // prepare flush (take a snapshot)\n for (StoreFlusher flusher : storeFlushers) {\n flusher.prepare();\n }\n } finally {\n this.updatesLock.writeLock().unlock();\n }\n String s = \"Finished snapshotting \" + this +\n \", commencing wait for mvcc, flushsize=\" + flushsize;\n status.setStatus(s);\n LOG.debug(s);\n\n // wait for all in-progress transactions to commit to HLog before\n // we can start the flush. This prevents\n // uncommitted transactions from being written into HFiles.\n // We have to block before we start the flush, otherwise keys that\n // were removed via a rollbackMemstore could be written to Hfiles.\n mvcc.waitForRead(w);\n\n status.setStatus(\"Flushing stores\");\n LOG.debug(\"Finished snapshotting, commencing flushing stores\");\n\n // Any failure from here on out will be catastrophic requiring server\n // restart so hlog content can be replayed and put back into the memstore.\n // Otherwise, the snapshot content while backed up in the hlog, it will not\n // be part of the current running servers state.\n boolean compactionRequested = false;\n try {\n // A. Flush memstore to all the HStores.\n // Keep running vector of all store files that includes both old and the\n // just-made new flush store file. The new flushed file is still in the\n // tmp directory.\n\n for (StoreFlusher flusher : storeFlushers) {\n flusher.flushCache(status);\n }\n\n // Switch snapshot (in memstore) -> new hfile (thus causing\n // all the store scanners to reset/reseek).\n for (StoreFlusher flusher : storeFlushers) {\n boolean needsCompaction = flusher.commit(status);\n if (needsCompaction) {\n compactionRequested = true;\n }\n }\n storeFlushers.clear();\n\n // Set down the memstore size by amount of flush.\n this.addAndGetGlobalMemstoreSize(-flushsize);\n } catch (Throwable t) {\n // An exception here means that the snapshot was not persisted.\n // The hlog needs to be replayed so its content is restored to memstore.\n // Currently, only a server restart will do this.\n // We used to only catch IOEs but its possible that we'd get other\n // exceptions -- e.g. HBASE-659 was about an NPE -- so now we catch\n // all and sundry.\n if (wal != null) {\n wal.abortCacheFlush(this.regionInfo.getEncodedNameAsBytes());\n }\n DroppedSnapshotException dse = new DroppedSnapshotException(\"region: \" +\n Bytes.toStringBinary(getRegionName()));\n dse.initCause(t);\n status.abort(\"Flush failed: \" + StringUtils.stringifyException(t));\n throw dse;\n }\n\n // If we get to here, the HStores have been written. If we get an\n // error in completeCacheFlush it will release the lock it is holding\n\n // B. Write a FLUSHCACHE-COMPLETE message to the log.\n // This tells future readers that the HStores were emitted correctly,\n // and that all updates to the log for this regionName that have lower\n // log-sequence-ids can be safely ignored.\n if (wal != null) {\n wal.completeCacheFlush(this.regionInfo.getEncodedNameAsBytes(),\n regionInfo.getTableName(), completeSequenceId,\n this.getRegionInfo().isMetaRegion());\n }\n\n // C. Finally notify anyone waiting on memstore to clear:\n // e.g. checkResources().\n synchronized (this) {\n notifyAll(); // FindBugs NN_NAKED_NOTIFY\n }\n\n long time = EnvironmentEdgeManager.currentTimeMillis() - startTime;\n long memstoresize = this.memstoreSize.get();\n String msg = \"Finished memstore flush of ~\" +\n StringUtils.humanReadableInt(flushsize) + \"/\" + flushsize +\n \", currentsize=\" +\n StringUtils.humanReadableInt(memstoresize) + \"/\" + memstoresize +\n \" for region \" + this + \" in \" + time + \"ms, sequenceid=\" + sequenceId +\n \", compaction requested=\" + compactionRequested +\n ((wal == null)? \"; wal=null\": \"\");\n LOG.info(msg);\n status.setStatus(msg);\n this.recentFlushes.add(new Pair<Long,Long>(time/1000, flushsize));\n\n return compactionRequested;\n }\n\n /**\n * Get the sequence number to be associated with this cache flush. Used by\n * TransactionalRegion to not complete pending transactions.\n *\n *\n * @param currentSequenceId\n * @return sequence id to complete the cache flush with\n */\n protected long getCompleteCacheFlushSequenceId(long currentSequenceId) {\n return currentSequenceId;\n }\n\n //////////////////////////////////////////////////////////////////////////////\n // get() methods for client use.\n //////////////////////////////////////////////////////////////////////////////\n /**\n * Return all the data for the row that matches <i>row</i> exactly,\n * or the one that immediately preceeds it, at or immediately before\n * <i>ts</i>.\n *\n * @param row row key\n * @return map of values\n * @throws IOException\n */\n Result getClosestRowBefore(final byte [] row)\n throws IOException{\n return getClosestRowBefore(row, HConstants.CATALOG_FAMILY);\n }\n\n /**\n * Return all the data for the row that matches <i>row</i> exactly,\n * or the one that immediately preceeds it, at or immediately before\n * <i>ts</i>.\n *\n * @param row row key\n * @param family column family to find on\n * @return map of values\n * @throws IOException read exceptions\n */\n public Result getClosestRowBefore(final byte [] row, final byte [] family)\n throws IOException {\n if (coprocessorHost != null) {\n Result result = new Result();\n if (coprocessorHost.preGetClosestRowBefore(row, family, result)) {\n return result;\n }\n }\n // look across all the HStores for this region and determine what the\n // closest key is across all column families, since the data may be sparse\n checkRow(row, \"getClosestRowBefore\");\n startRegionOperation();\n this.readRequestsCount.increment();\n try {\n Store store = getStore(family);\n // get the closest key. (HStore.getRowKeyAtOrBefore can return null)\n KeyValue key = store.getRowKeyAtOrBefore(row);\n Result result = null;\n if (key != null) {\n Get get = new Get(key.getRow());\n get.addFamily(family);\n result = get(get, null);\n }\n if (coprocessorHost != null) {\n coprocessorHost.postGetClosestRowBefore(row, family, result);\n }\n return result;\n } finally {\n closeRegionOperation();\n }\n }\n\n /**\n * Return an iterator that scans over the HRegion, returning the indicated\n * columns and rows specified by the {@link Scan}.\n * <p>\n * This Iterator must be closed by the caller.\n *\n * @param scan configured {@link Scan}\n * @return RegionScanner\n * @throws IOException read exceptions\n */\n public RegionScanner getScanner(Scan scan) throws IOException {\n return getScanner(scan, null);\n }\n\n void prepareScanner(Scan scan) throws IOException {\n if(!scan.hasFamilies()) {\n // Adding all families to scanner\n for(byte[] family: this.htableDescriptor.getFamiliesKeys()){\n scan.addFamily(family);\n }\n }\n }\n\n protected RegionScanner getScanner(Scan scan,\n List<KeyValueScanner> additionalScanners) throws IOException {\n startRegionOperation();\n this.readRequestsCount.increment();\n try {\n // Verify families are all valid\n prepareScanner(scan);\n if(scan.hasFamilies()) {\n for(byte [] family : scan.getFamilyMap().keySet()) {\n checkFamily(family);\n }\n }\n return instantiateRegionScanner(scan, additionalScanners);\n } finally {\n closeRegionOperation();\n }\n }\n\n protected RegionScanner instantiateRegionScanner(Scan scan,\n List<KeyValueScanner> additionalScanners) throws IOException {\n return new RegionScannerImpl(scan, additionalScanners);\n }\n\n /*\n * @param delete The passed delete is modified by this method. WARNING!\n */\n private void prepareDelete(Delete delete) throws IOException {\n // Check to see if this is a deleteRow insert\n if(delete.getFamilyMap().isEmpty()){\n for(byte [] family : this.htableDescriptor.getFamiliesKeys()){\n // Don't eat the timestamp\n delete.deleteFamily(family, delete.getTimeStamp());\n }\n } else {\n for(byte [] family : delete.getFamilyMap().keySet()) {\n if(family == null) {\n throw new NoSuchColumnFamilyException(\"Empty family is invalid\");\n }\n checkFamily(family);\n }\n }\n }\n\n //////////////////////////////////////////////////////////////////////////////\n // set() methods for client use.\n //////////////////////////////////////////////////////////////////////////////\n /**\n * @param delete delete object\n * @param lockid existing lock id, or null for grab a lock\n * @param writeToWAL append to the write ahead lock or not\n * @throws IOException read exceptions\n */\n public void delete(Delete delete, Integer lockid, boolean writeToWAL)\n throws IOException {\n checkReadOnly();\n checkResources();\n Integer lid = null;\n startRegionOperation();\n this.writeRequestsCount.increment();\n try {\n byte [] row = delete.getRow();\n // If we did not pass an existing row lock, obtain a new one\n lid = getLock(lockid, row, true);\n\n try {\n // All edits for the given row (across all column families) must happen atomically.\n prepareDelete(delete);\n internalDelete(delete, delete.getClusterId(), writeToWAL);\n } finally {\n if(lockid == null) releaseRowLock(lid);\n }\n } finally {\n closeRegionOperation();\n }\n }\n\n /**\n * This is used only by unit tests. Not required to be a public API.\n * @param familyMap map of family to edits for the given family.\n * @param writeToWAL\n * @throws IOException\n */\n void delete(Map<byte[], List<KeyValue>> familyMap, UUID clusterId,\n boolean writeToWAL) throws IOException {\n Delete delete = new Delete();\n delete.setFamilyMap(familyMap);\n delete.setClusterId(clusterId);\n delete.setWriteToWAL(writeToWAL);\n internalDelete(delete, clusterId, writeToWAL);\n }\n\n /**\n * Setup correct timestamps in the KVs in Delete object.\n * Caller should have the row and region locks.\n * @param familyMap\n * @param now\n * @throws IOException\n */\n private void prepareDeleteTimestamps(Map<byte[], List<KeyValue>> familyMap, byte[] byteNow)\n throws IOException {\n for (Map.Entry<byte[], List<KeyValue>> e : familyMap.entrySet()) {\n\n byte[] family = e.getKey();\n List<KeyValue> kvs = e.getValue();\n Map<byte[], Integer> kvCount = new TreeMap<byte[], Integer>(Bytes.BYTES_COMPARATOR);\n\n for (KeyValue kv: kvs) {\n // Check if time is LATEST, change to time of most recent addition if so\n // This is expensive.\n if (kv.isLatestTimestamp() && kv.isDeleteType()) {\n byte[] qual = kv.getQualifier();\n if (qual == null) qual = HConstants.EMPTY_BYTE_ARRAY;\n\n Integer count = kvCount.get(qual);\n if (count == null) {\n kvCount.put(qual, 1);\n } else {\n kvCount.put(qual, count + 1);\n }\n count = kvCount.get(qual);\n\n Get get = new Get(kv.getRow());\n get.setMaxVersions(count);\n get.addColumn(family, qual);\n\n List<KeyValue> result = get(get, false);\n\n if (result.size() < count) {\n // Nothing to delete\n kv.updateLatestStamp(byteNow);\n continue;\n }\n if (result.size() > count) {\n throw new RuntimeException(\"Unexpected size: \" + result.size());\n }\n KeyValue getkv = result.get(count - 1);\n Bytes.putBytes(kv.getBuffer(), kv.getTimestampOffset(),\n getkv.getBuffer(), getkv.getTimestampOffset(), Bytes.SIZEOF_LONG);\n } else {\n kv.updateLatestStamp(byteNow);\n }\n }\n }\n }\n\n /**\n * @param delete The Delete command\n * @param clusterId UUID of the originating cluster (for replication).\n * @param writeToWAL\n * @throws IOException\n */\n private void internalDelete(Delete delete, UUID clusterId,\n boolean writeToWAL) throws IOException {\n Map<byte[], List<KeyValue>> familyMap = delete.getFamilyMap();\n WALEdit walEdit = new WALEdit();\n /* Run coprocessor pre hook outside of locks to avoid deadlock */\n if (coprocessorHost != null) {\n if (coprocessorHost.preDelete(delete, walEdit, writeToWAL)) {\n return;\n }\n }\n\n long now = EnvironmentEdgeManager.currentTimeMillis();\n byte [] byteNow = Bytes.toBytes(now);\n boolean flush = false;\n\n updatesLock.readLock().lock();\n try {\n prepareDeleteTimestamps(delete.getFamilyMap(), byteNow);\n\n if (writeToWAL) {\n // write/sync to WAL should happen before we touch memstore.\n //\n // If order is reversed, i.e. we write to memstore first, and\n // for some reason fail to write/sync to commit log, the memstore\n // will contain uncommitted transactions.\n //\n // bunch up all edits across all column families into a\n // single WALEdit.\n addFamilyMapToWALEdit(familyMap, walEdit);\n this.log.append(regionInfo, this.htableDescriptor.getName(),\n walEdit, clusterId, now, this.htableDescriptor);\n }\n\n // Now make changes to the memstore.\n long addedSize = applyFamilyMapToMemstore(familyMap, null);\n flush = isFlushSize(this.addAndGetGlobalMemstoreSize(addedSize));\n\n } finally {\n this.updatesLock.readLock().unlock();\n }\n // do after lock\n if (coprocessorHost != null) {\n coprocessorHost.postDelete(delete, walEdit, writeToWAL);\n }\n final long after = EnvironmentEdgeManager.currentTimeMillis();\n this.opMetrics.updateDeleteMetrics(familyMap.keySet(), after-now);\n\n if (flush) {\n // Request a cache flush. Do it outside update lock.\n requestFlush();\n }\n }\n\n /**\n * @param put\n * @throws IOException\n */\n public void put(Put put) throws IOException {\n this.put(put, null, put.getWriteToWAL());\n }\n\n /**\n * @param put\n * @param writeToWAL\n * @throws IOException\n */\n public void put(Put put, boolean writeToWAL) throws IOException {\n this.put(put, null, writeToWAL);\n }\n\n /**\n * @param put\n * @param lockid\n * @throws IOException\n */\n public void put(Put put, Integer lockid) throws IOException {\n this.put(put, lockid, put.getWriteToWAL());\n }\n\n\n\n /**\n * @param put\n * @param lockid\n * @param writeToWAL\n * @throws IOException\n */\n public void put(Put put, Integer lockid, boolean writeToWAL)\n throws IOException {\n checkReadOnly();\n\n // Do a rough check that we have resources to accept a write. The check is\n // 'rough' in that between the resource check and the call to obtain a\n // read lock, resources may run out. For now, the thought is that this\n // will be extremely rare; we'll deal with it when it happens.\n checkResources();\n startRegionOperation();\n this.writeRequestsCount.increment();\n try {\n // We obtain a per-row lock, so other clients will block while one client\n // performs an update. The read lock is released by the client calling\n // #commit or #abort or if the HRegionServer lease on the lock expires.\n // See HRegionServer#RegionListener for how the expire on HRegionServer\n // invokes a HRegion#abort.\n byte [] row = put.getRow();\n // If we did not pass an existing row lock, obtain a new one\n Integer lid = getLock(lockid, row, true);\n\n try {\n // All edits for the given row (across all column families) must happen atomically.\n internalPut(put, put.getClusterId(), writeToWAL);\n } finally {\n if(lockid == null) releaseRowLock(lid);\n }\n } finally {\n closeRegionOperation();\n }\n }\n\n /**\n * Struct-like class that tracks the progress of a batch operation,\n * accumulating status codes and tracking the index at which processing\n * is proceeding.\n */\n private static class BatchOperationInProgress<T> {\n T[] operations;\n int nextIndexToProcess = 0;\n OperationStatus[] retCodeDetails;\n WALEdit[] walEditsFromCoprocessors;\n\n public BatchOperationInProgress(T[] operations) {\n this.operations = operations;\n this.retCodeDetails = new OperationStatus[operations.length];\n this.walEditsFromCoprocessors = new WALEdit[operations.length];\n Arrays.fill(this.retCodeDetails, OperationStatus.NOT_RUN);\n }\n\n public boolean isDone() {\n return nextIndexToProcess == operations.length;\n }\n }\n\n /**\n * Perform a batch put with no pre-specified locks\n * @see HRegion#batchMutate(Pair[])\n */\n public OperationStatus[] put(Put[] puts) throws IOException {\n @SuppressWarnings(\"unchecked\")\n Pair<Mutation, Integer> putsAndLocks[] = new Pair[puts.length];\n\n for (int i = 0; i < puts.length; i++) {\n putsAndLocks[i] = new Pair<Mutation, Integer>(puts[i], null);\n }\n return batchMutate(putsAndLocks);\n }\n\n /**\n * Perform a batch of puts.\n * @param putsAndLocks\n * the list of puts paired with their requested lock IDs.\n * @return an array of OperationStatus which internally contains the OperationStatusCode and the\n * exceptionMessage if any.\n * @throws IOException\n * @deprecated Instead use {@link HRegion#batchMutate(Pair[])}\n */\n @Deprecated\n public OperationStatus[] put(Pair<Put, Integer>[] putsAndLocks) throws IOException {\n Pair<Mutation, Integer>[] mutationsAndLocks = new Pair[putsAndLocks.length];\n System.arraycopy(putsAndLocks, 0, mutationsAndLocks, 0, putsAndLocks.length);\n return batchMutate(mutationsAndLocks);\n }\n \n /**\n * Perform a batch of mutations.\n * It supports only Put and Delete mutations and will ignore other types passed.\n * @param mutationsAndLocks\n * the list of mutations paired with their requested lock IDs.\n * @return an array of OperationStatus which internally contains the\n * OperationStatusCode and the exceptionMessage if any.\n * @throws IOException\n */\n public OperationStatus[] batchMutate(\n Pair<Mutation, Integer>[] mutationsAndLocks) throws IOException {\n BatchOperationInProgress<Pair<Mutation, Integer>> batchOp =\n new BatchOperationInProgress<Pair<Mutation,Integer>>(mutationsAndLocks);\n\n boolean initialized = false;\n\n while (!batchOp.isDone()) {\n checkReadOnly();\n checkResources();\n\n long newSize;\n startRegionOperation();\n\n try {\n if (!initialized) {\n this.writeRequestsCount.increment();\n doPreMutationHook(batchOp);\n initialized = true;\n }\n long addedSize = doMiniBatchMutation(batchOp);\n newSize = this.addAndGetGlobalMemstoreSize(addedSize);\n } finally {\n closeRegionOperation();\n }\n if (isFlushSize(newSize)) {\n requestFlush();\n }\n }\n return batchOp.retCodeDetails;\n }\n\n private void doPreMutationHook(BatchOperationInProgress<Pair<Mutation, Integer>> batchOp)\n throws IOException {\n /* Run coprocessor pre hook outside of locks to avoid deadlock */\n WALEdit walEdit = new WALEdit();\n if (coprocessorHost != null) {\n for (int i = 0; i < batchOp.operations.length; i++) {\n Pair<Mutation, Integer> nextPair = batchOp.operations[i];\n Mutation m = nextPair.getFirst();\n if (m instanceof Put) {\n if (coprocessorHost.prePut((Put) m, walEdit, m.getWriteToWAL())) {\n // pre hook says skip this Put\n // mark as success and skip in doMiniBatchMutation\n batchOp.retCodeDetails[i] = OperationStatus.SUCCESS;\n }\n } else if (m instanceof Delete) {\n if (coprocessorHost.preDelete((Delete) m, walEdit, m.getWriteToWAL())) {\n // pre hook says skip this Delete\n // mark as success and skip in doMiniBatchMutation\n batchOp.retCodeDetails[i] = OperationStatus.SUCCESS;\n }\n } else {\n // In case of passing Append mutations along with the Puts and Deletes in batchMutate\n // mark the operation return code as failure so that it will not be considered in\n // the doMiniBatchMutation\n batchOp.retCodeDetails[i] = new OperationStatus(OperationStatusCode.FAILURE,\n \"Put/Delete mutations only supported in batchMutate() now\");\n }\n if (!walEdit.isEmpty()) {\n batchOp.walEditsFromCoprocessors[i] = walEdit;\n walEdit = new WALEdit();\n }\n }\n }\n }\n\n // The mutation will be either a Put or Delete.\n @SuppressWarnings(\"unchecked\")\n private long doMiniBatchMutation(\n BatchOperationInProgress<Pair<Mutation, Integer>> batchOp) throws IOException {\n\n // The set of columnFamilies first seen for Put.\n Set<byte[]> putsCfSet = null;\n // variable to note if all Put items are for the same CF -- metrics related\n boolean putsCfSetConsistent = true;\n // The set of columnFamilies first seen for Delete.\n Set<byte[]> deletesCfSet = null;\n // variable to note if all Delete items are for the same CF -- metrics related\n boolean deletesCfSetConsistent = true;\n long startTimeMs = EnvironmentEdgeManager.currentTimeMillis();\n\n WALEdit walEdit = new WALEdit();\n\n MultiVersionConsistencyControl.WriteEntry w = null;\n long txid = 0;\n boolean walSyncSuccessful = false;\n boolean locked = false;\n\n /** Keep track of the locks we hold so we can release them in finally clause */\n List<Integer> acquiredLocks = Lists.newArrayListWithCapacity(batchOp.operations.length);\n // reference family maps directly so coprocessors can mutate them if desired\n Map<byte[],List<KeyValue>>[] familyMaps = new Map[batchOp.operations.length];\n // We try to set up a batch in the range [firstIndex,lastIndexExclusive)\n int firstIndex = batchOp.nextIndexToProcess;\n int lastIndexExclusive = firstIndex;\n boolean success = false;\n int noOfPuts = 0, noOfDeletes = 0;\n try {\n // ------------------------------------\n // STEP 1. Try to acquire as many locks as we can, and ensure\n // we acquire at least one.\n // ----------------------------------\n int numReadyToWrite = 0;\n long now = EnvironmentEdgeManager.currentTimeMillis();\n while (lastIndexExclusive < batchOp.operations.length) {\n Pair<Mutation, Integer> nextPair = batchOp.operations[lastIndexExclusive];\n Mutation mutation = nextPair.getFirst();\n Integer providedLockId = nextPair.getSecond();\n\n Map<byte[], List<KeyValue>> familyMap = mutation.getFamilyMap();\n // store the family map reference to allow for mutations\n familyMaps[lastIndexExclusive] = familyMap;\n\n // skip anything that \"ran\" already\n if (batchOp.retCodeDetails[lastIndexExclusive].getOperationStatusCode()\n != OperationStatusCode.NOT_RUN) {\n lastIndexExclusive++;\n continue;\n }\n\n try {\n if (mutation instanceof Put) {\n checkFamilies(familyMap.keySet());\n checkTimestamps(mutation.getFamilyMap(), now);\n } else {\n prepareDelete((Delete) mutation);\n }\n } catch (NoSuchColumnFamilyException nscf) {\n LOG.warn(\"No such column family in batch mutation\", nscf);\n batchOp.retCodeDetails[lastIndexExclusive] = new OperationStatus(\n OperationStatusCode.BAD_FAMILY, nscf.getMessage());\n lastIndexExclusive++;\n continue;\n } catch (DoNotRetryIOException fsce) {\n // The only thing that throws a generic DoNotRetryIOException in the above code is\n // checkTimestamps so that DoNotRetryIOException means that timestamps were invalid.\n // If more checks are added, be sure to revisit this assumption.\n LOG.warn(\"Batch Mutation did not pass sanity check\", fsce);\n batchOp.retCodeDetails[lastIndexExclusive] = new OperationStatus(\n OperationStatusCode.SANITY_CHECK_FAILURE, fsce.getMessage());\n lastIndexExclusive++;\n continue;\n }\n // If we haven't got any rows in our batch, we should block to\n // get the next one.\n boolean shouldBlock = numReadyToWrite == 0;\n Integer acquiredLockId = null;\n try {\n acquiredLockId = getLock(providedLockId, mutation.getRow(),\n shouldBlock);\n } catch (IOException ioe) {\n LOG.warn(\"Failed getting lock in batch put, row=\"\n + Bytes.toStringBinary(mutation.getRow()), ioe);\n }\n if (acquiredLockId == null) {\n // We failed to grab another lock\n assert !shouldBlock : \"Should never fail to get lock when blocking\";\n break; // stop acquiring more rows for this batch\n }\n if (providedLockId == null) {\n acquiredLocks.add(acquiredLockId);\n }\n lastIndexExclusive++;\n numReadyToWrite++;\n\n if (mutation instanceof Put) {\n // If Column Families stay consistent through out all of the\n // individual puts then metrics can be reported as a mutliput across\n // column families in the first put.\n if (putsCfSet == null) {\n putsCfSet = mutation.getFamilyMap().keySet();\n } else {\n putsCfSetConsistent = putsCfSetConsistent\n && mutation.getFamilyMap().keySet().equals(putsCfSet);\n }\n } else {\n if (deletesCfSet == null) {\n deletesCfSet = mutation.getFamilyMap().keySet();\n } else {\n deletesCfSetConsistent = deletesCfSetConsistent\n && mutation.getFamilyMap().keySet().equals(deletesCfSet);\n }\n }\n }\n\n // we should record the timestamp only after we have acquired the rowLock,\n // otherwise, newer puts/deletes are not guaranteed to have a newer timestamp\n now = EnvironmentEdgeManager.currentTimeMillis();\n byte[] byteNow = Bytes.toBytes(now);\n\n // Nothing to put/delete -- an exception in the above such as NoSuchColumnFamily?\n if (numReadyToWrite <= 0) return 0L;\n\n // We've now grabbed as many mutations off the list as we can\n\n // ------------------------------------\n // STEP 2. Update any LATEST_TIMESTAMP timestamps\n // ----------------------------------\n for (int i = firstIndex; i < lastIndexExclusive; i++) {\n // skip invalid\n if (batchOp.retCodeDetails[i].getOperationStatusCode()\n != OperationStatusCode.NOT_RUN) continue;\n Mutation mutation = batchOp.operations[i].getFirst();\n if (mutation instanceof Put) {\n updateKVTimestamps(familyMaps[i].values(), byteNow);\n noOfPuts++;\n } else {\n prepareDeleteTimestamps(familyMaps[i], byteNow);\n noOfDeletes++;\n }\n }\n\n this.updatesLock.readLock().lock();\n locked = true;\n\n //\n // ------------------------------------\n // Acquire the latest mvcc number\n // ----------------------------------\n w = mvcc.beginMemstoreInsert();\n\n // ------------------------------------\n // STEP 3. Write back to memstore\n // Write to memstore. It is ok to write to memstore\n // first without updating the HLog because we do not roll\n // forward the memstore MVCC. The MVCC will be moved up when\n // the complete operation is done. These changes are not yet\n // visible to scanners till we update the MVCC. The MVCC is\n // moved only when the sync is complete.\n // ----------------------------------\n long addedSize = 0;\n for (int i = firstIndex; i < lastIndexExclusive; i++) {\n if (batchOp.retCodeDetails[i].getOperationStatusCode()\n != OperationStatusCode.NOT_RUN) {\n continue;\n }\n addedSize += applyFamilyMapToMemstore(familyMaps[i], w);\n }\n\n // ------------------------------------\n // STEP 4. Build WAL edit\n // ----------------------------------\n for (int i = firstIndex; i < lastIndexExclusive; i++) {\n // Skip puts that were determined to be invalid during preprocessing\n if (batchOp.retCodeDetails[i].getOperationStatusCode()\n != OperationStatusCode.NOT_RUN) {\n continue;\n }\n batchOp.retCodeDetails[i] = OperationStatus.SUCCESS;\n\n Mutation m = batchOp.operations[i].getFirst();\n if (!m.getWriteToWAL()) {\n if (m instanceof Put) {\n recordPutWithoutWal(m.getFamilyMap());\n }\n continue;\n }\n // Add WAL edits by CP\n WALEdit fromCP = batchOp.walEditsFromCoprocessors[i];\n if (fromCP != null) {\n for (KeyValue kv : fromCP.getKeyValues()) {\n walEdit.add(kv);\n }\n }\n addFamilyMapToWALEdit(familyMaps[i], walEdit);\n }\n\n // -------------------------\n // STEP 5. Append the edit to WAL. Do not sync wal.\n // -------------------------\n Mutation first = batchOp.operations[firstIndex].getFirst();\n txid = this.log.appendNoSync(regionInfo, this.htableDescriptor.getName(),\n walEdit, first.getClusterId(), now, this.htableDescriptor);\n\n // -------------------------------\n // STEP 6. Release row locks, etc.\n // -------------------------------\n if (locked) {\n this.updatesLock.readLock().unlock();\n locked = false;\n }\n if (acquiredLocks != null) {\n for (Integer toRelease : acquiredLocks) {\n releaseRowLock(toRelease);\n }\n acquiredLocks = null;\n }\n // -------------------------\n // STEP 7. Sync wal.\n // -------------------------\n if (walEdit.size() > 0) {\n syncOrDefer(txid);\n }\n walSyncSuccessful = true;\n // ------------------------------------------------------------------\n // STEP 8. Advance mvcc. This will make this put visible to scanners and getters.\n // ------------------------------------------------------------------\n if (w != null) {\n mvcc.completeMemstoreInsert(w);\n w = null;\n }\n\n // ------------------------------------\n // STEP 9. Run coprocessor post hooks. This should be done after the wal is\n // synced so that the coprocessor contract is adhered to.\n // ------------------------------------\n if (coprocessorHost != null) {\n for (int i = firstIndex; i < lastIndexExclusive; i++) {\n // only for successful puts\n if (batchOp.retCodeDetails[i].getOperationStatusCode()\n != OperationStatusCode.SUCCESS) {\n continue;\n }\n Mutation m = batchOp.operations[i].getFirst();\n if (m instanceof Put) {\n coprocessorHost.postPut((Put) m, walEdit, m.getWriteToWAL());\n } else {\n coprocessorHost.postDelete((Delete) m, walEdit, m.getWriteToWAL());\n }\n }\n }\n success = true;\n return addedSize;\n } finally {\n\n // if the wal sync was unsuccessful, remove keys from memstore\n if (!walSyncSuccessful) {\n rollbackMemstore(batchOp, familyMaps, firstIndex, lastIndexExclusive);\n }\n if (w != null) mvcc.completeMemstoreInsert(w);\n\n if (locked) {\n this.updatesLock.readLock().unlock();\n }\n\n if (acquiredLocks != null) {\n for (Integer toRelease : acquiredLocks) {\n releaseRowLock(toRelease);\n }\n }\n\n // do after lock\n final long netTimeMs = EnvironmentEdgeManager.currentTimeMillis()- startTimeMs;\n \n // See if the column families were consistent through the whole thing.\n // if they were then keep them. If they were not then pass a null.\n // null will be treated as unknown.\n // Total time taken might be involving Puts and Deletes.\n // Split the time for puts and deletes based on the total number of Puts and Deletes.\n long timeTakenForPuts = 0;\n if (noOfPuts > 0) {\n // There were some Puts in the batch.\n double noOfMutations = noOfPuts + noOfDeletes;\n timeTakenForPuts = (long) (netTimeMs * (noOfPuts / noOfMutations));\n final Set<byte[]> keptCfs = putsCfSetConsistent ? putsCfSet : null;\n this.opMetrics.updateMultiPutMetrics(keptCfs, timeTakenForPuts);\n }\n if (noOfDeletes > 0) {\n // There were some Deletes in the batch.\n final Set<byte[]> keptCfs = deletesCfSetConsistent ? deletesCfSet : null;\n this.opMetrics.updateMultiDeleteMetrics(keptCfs, netTimeMs - timeTakenForPuts);\n }\n if (!success) {\n for (int i = firstIndex; i < lastIndexExclusive; i++) {\n if (batchOp.retCodeDetails[i].getOperationStatusCode() == OperationStatusCode.NOT_RUN) {\n batchOp.retCodeDetails[i] = OperationStatus.FAILURE;\n }\n }\n }\n batchOp.nextIndexToProcess = lastIndexExclusive;\n }\n }\n\n //TODO, Think that gets/puts and deletes should be refactored a bit so that\n //the getting of the lock happens before, so that you would just pass it into\n //the methods. So in the case of checkAndMutate you could just do lockRow,\n //get, put, unlockRow or something\n /**\n *\n * @param row\n * @param family\n * @param qualifier\n * @param compareOp\n * @param comparator\n * @param lockId\n * @param writeToWAL\n * @throws IOException\n * @return true if the new put was execute, false otherwise\n */\n public boolean checkAndMutate(byte [] row, byte [] family, byte [] qualifier,\n CompareOp compareOp, WritableByteArrayComparable comparator, Writable w,\n Integer lockId, boolean writeToWAL)\n throws IOException{\n checkReadOnly();\n //TODO, add check for value length or maybe even better move this to the\n //client if this becomes a global setting\n checkResources();\n boolean isPut = w instanceof Put;\n if (!isPut && !(w instanceof Delete))\n throw new DoNotRetryIOException(\"Action must be Put or Delete\");\n Row r = (Row)w;\n if (!Bytes.equals(row, r.getRow())) {\n throw new DoNotRetryIOException(\"Action's getRow must match the passed row\");\n }\n\n startRegionOperation();\n this.writeRequestsCount.increment();\n try {\n RowLock lock = isPut ? ((Put)w).getRowLock() : ((Delete)w).getRowLock();\n Get get = new Get(row, lock);\n checkFamily(family);\n get.addColumn(family, qualifier);\n\n // Lock row\n Integer lid = getLock(lockId, get.getRow(), true);\n List<KeyValue> result = new ArrayList<KeyValue>();\n try {\n result = get(get, false);\n\n boolean valueIsNull = comparator.getValue() == null ||\n comparator.getValue().length == 0;\n boolean matches = false;\n if (result.size() == 0 && valueIsNull) {\n matches = true;\n } else if (result.size() > 0 && result.get(0).getValue().length == 0 &&\n valueIsNull) {\n matches = true;\n } else if (result.size() == 1 && !valueIsNull) {\n KeyValue kv = result.get(0);\n int compareResult = comparator.compareTo(kv.getBuffer(),\n kv.getValueOffset(), kv.getValueLength());\n switch (compareOp) {\n case LESS:\n matches = compareResult <= 0;\n break;\n case LESS_OR_EQUAL:\n matches = compareResult < 0;\n break;\n case EQUAL:\n matches = compareResult == 0;\n break;\n case NOT_EQUAL:\n matches = compareResult != 0;\n break;\n case GREATER_OR_EQUAL:\n matches = compareResult > 0;\n break;\n case GREATER:\n matches = compareResult >= 0;\n break;\n default:\n throw new RuntimeException(\"Unknown Compare op \" + compareOp.name());\n }\n }\n //If matches put the new put or delete the new delete\n if (matches) {\n // All edits for the given row (across all column families) must\n // happen atomically.\n //\n // Using default cluster id, as this can only happen in the\n // originating cluster. A slave cluster receives the result as a Put\n // or Delete\n if (isPut) {\n internalPut(((Put) w), HConstants.DEFAULT_CLUSTER_ID, writeToWAL);\n } else {\n Delete d = (Delete)w;\n prepareDelete(d);\n internalDelete(d, HConstants.DEFAULT_CLUSTER_ID, writeToWAL);\n }\n return true;\n }\n return false;\n } finally {\n if(lockId == null) releaseRowLock(lid);\n }\n } finally {\n closeRegionOperation();\n }\n }\n\n\n /**\n * Replaces any KV timestamps set to {@link HConstants#LATEST_TIMESTAMP}\n * with the provided current timestamp.\n */\n private void updateKVTimestamps(\n final Iterable<List<KeyValue>> keyLists, final byte[] now) {\n for (List<KeyValue> keys: keyLists) {\n if (keys == null) continue;\n for (KeyValue key : keys) {\n key.updateLatestStamp(now);\n }\n }\n }\n\n /*\n * Check if resources to support an update.\n *\n * Here we synchronize on HRegion, a broad scoped lock. Its appropriate\n * given we're figuring in here whether this region is able to take on\n * writes. This is only method with a synchronize (at time of writing),\n * this and the synchronize on 'this' inside in internalFlushCache to send\n * the notify.\n */\n private void checkResources() {\n\n // If catalog region, do not impose resource constraints or block updates.\n if (this.getRegionInfo().isMetaRegion()) return;\n\n boolean blocked = false;\n while (this.memstoreSize.get() > this.blockingMemStoreSize) {\n requestFlush();\n if (!blocked) {\n LOG.info(\"Blocking updates for '\" + Thread.currentThread().getName() +\n \"' on region \" + Bytes.toStringBinary(getRegionName()) +\n \": memstore size \" +\n StringUtils.humanReadableInt(this.memstoreSize.get()) +\n \" is >= than blocking \" +\n StringUtils.humanReadableInt(this.blockingMemStoreSize) + \" size\");\n }\n blocked = true;\n synchronized(this) {\n try {\n wait(threadWakeFrequency);\n } catch (InterruptedException e) {\n // continue;\n }\n }\n }\n if (blocked) {\n LOG.info(\"Unblocking updates for region \" + this + \" '\"\n + Thread.currentThread().getName() + \"'\");\n }\n }\n\n /**\n * @throws IOException Throws exception if region is in read-only mode.\n */\n protected void checkReadOnly() throws IOException {\n if (this.writestate.isReadOnly()) {\n throw new IOException(\"region is read only\");\n }\n }\n\n /**\n * Add updates first to the hlog and then add values to memstore.\n * Warning: Assumption is caller has lock on passed in row.\n * @param family\n * @param edits Cell updates by column\n * @praram now\n * @throws IOException\n */\n private void put(byte [] family, List<KeyValue> edits)\n throws IOException {\n Map<byte[], List<KeyValue>> familyMap;\n familyMap = new HashMap<byte[], List<KeyValue>>();\n\n familyMap.put(family, edits);\n Put p = new Put();\n p.setFamilyMap(familyMap);\n p.setClusterId(HConstants.DEFAULT_CLUSTER_ID);\n p.setWriteToWAL(true);\n this.internalPut(p, HConstants.DEFAULT_CLUSTER_ID, true);\n }\n\n /**\n * Add updates first to the hlog (if writeToWal) and then add values to memstore.\n * Warning: Assumption is caller has lock on passed in row.\n * @param put The Put command\n * @param clusterId UUID of the originating cluster (for replication).\n * @param writeToWAL if true, then we should write to the log\n * @throws IOException\n */\n private void internalPut(Put put, UUID clusterId, boolean writeToWAL) throws IOException {\n Map<byte[], List<KeyValue>> familyMap = put.getFamilyMap();\n WALEdit walEdit = new WALEdit();\n /* run pre put hook outside of lock to avoid deadlock */\n if (coprocessorHost != null) {\n if (coprocessorHost.prePut(put, walEdit, writeToWAL)) {\n return;\n }\n }\n\n long now = EnvironmentEdgeManager.currentTimeMillis();\n byte[] byteNow = Bytes.toBytes(now);\n boolean flush = false;\n\n this.updatesLock.readLock().lock();\n try {\n checkFamilies(familyMap.keySet());\n checkTimestamps(familyMap, now);\n updateKVTimestamps(familyMap.values(), byteNow);\n // write/sync to WAL should happen before we touch memstore.\n //\n // If order is reversed, i.e. we write to memstore first, and\n // for some reason fail to write/sync to commit log, the memstore\n // will contain uncommitted transactions.\n if (writeToWAL) {\n addFamilyMapToWALEdit(familyMap, walEdit);\n this.log.append(regionInfo, this.htableDescriptor.getName(),\n walEdit, clusterId, now, this.htableDescriptor);\n } else {\n recordPutWithoutWal(familyMap);\n }\n\n long addedSize = applyFamilyMapToMemstore(familyMap, null);\n flush = isFlushSize(this.addAndGetGlobalMemstoreSize(addedSize));\n } finally {\n this.updatesLock.readLock().unlock();\n }\n\n if (coprocessorHost != null) {\n coprocessorHost.postPut(put, walEdit, writeToWAL);\n }\n\n // do after lock\n final long after = EnvironmentEdgeManager.currentTimeMillis();\n this.opMetrics.updatePutMetrics(familyMap.keySet(), after - now);\n \n if (flush) {\n // Request a cache flush. Do it outside update lock.\n requestFlush();\n }\n }\n\n /**\n * Atomically apply the given map of family->edits to the memstore.\n * This handles the consistency control on its own, but the caller\n * should already have locked updatesLock.readLock(). This also does\n * <b>not</b> check the families for validity.\n *\n * @param familyMap Map of kvs per family\n * @param localizedWriteEntry The WriteEntry of the MVCC for this transaction.\n * If null, then this method internally creates a mvcc transaction.\n * @return the additional memory usage of the memstore caused by the\n * new entries.\n */\n private long applyFamilyMapToMemstore(Map<byte[], List<KeyValue>> familyMap,\n MultiVersionConsistencyControl.WriteEntry localizedWriteEntry) {\n long size = 0;\n boolean freemvcc = false;\n\n try {\n if (localizedWriteEntry == null) {\n localizedWriteEntry = mvcc.beginMemstoreInsert();\n freemvcc = true;\n }\n\n for (Map.Entry<byte[], List<KeyValue>> e : familyMap.entrySet()) {\n byte[] family = e.getKey();\n List<KeyValue> edits = e.getValue();\n\n Store store = getStore(family);\n for (KeyValue kv: edits) {\n kv.setMemstoreTS(localizedWriteEntry.getWriteNumber());\n size += store.add(kv);\n }\n }\n } finally {\n if (freemvcc) {\n mvcc.completeMemstoreInsert(localizedWriteEntry);\n }\n }\n\n return size;\n }\n\n /**\n * Remove all the keys listed in the map from the memstore. This method is\n * called when a Put/Delete has updated memstore but subequently fails to update\n * the wal. This method is then invoked to rollback the memstore.\n */\n private void rollbackMemstore(BatchOperationInProgress<Pair<Mutation, Integer>> batchOp,\n Map<byte[], List<KeyValue>>[] familyMaps,\n int start, int end) {\n int kvsRolledback = 0;\n for (int i = start; i < end; i++) {\n // skip over request that never succeeded in the first place.\n if (batchOp.retCodeDetails[i].getOperationStatusCode()\n != OperationStatusCode.SUCCESS) {\n continue;\n }\n\n // Rollback all the kvs for this row.\n Map<byte[], List<KeyValue>> familyMap = familyMaps[i];\n for (Map.Entry<byte[], List<KeyValue>> e : familyMap.entrySet()) {\n byte[] family = e.getKey();\n List<KeyValue> edits = e.getValue();\n\n // Remove those keys from the memstore that matches our\n // key's (row, cf, cq, timestamp, memstoreTS). The interesting part is\n // that even the memstoreTS has to match for keys that will be rolleded-back.\n Store store = getStore(family);\n for (KeyValue kv: edits) {\n store.rollback(kv);\n kvsRolledback++;\n }\n }\n }\n LOG.debug(\"rollbackMemstore rolled back \" + kvsRolledback +\n \" keyvalues from start:\" + start + \" to end:\" + end);\n }\n\n /**\n * Check the collection of families for validity.\n * @throws NoSuchColumnFamilyException if a family does not exist.\n */\n private void checkFamilies(Collection<byte[]> families)\n throws NoSuchColumnFamilyException {\n for (byte[] family : families) {\n checkFamily(family);\n }\n }\n\n private void checkTimestamps(final Map<byte[], List<KeyValue>> familyMap,\n long now) throws DoNotRetryIOException {\n if (timestampSlop == HConstants.LATEST_TIMESTAMP) {\n return;\n }\n long maxTs = now + timestampSlop;\n for (List<KeyValue> kvs : familyMap.values()) {\n for (KeyValue kv : kvs) {\n // see if the user-side TS is out of range. latest = server-side\n if (!kv.isLatestTimestamp() && kv.getTimestamp() > maxTs) {\n throw new DoNotRetryIOException(\"Timestamp for KV out of range \"\n + kv + \" (too.new=\" + timestampSlop + \")\");\n }\n }\n }\n }\n\n /**\n * Append the given map of family->edits to a WALEdit data structure.\n * This does not write to the HLog itself.\n * @param familyMap map of family->edits\n * @param walEdit the destination entry to append into\n */\n private void addFamilyMapToWALEdit(Map<byte[], List<KeyValue>> familyMap,\n WALEdit walEdit) {\n for (List<KeyValue> edits : familyMap.values()) {\n for (KeyValue kv : edits) {\n walEdit.add(kv);\n }\n }\n }\n\n private void requestFlush() {\n if (this.rsServices == null) {\n return;\n }\n synchronized (writestate) {\n if (this.writestate.isFlushRequested()) {\n return;\n }\n writestate.flushRequested = true;\n }\n // Make request outside of synchronize block; HBASE-818.\n this.rsServices.getFlushRequester().requestFlush(this);\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"Flush requested on \" + this);\n }\n }\n\n /*\n * @param size\n * @return True if size is over the flush threshold\n */\n private boolean isFlushSize(final long size) {\n return size > this.memstoreFlushSize;\n }\n\n /**\n * Read the edits log put under this region by wal log splitting process. Put\n * the recovered edits back up into this region.\n *\n * <p>We can ignore any log message that has a sequence ID that's equal to or\n * lower than minSeqId. (Because we know such log messages are already\n * reflected in the HFiles.)\n *\n * <p>While this is running we are putting pressure on memory yet we are\n * outside of our usual accounting because we are not yet an onlined region\n * (this stuff is being run as part of Region initialization). This means\n * that if we're up against global memory limits, we'll not be flagged to flush\n * because we are not online. We can't be flushed by usual mechanisms anyways;\n * we're not yet online so our relative sequenceids are not yet aligned with\n * HLog sequenceids -- not till we come up online, post processing of split\n * edits.\n *\n * <p>But to help relieve memory pressure, at least manage our own heap size\n * flushing if are in excess of per-region limits. Flushing, though, we have\n * to be careful and avoid using the regionserver/hlog sequenceid. Its running\n * on a different line to whats going on in here in this region context so if we\n * crashed replaying these edits, but in the midst had a flush that used the\n * regionserver log with a sequenceid in excess of whats going on in here\n * in this region and with its split editlogs, then we could miss edits the\n * next time we go to recover. So, we have to flush inline, using seqids that\n * make sense in a this single region context only -- until we online.\n *\n * @param regiondir\n * @param minSeqId Any edit found in split editlogs needs to be in excess of\n * this minSeqId to be applied, else its skipped.\n * @param reporter\n * @return the sequence id of the last edit added to this region out of the\n * recovered edits log or <code>minSeqId</code> if nothing added from editlogs.\n * @throws UnsupportedEncodingException\n * @throws IOException\n */\n protected long replayRecoveredEditsIfAny(final Path regiondir,\n final long minSeqId, final CancelableProgressable reporter,\n final MonitoredTask status)\n throws UnsupportedEncodingException, IOException {\n long seqid = minSeqId;\n NavigableSet<Path> files = HLog.getSplitEditFilesSorted(this.fs, regiondir);\n if (files == null || files.isEmpty()) return seqid;\n for (Path edits: files) {\n if (edits == null || !this.fs.exists(edits)) {\n LOG.warn(\"Null or non-existent edits file: \" + edits);\n continue;\n }\n if (isZeroLengthThenDelete(this.fs, edits)) continue;\n\n long maxSeqId = Long.MAX_VALUE;\n String fileName = edits.getName();\n maxSeqId = Math.abs(Long.parseLong(fileName));\n if (maxSeqId <= minSeqId) {\n String msg = \"Maximum sequenceid for this log is \" + maxSeqId\n + \" and minimum sequenceid for the region is \" + minSeqId\n + \", skipped the whole file, path=\" + edits;\n LOG.debug(msg);\n continue;\n }\n\n try {\n seqid = replayRecoveredEdits(edits, seqid, reporter);\n } catch (IOException e) {\n boolean skipErrors = conf.getBoolean(\"hbase.skip.errors\", false);\n if (skipErrors) {\n Path p = HLog.moveAsideBadEditsFile(fs, edits);\n LOG.error(\"hbase.skip.errors=true so continuing. Renamed \" + edits +\n \" as \" + p, e);\n } else {\n throw e;\n }\n }\n // The edits size added into rsAccounting during this replaying will not\n // be required any more. So just clear it.\n if (this.rsAccounting != null) {\n this.rsAccounting.clearRegionReplayEditsSize(this.regionInfo.getRegionName());\n }\n }\n if (seqid > minSeqId) {\n // Then we added some edits to memory. Flush and cleanup split edit files.\n internalFlushcache(null, seqid, status);\n }\n // Now delete the content of recovered edits. We're done w/ them.\n for (Path file: files) {\n if (!this.fs.delete(file, false)) {\n LOG.error(\"Failed delete of \" + file);\n } else {\n LOG.debug(\"Deleted recovered.edits file=\" + file);\n }\n }\n return seqid;\n }\n\n /*\n * @param edits File of recovered edits.\n * @param minSeqId Minimum sequenceid found in a store file. Edits in log\n * must be larger than this to be replayed.\n * @param reporter\n * @return the sequence id of the last edit added to this region out of the\n * recovered edits log or <code>minSeqId</code> if nothing added from editlogs.\n * @throws IOException\n */\n private long replayRecoveredEdits(final Path edits,\n final long minSeqId, final CancelableProgressable reporter)\n throws IOException {\n String msg = \"Replaying edits from \" + edits + \"; minSequenceid=\" +\n minSeqId + \"; path=\" + edits;\n LOG.info(msg);\n MonitoredTask status = TaskMonitor.get().createStatus(msg);\n\n status.setStatus(\"Opening logs\");\n HLog.Reader reader = null;\n try {\n reader = HLog.getReader(this.fs, edits, conf);\n long currentEditSeqId = minSeqId;\n long firstSeqIdInLog = -1;\n long skippedEdits = 0;\n long editsCount = 0;\n long intervalEdits = 0;\n HLog.Entry entry;\n Store store = null;\n boolean reported_once = false;\n\n try {\n // How many edits seen before we check elapsed time\n int interval = this.conf.getInt(\"hbase.hstore.report.interval.edits\",\n 2000);\n // How often to send a progress report (default 1/2 master timeout)\n int period = this.conf.getInt(\"hbase.hstore.report.period\",\n this.conf.getInt(\"hbase.master.assignment.timeoutmonitor.timeout\",\n 180000) / 2);\n long lastReport = EnvironmentEdgeManager.currentTimeMillis();\n\n while ((entry = reader.next()) != null) {\n HLogKey key = entry.getKey();\n WALEdit val = entry.getEdit();\n\n if (reporter != null) {\n intervalEdits += val.size();\n if (intervalEdits >= interval) {\n // Number of edits interval reached\n intervalEdits = 0;\n long cur = EnvironmentEdgeManager.currentTimeMillis();\n if (lastReport + period <= cur) {\n status.setStatus(\"Replaying edits...\" +\n \" skipped=\" + skippedEdits +\n \" edits=\" + editsCount);\n // Timeout reached\n if(!reporter.progress()) {\n msg = \"Progressable reporter failed, stopping replay\";\n LOG.warn(msg);\n status.abort(msg);\n throw new IOException(msg);\n }\n reported_once = true;\n lastReport = cur;\n }\n }\n }\n\n // Start coprocessor replay here. The coprocessor is for each WALEdit\n // instead of a KeyValue.\n if (coprocessorHost != null) {\n status.setStatus(\"Running pre-WAL-restore hook in coprocessors\");\n if (coprocessorHost.preWALRestore(this.getRegionInfo(), key, val)) {\n // if bypass this log entry, ignore it ...\n continue;\n }\n }\n\n if (firstSeqIdInLog == -1) {\n firstSeqIdInLog = key.getLogSeqNum();\n }\n // Now, figure if we should skip this edit.\n if (key.getLogSeqNum() <= currentEditSeqId) {\n skippedEdits++;\n continue;\n }\n currentEditSeqId = key.getLogSeqNum();\n boolean flush = false;\n for (KeyValue kv: val.getKeyValues()) {\n // Check this edit is for me. Also, guard against writing the special\n // METACOLUMN info such as HBASE::CACHEFLUSH entries\n if (kv.matchingFamily(HLog.METAFAMILY) ||\n !Bytes.equals(key.getEncodedRegionName(), this.regionInfo.getEncodedNameAsBytes())) {\n skippedEdits++;\n continue;\n }\n // Figure which store the edit is meant for.\n if (store == null || !kv.matchingFamily(store.getFamily().getName())) {\n store = this.stores.get(kv.getFamily());\n }\n if (store == null) {\n // This should never happen. Perhaps schema was changed between\n // crash and redeploy?\n LOG.warn(\"No family for \" + kv);\n skippedEdits++;\n continue;\n }\n // Once we are over the limit, restoreEdit will keep returning true to\n // flush -- but don't flush until we've played all the kvs that make up\n // the WALEdit.\n flush = restoreEdit(store, kv);\n editsCount++;\n }\n if (flush) internalFlushcache(null, currentEditSeqId, status);\n\n if (coprocessorHost != null) {\n coprocessorHost.postWALRestore(this.getRegionInfo(), key, val);\n }\n }\n } catch (EOFException eof) {\n Path p = HLog.moveAsideBadEditsFile(fs, edits);\n msg = \"Encountered EOF. Most likely due to Master failure during \" +\n \"log spliting, so we have this data in another edit. \" +\n \"Continuing, but renaming \" + edits + \" as \" + p;\n LOG.warn(msg, eof);\n status.abort(msg);\n } catch (IOException ioe) {\n // If the IOE resulted from bad file format,\n // then this problem is idempotent and retrying won't help\n if (ioe.getCause() instanceof ParseException) {\n Path p = HLog.moveAsideBadEditsFile(fs, edits);\n msg = \"File corruption encountered! \" +\n \"Continuing, but renaming \" + edits + \" as \" + p;\n LOG.warn(msg, ioe);\n status.setStatus(msg);\n } else {\n status.abort(StringUtils.stringifyException(ioe));\n // other IO errors may be transient (bad network connection,\n // checksum exception on one datanode, etc). throw & retry\n throw ioe;\n }\n }\n if (reporter != null && !reported_once) {\n reporter.progress();\n }\n msg = \"Applied \" + editsCount + \", skipped \" + skippedEdits +\n \", firstSequenceidInLog=\" + firstSeqIdInLog +\n \", maxSequenceidInLog=\" + currentEditSeqId + \", path=\" + edits;\n status.markComplete(msg);\n LOG.debug(msg);\n return currentEditSeqId;\n } finally {\n status.cleanup();\n if (reader != null) {\n reader.close();\n }\n }\n }\n\n /**\n * Used by tests\n * @param s Store to add edit too.\n * @param kv KeyValue to add.\n * @return True if we should flush.\n */\n protected boolean restoreEdit(final Store s, final KeyValue kv) {\n long kvSize = s.add(kv);\n if (this.rsAccounting != null) {\n rsAccounting.addAndGetRegionReplayEditsSize(this.regionInfo.getRegionName(), kvSize);\n }\n return isFlushSize(this.addAndGetGlobalMemstoreSize(kvSize));\n }\n\n /*\n * @param fs\n * @param p File to check.\n * @return True if file was zero-length (and if so, we'll delete it in here).\n * @throws IOException\n */\n private static boolean isZeroLengthThenDelete(final FileSystem fs, final Path p)\n throws IOException {\n FileStatus stat = fs.getFileStatus(p);\n if (stat.getLen() > 0) return false;\n LOG.warn(\"File \" + p + \" is zero-length, deleting.\");\n fs.delete(p, false);\n return true;\n }\n\n protected Store instantiateHStore(Path tableDir, HColumnDescriptor c)\n throws IOException {\n return new Store(tableDir, this, c, this.fs, this.conf);\n }\n\n /**\n * Return HStore instance.\n * Use with caution. Exposed for use of fixup utilities.\n * @param column Name of column family hosted by this region.\n * @return Store that goes with the family on passed <code>column</code>.\n * TODO: Make this lookup faster.\n */\n public Store getStore(final byte [] column) {\n return this.stores.get(column);\n }\n\n public Map<byte[], Store> getStores() {\n return this.stores;\n }\n\n /**\n * Return list of storeFiles for the set of CFs.\n * Uses closeLock to prevent the race condition where a region closes\n * in between the for loop - closing the stores one by one, some stores\n * will return 0 files.\n * @return List of storeFiles.\n */\n public List<String> getStoreFileList(final byte [][] columns)\n throws IllegalArgumentException {\n List<String> storeFileNames = new ArrayList<String>();\n synchronized(closeLock) {\n for(byte[] column : columns) {\n Store store = this.stores.get(column);\n if (store == null) {\n throw new IllegalArgumentException(\"No column family : \" +\n new String(column) + \" available\");\n }\n List<StoreFile> storeFiles = store.getStorefiles();\n for (StoreFile storeFile: storeFiles) {\n storeFileNames.add(storeFile.getPath().toString());\n }\n }\n }\n return storeFileNames;\n }\n //////////////////////////////////////////////////////////////////////////////\n // Support code\n //////////////////////////////////////////////////////////////////////////////\n\n /** Make sure this is a valid row for the HRegion */\n void checkRow(final byte [] row, String op) throws IOException {\n if(!rowIsInRange(regionInfo, row)) {\n throw new WrongRegionException(\"Requested row out of range for \" +\n op + \" on HRegion \" + this + \", startKey='\" +\n Bytes.toStringBinary(regionInfo.getStartKey()) + \"', getEndKey()='\" +\n Bytes.toStringBinary(regionInfo.getEndKey()) + \"', row='\" +\n Bytes.toStringBinary(row) + \"'\");\n }\n }\n\n /**\n * Obtain a lock on the given row. Blocks until success.\n *\n * I know it's strange to have two mappings:\n * <pre>\n * ROWS ==> LOCKS\n * </pre>\n * as well as\n * <pre>\n * LOCKS ==> ROWS\n * </pre>\n *\n * But it acts as a guard on the client; a miswritten client just can't\n * submit the name of a row and start writing to it; it must know the correct\n * lockid, which matches the lock list in memory.\n *\n * <p>It would be more memory-efficient to assume a correctly-written client,\n * which maybe we'll do in the future.\n *\n * @param row Name of row to lock.\n * @throws IOException\n * @return The id of the held lock.\n */\n public Integer obtainRowLock(final byte [] row) throws IOException {\n startRegionOperation();\n this.writeRequestsCount.increment();\n try {\n return internalObtainRowLock(row, true);\n } finally {\n closeRegionOperation();\n }\n }\n\n /**\n * Obtains or tries to obtain the given row lock.\n * @param waitForLock if true, will block until the lock is available.\n * Otherwise, just tries to obtain the lock and returns\n * null if unavailable.\n */\n private Integer internalObtainRowLock(final byte[] row, boolean waitForLock)\n throws IOException {\n checkRow(row, \"row lock\");\n startRegionOperation();\n try {\n HashedBytes rowKey = new HashedBytes(row);\n CountDownLatch rowLatch = new CountDownLatch(1);\n\n // loop until we acquire the row lock (unless !waitForLock)\n while (true) {\n CountDownLatch existingLatch = lockedRows.putIfAbsent(rowKey, rowLatch);\n if (existingLatch == null) {\n break;\n } else {\n // row already locked\n if (!waitForLock) {\n return null;\n }\n try {\n if (!existingLatch.await(this.rowLockWaitDuration,\n TimeUnit.MILLISECONDS)) {\n throw new IOException(\"Timed out on getting lock for row=\"\n + Bytes.toStringBinary(row));\n }\n } catch (InterruptedException ie) {\n // Empty\n }\n }\n }\n\n // loop until we generate an unused lock id\n while (true) {\n Integer lockId = lockIdGenerator.incrementAndGet();\n HashedBytes existingRowKey = lockIds.putIfAbsent(lockId, rowKey);\n if (existingRowKey == null) {\n return lockId;\n } else {\n // lockId already in use, jump generator to a new spot\n lockIdGenerator.set(rand.nextInt());\n }\n }\n } finally {\n closeRegionOperation();\n }\n }\n\n /**\n * Used by unit tests.\n * @param lockid\n * @return Row that goes with <code>lockid</code>\n */\n byte[] getRowFromLock(final Integer lockid) {\n HashedBytes rowKey = lockIds.get(lockid);\n return rowKey == null ? null : rowKey.getBytes();\n }\n\n /**\n * Release the row lock!\n * @param lockId The lock ID to release.\n */\n public void releaseRowLock(final Integer lockId) {\n HashedBytes rowKey = lockIds.remove(lockId);\n if (rowKey == null) {\n LOG.warn(\"Release unknown lockId: \" + lockId);\n return;\n }\n CountDownLatch rowLatch = lockedRows.remove(rowKey);\n if (rowLatch == null) {\n LOG.error(\"Releases row not locked, lockId: \" + lockId + \" row: \"\n + rowKey);\n return;\n }\n rowLatch.countDown();\n }\n\n /**\n * See if row is currently locked.\n * @param lockid\n * @return boolean\n */\n boolean isRowLocked(final Integer lockId) {\n return lockIds.containsKey(lockId);\n }\n\n /**\n * Returns existing row lock if found, otherwise\n * obtains a new row lock and returns it.\n * @param lockid requested by the user, or null if the user didn't already hold lock\n * @param row the row to lock\n * @param waitForLock if true, will block until the lock is available, otherwise will\n * simply return null if it could not acquire the lock.\n * @return lockid or null if waitForLock is false and the lock was unavailable.\n */\n public Integer getLock(Integer lockid, byte [] row, boolean waitForLock)\n throws IOException {\n Integer lid = null;\n if (lockid == null) {\n lid = internalObtainRowLock(row, waitForLock);\n } else {\n if (!isRowLocked(lockid)) {\n throw new IOException(\"Invalid row lock\");\n }\n lid = lockid;\n }\n return lid;\n }\n\n /**\n * Determines whether multiple column families are present\n * Precondition: familyPaths is not null\n *\n * @param familyPaths List of Pair<byte[] column family, String hfilePath>\n */\n private static boolean hasMultipleColumnFamilies(\n List<Pair<byte[], String>> familyPaths) {\n boolean multipleFamilies = false;\n byte[] family = null;\n for (Pair<byte[], String> pair : familyPaths) {\n byte[] fam = pair.getFirst();\n if (family == null) {\n family = fam;\n } else if (!Bytes.equals(family, fam)) {\n multipleFamilies = true;\n break;\n }\n }\n return multipleFamilies;\n }\n\n /**\n * Attempts to atomically load a group of hfiles. This is critical for loading\n * rows with multiple column families atomically.\n *\n * @param familyPaths List of Pair<byte[] column family, String hfilePath>\n * @return true if successful, false if failed recoverably\n * @throws IOException if failed unrecoverably.\n */\n public boolean bulkLoadHFiles(List<Pair<byte[], String>> familyPaths)\n throws IOException {\n Preconditions.checkNotNull(familyPaths);\n // we need writeLock for multi-family bulk load\n startBulkRegionOperation(hasMultipleColumnFamilies(familyPaths));\n try {\n this.writeRequestsCount.increment();\n\n // There possibly was a split that happend between when the split keys\n // were gathered and before the HReiogn's write lock was taken. We need\n // to validate the HFile region before attempting to bulk load all of them\n List<IOException> ioes = new ArrayList<IOException>();\n List<Pair<byte[], String>> failures = new ArrayList<Pair<byte[], String>>();\n for (Pair<byte[], String> p : familyPaths) {\n byte[] familyName = p.getFirst();\n String path = p.getSecond();\n\n Store store = getStore(familyName);\n if (store == null) {\n IOException ioe = new DoNotRetryIOException(\n \"No such column family \" + Bytes.toStringBinary(familyName));\n ioes.add(ioe);\n failures.add(p);\n } else {\n try {\n store.assertBulkLoadHFileOk(new Path(path));\n } catch (WrongRegionException wre) {\n // recoverable (file doesn't fit in region)\n failures.add(p);\n } catch (IOException ioe) {\n // unrecoverable (hdfs problem)\n ioes.add(ioe);\n }\n }\n }\n\n // validation failed, bail out before doing anything permanent.\n if (failures.size() != 0) {\n StringBuilder list = new StringBuilder();\n for (Pair<byte[], String> p : failures) {\n list.append(\"\\n\").append(Bytes.toString(p.getFirst())).append(\" : \")\n .append(p.getSecond());\n }\n // problem when validating\n LOG.warn(\"There was a recoverable bulk load failure likely due to a\" +\n \" split. These (family, HFile) pairs were not loaded: \" + list);\n return false;\n }\n\n // validation failed because of some sort of IO problem.\n if (ioes.size() != 0) {\n LOG.error(\"There were IO errors when checking if bulk load is ok. \" +\n \"throwing exception!\");\n throw MultipleIOException.createIOException(ioes);\n }\n\n for (Pair<byte[], String> p : familyPaths) {\n byte[] familyName = p.getFirst();\n String path = p.getSecond();\n Store store = getStore(familyName);\n try {\n store.bulkLoadHFile(path);\n } catch (IOException ioe) {\n // a failure here causes an atomicity violation that we currently\n // cannot recover from since it is likely a failed hdfs operation.\n\n // TODO Need a better story for reverting partial failures due to HDFS.\n LOG.error(\"There was a partial failure due to IO when attempting to\" +\n \" load \" + Bytes.toString(p.getFirst()) + \" : \"+ p.getSecond());\n throw ioe;\n }\n }\n return true;\n } finally {\n closeBulkRegionOperation();\n }\n }\n\n @Override\n public boolean equals(Object o) {\n if (!(o instanceof HRegion)) {\n return false;\n }\n return Bytes.equals(this.getRegionName(), ((HRegion) o).getRegionName());\n }\n\n @Override\n public int hashCode() {\n return Bytes.hashCode(this.getRegionName());\n }\n\n @Override\n public String toString() {\n return this.regionInfo.getRegionNameAsString();\n }\n\n /** @return Path of region base directory */\n public Path getTableDir() {\n return this.tableDir;\n }\n\n /**\n * RegionScannerImpl is used to combine scanners from multiple Stores (aka column families).\n */\n class RegionScannerImpl implements RegionScanner {\n // Package local for testability\n KeyValueHeap storeHeap = null;\n private final byte [] stopRow;\n private Filter filter;\n private List<KeyValue> results = new ArrayList<KeyValue>();\n private int batch;\n private int isScan;\n private boolean filterClosed = false;\n private long readPt;\n\n public HRegionInfo getRegionInfo() {\n return regionInfo;\n }\n RegionScannerImpl(Scan scan, List<KeyValueScanner> additionalScanners) throws IOException {\n //DebugPrint.println(\"HRegionScanner.<init>\");\n\n this.filter = scan.getFilter();\n this.batch = scan.getBatch();\n if (Bytes.equals(scan.getStopRow(), HConstants.EMPTY_END_ROW)) {\n this.stopRow = null;\n } else {\n this.stopRow = scan.getStopRow();\n }\n // If we are doing a get, we want to be [startRow,endRow] normally\n // it is [startRow,endRow) and if startRow=endRow we get nothing.\n this.isScan = scan.isGetScan() ? -1 : 0;\n\n // synchronize on scannerReadPoints so that nobody calculates\n // getSmallestReadPoint, before scannerReadPoints is updated.\n IsolationLevel isolationLevel = scan.getIsolationLevel();\n synchronized(scannerReadPoints) {\n if (isolationLevel == IsolationLevel.READ_UNCOMMITTED) {\n // This scan can read even uncommitted transactions\n this.readPt = Long.MAX_VALUE;\n MultiVersionConsistencyControl.setThreadReadPoint(this.readPt);\n } else {\n this.readPt = MultiVersionConsistencyControl.resetThreadReadPoint(mvcc);\n }\n scannerReadPoints.put(this, this.readPt);\n }\n\n List<KeyValueScanner> scanners = new ArrayList<KeyValueScanner>();\n if (additionalScanners != null) {\n scanners.addAll(additionalScanners);\n }\n\n for (Map.Entry<byte[], NavigableSet<byte[]>> entry :\n scan.getFamilyMap().entrySet()) {\n Store store = stores.get(entry.getKey());\n KeyValueScanner scanner = store.getScanner(scan, entry.getValue());\n scanners.add(scanner);\n }\n this.storeHeap = new KeyValueHeap(scanners, comparator);\n }\n\n RegionScannerImpl(Scan scan) throws IOException {\n this(scan, null);\n }\n\n /**\n * Reset both the filter and the old filter.\n */\n protected void resetFilters() {\n if (filter != null) {\n filter.reset();\n }\n }\n\n @Override\n public synchronized boolean next(List<KeyValue> outResults, int limit)\n throws IOException {\n return next(outResults, limit, null);\n }\n\n @Override\n public synchronized boolean next(List<KeyValue> outResults, int limit,\n String metric) throws IOException {\n if (this.filterClosed) {\n throw new UnknownScannerException(\"Scanner was closed (timed out?) \" +\n \"after we renewed it. Could be caused by a very slow scanner \" +\n \"or a lengthy garbage collection\");\n }\n startRegionOperation();\n readRequestsCount.increment();\n try {\n\n // This could be a new thread from the last time we called next().\n MultiVersionConsistencyControl.setThreadReadPoint(this.readPt);\n\n results.clear();\n\n boolean returnResult = nextInternal(limit, metric);\n\n outResults.addAll(results);\n resetFilters();\n if (isFilterDone()) {\n return false;\n }\n return returnResult;\n } finally {\n closeRegionOperation();\n }\n }\n\n @Override\n public synchronized boolean next(List<KeyValue> outResults)\n throws IOException {\n // apply the batching limit by default\n return next(outResults, batch, null);\n }\n\n @Override\n public synchronized boolean next(List<KeyValue> outResults, String metric)\n throws IOException {\n // apply the batching limit by default\n return next(outResults, batch, metric);\n }\n\n /*\n * @return True if a filter rules the scanner is over, done.\n */\n public synchronized boolean isFilterDone() {\n return this.filter != null && this.filter.filterAllRemaining();\n }\n\n private boolean nextInternal(int limit, String metric) throws IOException {\n RpcCallContext rpcCall = HBaseServer.getCurrentCall();\n while (true) {\n if (rpcCall != null) {\n // If a user specifies a too-restrictive or too-slow scanner, the\n // client might time out and disconnect while the server side\n // is still processing the request. We should abort aggressively\n // in that case.\n rpcCall.throwExceptionIfCallerDisconnected();\n }\n\n KeyValue kv = this.storeHeap.peek();\n byte [] currentRow = kv == null ? null : kv.getRow();\n if (isStopRow(currentRow)) {\n if (filter != null && filter.hasFilterRow()) {\n filter.filterRow(results);\n }\n if (filter != null && filter.filterRow()) {\n results.clear();\n }\n\n return false;\n } else if (kv != null && !kv.isInternal() && filterRowKey(currentRow)) {\n nextRow(currentRow);\n } else {\n byte [] nextRow;\n do {\n this.storeHeap.next(results, limit - results.size(), metric);\n if (limit > 0 && results.size() == limit) {\n if (this.filter != null && filter.hasFilterRow()) {\n throw new IncompatibleFilterException(\n \"Filter with filterRow(List<KeyValue>) incompatible with scan with limit!\");\n }\n return true; // we are expecting more yes, but also limited to how many we can return.\n }\n } while (Bytes.equals(currentRow, nextRow = peekRow()));\n\n final boolean stopRow = isStopRow(nextRow);\n\n // now that we have an entire row, lets process with a filters:\n\n // first filter with the filterRow(List)\n if (filter != null && filter.hasFilterRow()) {\n filter.filterRow(results);\n }\n\n if (results.isEmpty() || filterRow()) {\n // this seems like a redundant step - we already consumed the row\n // there're no left overs.\n // the reasons for calling this method are:\n // 1. reset the filters.\n // 2. provide a hook to fast forward the row (used by subclasses)\n nextRow(currentRow);\n\n // This row was totally filtered out, if this is NOT the last row,\n // we should continue on.\n\n if (!stopRow) continue;\n }\n return !stopRow;\n }\n }\n }\n\n private boolean filterRow() {\n return filter != null\n && filter.filterRow();\n }\n private boolean filterRowKey(byte[] row) {\n return filter != null\n && filter.filterRowKey(row, 0, row.length);\n }\n\n protected void nextRow(byte [] currentRow) throws IOException {\n while (Bytes.equals(currentRow, peekRow())) {\n this.storeHeap.next(MOCKED_LIST);\n }\n results.clear();\n resetFilters();\n }\n\n private byte[] peekRow() {\n KeyValue kv = this.storeHeap.peek();\n return kv == null ? null : kv.getRow();\n }\n\n private boolean isStopRow(byte [] currentRow) {\n return currentRow == null ||\n (stopRow != null &&\n comparator.compareRows(stopRow, 0, stopRow.length,\n currentRow, 0, currentRow.length) <= isScan);\n }\n\n @Override\n public synchronized void close() {\n if (storeHeap != null) {\n storeHeap.close();\n storeHeap = null;\n }\n // no need to sychronize here.\n scannerReadPoints.remove(this);\n this.filterClosed = true;\n }\n\n KeyValueHeap getStoreHeapForTesting() {\n return storeHeap;\n }\n\n @Override\n public synchronized boolean reseek(byte[] row) throws IOException {\n if (row == null) {\n throw new IllegalArgumentException(\"Row cannot be null.\");\n }\n startRegionOperation();\n try {\n // This could be a new thread from the last time we called next().\n MultiVersionConsistencyControl.setThreadReadPoint(this.readPt);\n KeyValue kv = KeyValue.createFirstOnRow(row);\n // use request seek to make use of the lazy seek option. See HBASE-5520\n return this.storeHeap.requestSeek(kv, true, true);\n } finally {\n closeRegionOperation();\n }\n }\n }\n\n // Utility methods\n /**\n * A utility method to create new instances of HRegion based on the\n * {@link HConstants#REGION_IMPL} configuration property.\n * @param tableDir qualified path of directory where region should be located,\n * usually the table directory.\n * @param log The HLog is the outbound log for any updates to the HRegion\n * (There's a single HLog for all the HRegions on a single HRegionServer.)\n * The log file is a logfile from the previous execution that's\n * custom-computed for this HRegion. The HRegionServer computes and sorts the\n * appropriate log info for this HRegion. If there is a previous log file\n * (implying that the HRegion has been written-to before), then read it from\n * the supplied path.\n * @param fs is the filesystem.\n * @param conf is global configuration settings.\n * @param regionInfo - HRegionInfo that describes the region\n * is new), then read them from the supplied path.\n * @param htd\n * @param rsServices\n * @return the new instance\n */\n public static HRegion newHRegion(Path tableDir, HLog log, FileSystem fs,\n Configuration conf, HRegionInfo regionInfo, final HTableDescriptor htd,\n RegionServerServices rsServices) {\n try {\n @SuppressWarnings(\"unchecked\")\n Class<? extends HRegion> regionClass =\n (Class<? extends HRegion>) conf.getClass(HConstants.REGION_IMPL, HRegion.class);\n\n Constructor<? extends HRegion> c =\n regionClass.getConstructor(Path.class, HLog.class, FileSystem.class,\n Configuration.class, HRegionInfo.class, HTableDescriptor.class,\n RegionServerServices.class);\n\n return c.newInstance(tableDir, log, fs, conf, regionInfo, htd, rsServices);\n } catch (Throwable e) {\n // todo: what should I throw here?\n throw new IllegalStateException(\"Could not instantiate a region instance.\", e);\n }\n }\n\n /**\n * Convenience method creating new HRegions. Used by createTable and by the\n * bootstrap code in the HMaster constructor.\n * Note, this method creates an {@link HLog} for the created region. It\n * needs to be closed explicitly. Use {@link HRegion#getLog()} to get\n * access. <b>When done with a region created using this method, you will\n * need to explicitly close the {@link HLog} it created too; it will not be\n * done for you. Not closing the log will leave at least a daemon thread\n * running.</b> Call {@link #closeHRegion(HRegion)} and it will do\n * necessary cleanup for you.\n * @param info Info for region to create.\n * @param rootDir Root directory for HBase instance\n * @param conf\n * @param hTableDescriptor\n * @return new HRegion\n *\n * @throws IOException\n */\n public static HRegion createHRegion(final HRegionInfo info, final Path rootDir,\n final Configuration conf, final HTableDescriptor hTableDescriptor)\n throws IOException {\n return createHRegion(info, rootDir, conf, hTableDescriptor, null);\n }\n\n /**\n * This will do the necessary cleanup a call to {@link #createHRegion(HRegionInfo, Path, Configuration, HTableDescriptor)}\n * requires. This method will close the region and then close its\n * associated {@link HLog} file. You use it if you call the other createHRegion,\n * the one that takes an {@link HLog} instance but don't be surprised by the\n * call to the {@link HLog#closeAndDelete()} on the {@link HLog} the\n * HRegion was carrying.\n * @param r\n * @throws IOException\n */\n public static void closeHRegion(final HRegion r) throws IOException {\n if (r == null) return;\n r.close();\n if (r.getLog() == null) return;\n r.getLog().closeAndDelete();\n }\n\n /**\n * Convenience method creating new HRegions. Used by createTable.\n * The {@link HLog} for the created region needs to be closed explicitly.\n * Use {@link HRegion#getLog()} to get access.\n *\n * @param info Info for region to create.\n * @param rootDir Root directory for HBase instance\n * @param conf\n * @param hTableDescriptor\n * @param hlog shared HLog\n * @return new HRegion\n *\n * @throws IOException\n */\n public static HRegion createHRegion(final HRegionInfo info, final Path rootDir,\n final Configuration conf,\n final HTableDescriptor hTableDescriptor,\n final HLog hlog)\n throws IOException {\n LOG.info(\"creating HRegion \" + info.getTableNameAsString()\n + \" HTD == \" + hTableDescriptor + \" RootDir = \" + rootDir +\n \" Table name == \" + info.getTableNameAsString());\n\n Path tableDir =\n HTableDescriptor.getTableDir(rootDir, info.getTableName());\n Path regionDir = HRegion.getRegionDir(tableDir, info.getEncodedName());\n FileSystem fs = FileSystem.get(conf);\n fs.mkdirs(regionDir);\n HLog effectiveHLog = hlog;\n if (hlog == null) {\n effectiveHLog = new HLog(fs, new Path(regionDir, HConstants.HREGION_LOGDIR_NAME),\n new Path(regionDir, HConstants.HREGION_OLDLOGDIR_NAME), conf);\n }\n HRegion region = HRegion.newHRegion(tableDir,\n effectiveHLog, fs, conf, info, hTableDescriptor, null);\n region.initialize();\n return region;\n }\n\n /**\n * Open a Region.\n * @param info Info for region to be opened.\n * @param wal HLog for region to use. This method will call\n * HLog#setSequenceNumber(long) passing the result of the call to\n * HRegion#getMinSequenceId() to ensure the log id is properly kept\n * up. HRegionStore does this every time it opens a new region.\n * @param conf\n * @return new HRegion\n *\n * @throws IOException\n */\n public static HRegion openHRegion(final HRegionInfo info,\n final HTableDescriptor htd, final HLog wal,\n final Configuration conf)\n throws IOException {\n return openHRegion(info, htd, wal, conf, null, null);\n }\n\n /**\n * Open a Region.\n * @param info Info for region to be opened\n * @param htd\n * @param wal HLog for region to use. This method will call\n * HLog#setSequenceNumber(long) passing the result of the call to\n * HRegion#getMinSequenceId() to ensure the log id is properly kept\n * up. HRegionStore does this every time it opens a new region.\n * @param conf\n * @param rsServices An interface we can request flushes against.\n * @param reporter An interface we can report progress against.\n * @return new HRegion\n *\n * @throws IOException\n */\n public static HRegion openHRegion(final HRegionInfo info,\n final HTableDescriptor htd, final HLog wal, final Configuration conf,\n final RegionServerServices rsServices,\n final CancelableProgressable reporter)\n throws IOException {\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"Opening region: \" + info);\n }\n if (info == null) {\n throw new NullPointerException(\"Passed region info is null\");\n }\n Path dir = HTableDescriptor.getTableDir(FSUtils.getRootDir(conf),\n info.getTableName());\n FileSystem fs = null;\n if (rsServices != null) {\n fs = rsServices.getFileSystem();\n }\n if (fs == null) {\n fs = FileSystem.get(conf);\n }\n HRegion r = HRegion.newHRegion(dir, wal, fs, conf, info,\n htd, rsServices);\n return r.openHRegion(reporter);\n }\n\n public static HRegion openHRegion(Path tableDir, final HRegionInfo info,\n final HTableDescriptor htd, final HLog wal, final Configuration conf)\n throws IOException {\n return openHRegion(tableDir, info, htd, wal, conf, null, null);\n }\n\n /**\n * Open a Region.\n * @param tableDir Table directory\n * @param info Info for region to be opened.\n * @param wal HLog for region to use. This method will call\n * HLog#setSequenceNumber(long) passing the result of the call to\n * HRegion#getMinSequenceId() to ensure the log id is properly kept\n * up. HRegionStore does this every time it opens a new region.\n * @param conf\n * @param reporter An interface we can report progress against.\n * @return new HRegion\n *\n * @throws IOException\n */\n public static HRegion openHRegion(final Path tableDir, final HRegionInfo info,\n final HTableDescriptor htd, final HLog wal, final Configuration conf,\n final RegionServerServices rsServices,\n final CancelableProgressable reporter)\n throws IOException {\n if (info == null) throw new NullPointerException(\"Passed region info is null\");\n LOG.info(\"HRegion.openHRegion Region name ==\" + info.getRegionNameAsString());\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"Opening region: \" + info);\n }\n Path dir = HTableDescriptor.getTableDir(tableDir,\n info.getTableName());\n HRegion r = HRegion.newHRegion(dir, wal, FileSystem.get(conf), conf, info,\n htd, rsServices);\n return r.openHRegion(reporter);\n }\n\n\n /**\n * Open HRegion.\n * Calls initialize and sets sequenceid.\n * @param reporter\n * @return Returns <code>this</code>\n * @throws IOException\n */\n protected HRegion openHRegion(final CancelableProgressable reporter)\n throws IOException {\n checkCompressionCodecs();\n\n long seqid = initialize(reporter);\n if (this.log != null) {\n this.log.setSequenceNumber(seqid);\n }\n return this;\n }\n\n private void checkCompressionCodecs() throws IOException {\n for (HColumnDescriptor fam: this.htableDescriptor.getColumnFamilies()) {\n CompressionTest.testCompression(fam.getCompression());\n CompressionTest.testCompression(fam.getCompactionCompression());\n }\n }\n\n /**\n * Inserts a new region's meta information into the passed\n * <code>meta</code> region. Used by the HMaster bootstrap code adding\n * new table to ROOT table.\n *\n * @param meta META HRegion to be updated\n * @param r HRegion to add to <code>meta</code>\n *\n * @throws IOException\n */\n public static void addRegionToMETA(HRegion meta, HRegion r)\n throws IOException {\n meta.checkResources();\n // The row key is the region name\n byte[] row = r.getRegionName();\n Integer lid = meta.obtainRowLock(row);\n try {\n final long now = EnvironmentEdgeManager.currentTimeMillis();\n final List<KeyValue> edits = new ArrayList<KeyValue>(2);\n edits.add(new KeyValue(row, HConstants.CATALOG_FAMILY,\n HConstants.REGIONINFO_QUALIFIER, now,\n Writables.getBytes(r.getRegionInfo())));\n // Set into the root table the version of the meta table.\n edits.add(new KeyValue(row, HConstants.CATALOG_FAMILY,\n HConstants.META_VERSION_QUALIFIER, now,\n Bytes.toBytes(HConstants.META_VERSION)));\n meta.put(HConstants.CATALOG_FAMILY, edits);\n } finally {\n meta.releaseRowLock(lid);\n }\n }\n\n /**\n * Deletes all the files for a HRegion\n *\n * @param fs the file system object\n * @param rootdir qualified path of HBase root directory\n * @param info HRegionInfo for region to be deleted\n * @throws IOException\n */\n public static void deleteRegion(FileSystem fs, Path rootdir, HRegionInfo info)\n throws IOException {\n deleteRegion(fs, HRegion.getRegionDir(rootdir, info));\n }\n\n private static void deleteRegion(FileSystem fs, Path regiondir)\n throws IOException {\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"DELETING region \" + regiondir.toString());\n }\n if (!fs.delete(regiondir, true)) {\n LOG.warn(\"Failed delete of \" + regiondir);\n }\n }\n\n /**\n * Computes the Path of the HRegion\n *\n * @param rootdir qualified path of HBase root directory\n * @param info HRegionInfo for the region\n * @return qualified path of region directory\n */\n public static Path getRegionDir(final Path rootdir, final HRegionInfo info) {\n return new Path(\n HTableDescriptor.getTableDir(rootdir, info.getTableName()),\n info.getEncodedName());\n }\n\n /**\n * Determines if the specified row is within the row range specified by the\n * specified HRegionInfo\n *\n * @param info HRegionInfo that specifies the row range\n * @param row row to be checked\n * @return true if the row is within the range specified by the HRegionInfo\n */\n public static boolean rowIsInRange(HRegionInfo info, final byte [] row) {\n return ((info.getStartKey().length == 0) ||\n (Bytes.compareTo(info.getStartKey(), row) <= 0)) &&\n ((info.getEndKey().length == 0) ||\n (Bytes.compareTo(info.getEndKey(), row) > 0));\n }\n\n /**\n * Make the directories for a specific column family\n *\n * @param fs the file system\n * @param tabledir base directory where region will live (usually the table dir)\n * @param hri\n * @param colFamily the column family\n * @throws IOException\n */\n public static void makeColumnFamilyDirs(FileSystem fs, Path tabledir,\n final HRegionInfo hri, byte [] colFamily)\n throws IOException {\n Path dir = Store.getStoreHomedir(tabledir, hri.getEncodedName(), colFamily);\n if (!fs.mkdirs(dir)) {\n LOG.warn(\"Failed to create \" + dir);\n }\n }\n\n /**\n * Merge two HRegions. The regions must be adjacent and must not overlap.\n *\n * @param srcA\n * @param srcB\n * @return new merged HRegion\n * @throws IOException\n */\n public static HRegion mergeAdjacent(final HRegion srcA, final HRegion srcB)\n throws IOException {\n HRegion a = srcA;\n HRegion b = srcB;\n\n // Make sure that srcA comes first; important for key-ordering during\n // write of the merged file.\n if (srcA.getStartKey() == null) {\n if (srcB.getStartKey() == null) {\n throw new IOException(\"Cannot merge two regions with null start key\");\n }\n // A's start key is null but B's isn't. Assume A comes before B\n } else if ((srcB.getStartKey() == null) ||\n (Bytes.compareTo(srcA.getStartKey(), srcB.getStartKey()) > 0)) {\n a = srcB;\n b = srcA;\n }\n\n if (!(Bytes.compareTo(a.getEndKey(), b.getStartKey()) == 0)) {\n throw new IOException(\"Cannot merge non-adjacent regions\");\n }\n return merge(a, b);\n }\n\n /**\n * Merge two regions whether they are adjacent or not.\n *\n * @param a region a\n * @param b region b\n * @return new merged region\n * @throws IOException\n */\n public static HRegion merge(HRegion a, HRegion b)\n throws IOException {\n if (!a.getRegionInfo().getTableNameAsString().equals(\n b.getRegionInfo().getTableNameAsString())) {\n throw new IOException(\"Regions do not belong to the same table\");\n }\n\n FileSystem fs = a.getFilesystem();\n\n // Make sure each region's cache is empty\n\n a.flushcache();\n b.flushcache();\n\n // Compact each region so we only have one store file per family\n\n a.compactStores(true);\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"Files for region: \" + a);\n listPaths(fs, a.getRegionDir());\n }\n b.compactStores(true);\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"Files for region: \" + b);\n listPaths(fs, b.getRegionDir());\n }\n\n Configuration conf = a.getConf();\n HTableDescriptor tabledesc = a.getTableDesc();\n HLog log = a.getLog();\n Path tableDir = a.getTableDir();\n // Presume both are of same region type -- i.e. both user or catalog\n // table regions. This way can use comparator.\n final byte[] startKey =\n (a.comparator.matchingRows(a.getStartKey(), 0, a.getStartKey().length,\n HConstants.EMPTY_BYTE_ARRAY, 0, HConstants.EMPTY_BYTE_ARRAY.length)\n || b.comparator.matchingRows(b.getStartKey(), 0,\n b.getStartKey().length, HConstants.EMPTY_BYTE_ARRAY, 0,\n HConstants.EMPTY_BYTE_ARRAY.length))\n ? HConstants.EMPTY_BYTE_ARRAY\n : (a.comparator.compareRows(a.getStartKey(), 0, a.getStartKey().length,\n b.getStartKey(), 0, b.getStartKey().length) <= 0\n ? a.getStartKey()\n : b.getStartKey());\n final byte[] endKey =\n (a.comparator.matchingRows(a.getEndKey(), 0, a.getEndKey().length,\n HConstants.EMPTY_BYTE_ARRAY, 0, HConstants.EMPTY_BYTE_ARRAY.length)\n || a.comparator.matchingRows(b.getEndKey(), 0, b.getEndKey().length,\n HConstants.EMPTY_BYTE_ARRAY, 0,\n HConstants.EMPTY_BYTE_ARRAY.length))\n ? HConstants.EMPTY_BYTE_ARRAY\n : (a.comparator.compareRows(a.getEndKey(), 0, a.getEndKey().length,\n b.getEndKey(), 0, b.getEndKey().length) <= 0\n ? b.getEndKey()\n : a.getEndKey());\n\n HRegionInfo newRegionInfo =\n new HRegionInfo(tabledesc.getName(), startKey, endKey);\n LOG.info(\"Creating new region \" + newRegionInfo.toString());\n String encodedName = newRegionInfo.getEncodedName();\n Path newRegionDir = HRegion.getRegionDir(a.getTableDir(), encodedName);\n if(fs.exists(newRegionDir)) {\n throw new IOException(\"Cannot merge; target file collision at \" +\n newRegionDir);\n }\n fs.mkdirs(newRegionDir);\n\n LOG.info(\"starting merge of regions: \" + a + \" and \" + b +\n \" into new region \" + newRegionInfo.toString() +\n \" with start key <\" + Bytes.toStringBinary(startKey) + \"> and end key <\" +\n Bytes.toStringBinary(endKey) + \">\");\n\n // Move HStoreFiles under new region directory\n Map<byte [], List<StoreFile>> byFamily =\n new TreeMap<byte [], List<StoreFile>>(Bytes.BYTES_COMPARATOR);\n byFamily = filesByFamily(byFamily, a.close());\n byFamily = filesByFamily(byFamily, b.close());\n for (Map.Entry<byte [], List<StoreFile>> es : byFamily.entrySet()) {\n byte [] colFamily = es.getKey();\n makeColumnFamilyDirs(fs, tableDir, newRegionInfo, colFamily);\n // Because we compacted the source regions we should have no more than two\n // HStoreFiles per family and there will be no reference store\n List<StoreFile> srcFiles = es.getValue();\n if (srcFiles.size() == 2) {\n long seqA = srcFiles.get(0).getMaxSequenceId();\n long seqB = srcFiles.get(1).getMaxSequenceId();\n if (seqA == seqB) {\n // Can't have same sequenceid since on open of a store, this is what\n // distingushes the files (see the map of stores how its keyed by\n // sequenceid).\n throw new IOException(\"Files have same sequenceid: \" + seqA);\n }\n }\n for (StoreFile hsf: srcFiles) {\n StoreFile.rename(fs, hsf.getPath(),\n StoreFile.getUniqueFile(fs, Store.getStoreHomedir(tableDir,\n newRegionInfo.getEncodedName(), colFamily)));\n }\n }\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"Files for new region\");\n listPaths(fs, newRegionDir);\n }\n HRegion dstRegion = HRegion.newHRegion(tableDir, log, fs, conf,\n newRegionInfo, a.getTableDesc(), null);\n dstRegion.readRequestsCount.set(a.readRequestsCount.get() + b.readRequestsCount.get());\n dstRegion.writeRequestsCount.set(a.writeRequestsCount.get() + b.writeRequestsCount.get());\n dstRegion.initialize();\n dstRegion.compactStores();\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"Files for new region\");\n listPaths(fs, dstRegion.getRegionDir());\n }\n deleteRegion(fs, a.getRegionDir());\n deleteRegion(fs, b.getRegionDir());\n\n LOG.info(\"merge completed. New region is \" + dstRegion);\n\n return dstRegion;\n }\n\n /*\n * Fills a map with a vector of store files keyed by column family.\n * @param byFamily Map to fill.\n * @param storeFiles Store files to process.\n * @param family\n * @return Returns <code>byFamily</code>\n */\n private static Map<byte [], List<StoreFile>> filesByFamily(\n Map<byte [], List<StoreFile>> byFamily, List<StoreFile> storeFiles) {\n for (StoreFile src: storeFiles) {\n byte [] family = src.getFamily();\n List<StoreFile> v = byFamily.get(family);\n if (v == null) {\n v = new ArrayList<StoreFile>();\n byFamily.put(family, v);\n }\n v.add(src);\n }\n return byFamily;\n }\n\n /**\n * @return True if needs a mojor compaction.\n * @throws IOException\n */\n boolean isMajorCompaction() throws IOException {\n for (Store store: this.stores.values()) {\n if (store.isMajorCompaction()) {\n return true;\n }\n }\n return false;\n }\n\n /*\n * List the files under the specified directory\n *\n * @param fs\n * @param dir\n * @throws IOException\n */\n private static void listPaths(FileSystem fs, Path dir) throws IOException {\n if (LOG.isDebugEnabled()) {\n FileStatus[] stats = FSUtils.listStatus(fs, dir, null);\n if (stats == null || stats.length == 0) {\n return;\n }\n for (int i = 0; i < stats.length; i++) {\n String path = stats[i].getPath().toString();\n if (stats[i].isDir()) {\n LOG.debug(\"d \" + path);\n listPaths(fs, stats[i].getPath());\n } else {\n LOG.debug(\"f \" + path + \" size=\" + stats[i].getLen());\n }\n }\n }\n }\n\n\n //\n // HBASE-880\n //\n /**\n * @param get get object\n * @param lockid existing lock id, or null for no previous lock\n * @return result\n * @throws IOException read exceptions\n */\n public Result get(final Get get, final Integer lockid) throws IOException {\n checkRow(get.getRow(), \"Get\");\n // Verify families are all valid\n if (get.hasFamilies()) {\n for (byte [] family: get.familySet()) {\n checkFamily(family);\n }\n } else { // Adding all families to scanner\n for (byte[] family: this.htableDescriptor.getFamiliesKeys()) {\n get.addFamily(family);\n }\n }\n List<KeyValue> results = get(get, true);\n return new Result(results);\n }\n\n /*\n * Do a get based on the get parameter.\n * @param withCoprocessor invoke coprocessor or not. We don't want to\n * always invoke cp for this private method.\n */\n private List<KeyValue> get(Get get, boolean withCoprocessor)\n throws IOException {\n long now = EnvironmentEdgeManager.currentTimeMillis();\n\n List<KeyValue> results = new ArrayList<KeyValue>();\n\n // pre-get CP hook\n if (withCoprocessor && (coprocessorHost != null)) {\n if (coprocessorHost.preGet(get, results)) {\n return results;\n }\n }\n\n Scan scan = new Scan(get);\n\n RegionScanner scanner = null;\n try {\n scanner = getScanner(scan);\n scanner.next(results, SchemaMetrics.METRIC_GETSIZE);\n } finally {\n if (scanner != null)\n scanner.close();\n }\n\n // post-get CP hook\n if (withCoprocessor && (coprocessorHost != null)) {\n coprocessorHost.postGet(get, results);\n }\n\n // do after lock\n final long after = EnvironmentEdgeManager.currentTimeMillis();\n this.opMetrics.updateGetMetrics(get.familySet(), after - now);\n \n return results;\n }\n\n public void mutateRow(RowMutations rm) throws IOException {\n mutateRowsWithLocks(rm.getMutations(), Collections.singleton(rm.getRow()));\n }\n\n /**\n * Perform atomic mutations within the region.\n * @param mutations The list of mutations to perform.\n * <code>mutations</code> can contain operations for multiple rows.\n * Caller has to ensure that all rows are contained in this region.\n * @param rowsToLock Rows to lock\n * If multiple rows are locked care should be taken that\n * <code>rowsToLock</code> is sorted in order to avoid deadlocks.\n * @throws IOException\n */\n public void mutateRowsWithLocks(Collection<Mutation> mutations,\n Collection<byte[]> rowsToLock) throws IOException {\n boolean flush = false;\n\n startRegionOperation();\n List<Integer> acquiredLocks = null;\n try {\n // 1. run all pre-hooks before the atomic operation\n // if any pre hook indicates \"bypass\", bypass the entire operation\n\n // one WALEdit is used for all edits.\n WALEdit walEdit = new WALEdit();\n if (coprocessorHost != null) {\n for (Mutation m : mutations) {\n if (m instanceof Put) {\n if (coprocessorHost.prePut((Put) m, walEdit, m.getWriteToWAL())) {\n // by pass everything\n return;\n }\n } else if (m instanceof Delete) {\n Delete d = (Delete) m;\n prepareDelete(d);\n if (coprocessorHost.preDelete(d, walEdit, d.getWriteToWAL())) {\n // by pass everything\n return;\n }\n }\n }\n }\n\n long txid = 0;\n boolean walSyncSuccessful = false;\n boolean locked = false;\n\n // 2. acquire the row lock(s)\n acquiredLocks = new ArrayList<Integer>(rowsToLock.size());\n for (byte[] row : rowsToLock) {\n // attempt to lock all involved rows, fail if one lock times out\n Integer lid = getLock(null, row, true);\n if (lid == null) {\n throw new IOException(\"Failed to acquire lock on \"\n + Bytes.toStringBinary(row));\n }\n acquiredLocks.add(lid);\n }\n\n // 3. acquire the region lock\n this.updatesLock.readLock().lock();\n locked = true;\n\n // 4. Get a mvcc write number\n MultiVersionConsistencyControl.WriteEntry w = mvcc.beginMemstoreInsert();\n\n long now = EnvironmentEdgeManager.currentTimeMillis();\n byte[] byteNow = Bytes.toBytes(now);\n try {\n // 5. Check mutations and apply edits to a single WALEdit\n for (Mutation m : mutations) {\n if (m instanceof Put) {\n Map<byte[], List<KeyValue>> familyMap = m.getFamilyMap();\n checkFamilies(familyMap.keySet());\n checkTimestamps(familyMap, now);\n updateKVTimestamps(familyMap.values(), byteNow);\n } else if (m instanceof Delete) {\n Delete d = (Delete) m;\n prepareDelete(d);\n prepareDeleteTimestamps(d.getFamilyMap(), byteNow);\n } else {\n throw new DoNotRetryIOException(\n \"Action must be Put or Delete. But was: \"\n + m.getClass().getName());\n }\n if (m.getWriteToWAL()) {\n addFamilyMapToWALEdit(m.getFamilyMap(), walEdit);\n }\n }\n\n // 6. append all edits at once (don't sync)\n if (walEdit.size() > 0) {\n txid = this.log.appendNoSync(regionInfo,\n this.htableDescriptor.getName(), walEdit,\n HConstants.DEFAULT_CLUSTER_ID, now, this.htableDescriptor);\n }\n\n // 7. apply to memstore\n long addedSize = 0;\n for (Mutation m : mutations) {\n addedSize += applyFamilyMapToMemstore(m.getFamilyMap(), w);\n }\n flush = isFlushSize(this.addAndGetGlobalMemstoreSize(addedSize));\n\n // 8. release region and row lock(s)\n this.updatesLock.readLock().unlock();\n locked = false;\n if (acquiredLocks != null) {\n for (Integer lid : acquiredLocks) {\n releaseRowLock(lid);\n }\n acquiredLocks = null;\n }\n\n // 9. sync WAL if required\n if (walEdit.size() > 0) {\n syncOrDefer(txid);\n }\n walSyncSuccessful = true;\n\n // 10. advance mvcc\n mvcc.completeMemstoreInsert(w);\n w = null;\n\n // 11. run coprocessor post host hooks\n // after the WAL is sync'ed and all locks are released\n // (similar to doMiniBatchPut)\n if (coprocessorHost != null) {\n for (Mutation m : mutations) {\n if (m instanceof Put) {\n coprocessorHost.postPut((Put) m, walEdit, m.getWriteToWAL());\n } else if (m instanceof Delete) {\n coprocessorHost.postDelete((Delete) m, walEdit, m.getWriteToWAL());\n }\n }\n }\n } finally {\n // 12. clean up if needed\n if (!walSyncSuccessful) {\n int kvsRolledback = 0;\n for (Mutation m : mutations) {\n for (Map.Entry<byte[], List<KeyValue>> e : m.getFamilyMap()\n .entrySet()) {\n List<KeyValue> kvs = e.getValue();\n byte[] family = e.getKey();\n Store store = getStore(family);\n // roll back each kv\n for (KeyValue kv : kvs) {\n store.rollback(kv);\n kvsRolledback++;\n }\n }\n }\n LOG.info(\"mutateRowWithLocks: rolled back \" + kvsRolledback\n + \" KeyValues\");\n }\n\n if (w != null) {\n mvcc.completeMemstoreInsert(w);\n }\n\n if (locked) {\n this.updatesLock.readLock().unlock();\n }\n\n if (acquiredLocks != null) {\n for (Integer lid : acquiredLocks) {\n releaseRowLock(lid);\n }\n }\n }\n } finally {\n if (flush) {\n // 13. Flush cache if needed. Do it outside update lock.\n requestFlush();\n }\n closeRegionOperation();\n }\n }\n\n // TODO: There's a lot of boiler plate code identical\n // to increment... See how to better unify that.\n /**\n *\n * Perform one or more append operations on a row.\n * <p>\n * Appends performed are done under row lock but reads do not take locks out\n * so this can be seen partially complete by gets and scans.\n *\n * @param append\n * @param lockid\n * @param writeToWAL\n * @return new keyvalues after increment\n * @throws IOException\n */\n public Result append(Append append, Integer lockid, boolean writeToWAL)\n throws IOException {\n // TODO: Use MVCC to make this set of appends atomic to reads\n byte[] row = append.getRow();\n checkRow(row, \"append\");\n boolean flush = false;\n WALEdit walEdits = null;\n List<KeyValue> allKVs = new ArrayList<KeyValue>(append.size());\n Map<Store, List<KeyValue>> tempMemstore = new HashMap<Store, List<KeyValue>>();\n long before = EnvironmentEdgeManager.currentTimeMillis();\n long size = 0;\n long txid = 0;\n\n // Lock row\n startRegionOperation();\n this.writeRequestsCount.increment();\n try {\n Integer lid = getLock(lockid, row, true);\n this.updatesLock.readLock().lock();\n try {\n long now = EnvironmentEdgeManager.currentTimeMillis();\n // Process each family\n for (Map.Entry<byte[], List<KeyValue>> family : append.getFamilyMap()\n .entrySet()) {\n\n Store store = stores.get(family.getKey());\n List<KeyValue> kvs = new ArrayList<KeyValue>(family.getValue().size());\n\n // Get previous values for all columns in this family\n Get get = new Get(row);\n for (KeyValue kv : family.getValue()) {\n get.addColumn(family.getKey(), kv.getQualifier());\n }\n List<KeyValue> results = get(get, false);\n\n // Iterate the input columns and update existing values if they were\n // found, otherwise add new column initialized to the append value\n\n // Avoid as much copying as possible. Every byte is copied at most\n // once.\n // Would be nice if KeyValue had scatter/gather logic\n int idx = 0;\n for (KeyValue kv : family.getValue()) {\n KeyValue newKV;\n if (idx < results.size()\n && results.get(idx).matchingQualifier(kv.getBuffer(),\n kv.getQualifierOffset(), kv.getQualifierLength())) {\n KeyValue oldKv = results.get(idx);\n // allocate an empty kv once\n newKV = new KeyValue(row.length, kv.getFamilyLength(),\n kv.getQualifierLength(), now, KeyValue.Type.Put,\n oldKv.getValueLength() + kv.getValueLength());\n // copy in the value\n System.arraycopy(oldKv.getBuffer(), oldKv.getValueOffset(),\n newKV.getBuffer(), newKV.getValueOffset(),\n oldKv.getValueLength());\n System.arraycopy(kv.getBuffer(), kv.getValueOffset(),\n newKV.getBuffer(),\n newKV.getValueOffset() + oldKv.getValueLength(),\n kv.getValueLength());\n idx++;\n } else {\n // allocate an empty kv once\n newKV = new KeyValue(row.length, kv.getFamilyLength(),\n kv.getQualifierLength(), now, KeyValue.Type.Put,\n kv.getValueLength());\n // copy in the value\n System.arraycopy(kv.getBuffer(), kv.getValueOffset(),\n newKV.getBuffer(), newKV.getValueOffset(),\n kv.getValueLength());\n }\n // copy in row, family, and qualifier\n System.arraycopy(kv.getBuffer(), kv.getRowOffset(),\n newKV.getBuffer(), newKV.getRowOffset(), kv.getRowLength());\n System.arraycopy(kv.getBuffer(), kv.getFamilyOffset(),\n newKV.getBuffer(), newKV.getFamilyOffset(),\n kv.getFamilyLength());\n System.arraycopy(kv.getBuffer(), kv.getQualifierOffset(),\n newKV.getBuffer(), newKV.getQualifierOffset(),\n kv.getQualifierLength());\n\n kvs.add(newKV);\n\n // Append update to WAL\n if (writeToWAL) {\n if (walEdits == null) {\n walEdits = new WALEdit();\n }\n walEdits.add(newKV);\n }\n }\n\n // store the kvs to the temporary memstore before writing HLog\n tempMemstore.put(store, kvs);\n }\n\n // Actually write to WAL now\n if (writeToWAL) {\n // Using default cluster id, as this can only happen in the orginating\n // cluster. A slave cluster receives the final value (not the delta)\n // as a Put.\n txid = this.log.appendNoSync(regionInfo,\n this.htableDescriptor.getName(), walEdits,\n HConstants.DEFAULT_CLUSTER_ID, EnvironmentEdgeManager.currentTimeMillis(),\n this.htableDescriptor);\n }\n // Actually write to Memstore now\n for (Map.Entry<Store, List<KeyValue>> entry : tempMemstore.entrySet()) {\n Store store = entry.getKey();\n size += store.upsert(entry.getValue());\n allKVs.addAll(entry.getValue());\n }\n size = this.addAndGetGlobalMemstoreSize(size);\n flush = isFlushSize(size);\n } finally {\n this.updatesLock.readLock().unlock();\n releaseRowLock(lid);\n }\n if (writeToWAL) {\n syncOrDefer(txid); // sync the transaction log outside the rowlock\n }\n } finally {\n closeRegionOperation();\n }\n\n \n long after = EnvironmentEdgeManager.currentTimeMillis();\n this.opMetrics.updateAppendMetrics(append.getFamilyMap().keySet(), after - before);\n \n if (flush) {\n // Request a cache flush. Do it outside update lock.\n requestFlush();\n }\n\n return append.isReturnResults() ? new Result(allKVs) : null;\n }\n\n /**\n *\n * Perform one or more increment operations on a row.\n * <p>\n * Increments performed are done under row lock but reads do not take locks\n * out so this can be seen partially complete by gets and scans.\n * @param increment\n * @param lockid\n * @param writeToWAL\n * @return new keyvalues after increment\n * @throws IOException\n */\n public Result increment(Increment increment, Integer lockid,\n boolean writeToWAL)\n throws IOException {\n // TODO: Use MVCC to make this set of increments atomic to reads\n byte [] row = increment.getRow();\n checkRow(row, \"increment\");\n TimeRange tr = increment.getTimeRange();\n boolean flush = false;\n WALEdit walEdits = null;\n List<KeyValue> allKVs = new ArrayList<KeyValue>(increment.numColumns());\n Map<Store, List<KeyValue>> tempMemstore = new HashMap<Store, List<KeyValue>>();\n long before = EnvironmentEdgeManager.currentTimeMillis();\n long size = 0;\n long txid = 0;\n\n // Lock row\n startRegionOperation();\n this.writeRequestsCount.increment();\n try {\n Integer lid = getLock(lockid, row, true);\n this.updatesLock.readLock().lock();\n try {\n long now = EnvironmentEdgeManager.currentTimeMillis();\n // Process each family\n for (Map.Entry<byte [], NavigableMap<byte [], Long>> family :\n increment.getFamilyMap().entrySet()) {\n\n Store store = stores.get(family.getKey());\n List<KeyValue> kvs = new ArrayList<KeyValue>(family.getValue().size());\n\n // Get previous values for all columns in this family\n Get get = new Get(row);\n for (Map.Entry<byte [], Long> column : family.getValue().entrySet()) {\n get.addColumn(family.getKey(), column.getKey());\n }\n get.setTimeRange(tr.getMin(), tr.getMax());\n List<KeyValue> results = get(get, false);\n\n // Iterate the input columns and update existing values if they were\n // found, otherwise add new column initialized to the increment amount\n int idx = 0;\n for (Map.Entry<byte [], Long> column : family.getValue().entrySet()) {\n long amount = column.getValue();\n if (idx < results.size() &&\n results.get(idx).matchingQualifier(column.getKey())) {\n KeyValue kv = results.get(idx);\n if(kv.getValueLength() == Bytes.SIZEOF_LONG) {\n amount += Bytes.toLong(kv.getBuffer(), kv.getValueOffset(), Bytes.SIZEOF_LONG);\n } else {\n // throw DoNotRetryIOException instead of IllegalArgumentException\n throw new DoNotRetryIOException(\n \"Attempted to increment field that isn't 64 bits wide\");\n }\n idx++;\n }\n\n // Append new incremented KeyValue to list\n KeyValue newKV = new KeyValue(row, family.getKey(), column.getKey(),\n now, Bytes.toBytes(amount));\n kvs.add(newKV);\n\n // Append update to WAL\n if (writeToWAL) {\n if (walEdits == null) {\n walEdits = new WALEdit();\n }\n walEdits.add(newKV);\n }\n }\n\n //store the kvs to the temporary memstore before writing HLog\n tempMemstore.put(store, kvs);\n }\n\n // Actually write to WAL now\n if (writeToWAL) {\n // Using default cluster id, as this can only happen in the orginating\n // cluster. A slave cluster receives the final value (not the delta)\n // as a Put.\n txid = this.log.appendNoSync(regionInfo, this.htableDescriptor.getName(),\n walEdits, HConstants.DEFAULT_CLUSTER_ID, EnvironmentEdgeManager.currentTimeMillis(),\n this.htableDescriptor);\n }\n\n //Actually write to Memstore now\n for (Map.Entry<Store, List<KeyValue>> entry : tempMemstore.entrySet()) {\n Store store = entry.getKey();\n size += store.upsert(entry.getValue());\n allKVs.addAll(entry.getValue());\n }\n size = this.addAndGetGlobalMemstoreSize(size);\n flush = isFlushSize(size);\n } finally {\n this.updatesLock.readLock().unlock();\n releaseRowLock(lid);\n }\n if (writeToWAL) {\n syncOrDefer(txid); // sync the transaction log outside the rowlock\n }\n } finally {\n closeRegionOperation();\n long after = EnvironmentEdgeManager.currentTimeMillis();\n this.opMetrics.updateIncrementMetrics(increment.getFamilyMap().keySet(), after - before);\n }\n \n if (flush) {\n // Request a cache flush. Do it outside update lock.\n requestFlush();\n }\n\n return new Result(allKVs);\n }\n\n /**\n * @param row\n * @param family\n * @param qualifier\n * @param amount\n * @param writeToWAL\n * @return The new value.\n * @throws IOException\n */\n public long incrementColumnValue(byte [] row, byte [] family,\n byte [] qualifier, long amount, boolean writeToWAL)\n throws IOException {\n // to be used for metrics\n long before = EnvironmentEdgeManager.currentTimeMillis();\n\n checkRow(row, \"increment\");\n boolean flush = false;\n boolean wrongLength = false;\n long txid = 0;\n // Lock row\n long result = amount;\n startRegionOperation();\n this.writeRequestsCount.increment();\n try {\n Integer lid = obtainRowLock(row);\n this.updatesLock.readLock().lock();\n try {\n Store store = stores.get(family);\n\n // Get the old value:\n Get get = new Get(row);\n get.addColumn(family, qualifier);\n\n // we don't want to invoke coprocessor in this case; ICV is wrapped\n // in HRegionServer, so we leave getLastIncrement alone\n List<KeyValue> results = get(get, false);\n\n if (!results.isEmpty()) {\n KeyValue kv = results.get(0);\n if(kv.getValueLength() == Bytes.SIZEOF_LONG){\n byte [] buffer = kv.getBuffer();\n int valueOffset = kv.getValueOffset();\n result += Bytes.toLong(buffer, valueOffset, Bytes.SIZEOF_LONG);\n }\n else{\n wrongLength = true;\n }\n }\n if(!wrongLength){\n // build the KeyValue now:\n KeyValue newKv = new KeyValue(row, family,\n qualifier, EnvironmentEdgeManager.currentTimeMillis(),\n Bytes.toBytes(result));\n\n // now log it:\n if (writeToWAL) {\n long now = EnvironmentEdgeManager.currentTimeMillis();\n WALEdit walEdit = new WALEdit();\n walEdit.add(newKv);\n // Using default cluster id, as this can only happen in the\n // orginating cluster. A slave cluster receives the final value (not\n // the delta) as a Put.\n txid = this.log.appendNoSync(regionInfo, this.htableDescriptor.getName(),\n walEdit, HConstants.DEFAULT_CLUSTER_ID, now,\n this.htableDescriptor);\n }\n\n // Now request the ICV to the store, this will set the timestamp\n // appropriately depending on if there is a value in memcache or not.\n // returns the change in the size of the memstore from operation\n long size = store.updateColumnValue(row, family, qualifier, result);\n\n size = this.addAndGetGlobalMemstoreSize(size);\n flush = isFlushSize(size);\n }\n } finally {\n this.updatesLock.readLock().unlock();\n releaseRowLock(lid);\n }\n if (writeToWAL) {\n syncOrDefer(txid); // sync the transaction log outside the rowlock\n }\n } finally {\n closeRegionOperation();\n }\n\n // do after lock\n long after = EnvironmentEdgeManager.currentTimeMillis();\n this.opMetrics.updateIncrementColumnValueMetrics(family, after - before);\n\n if (flush) {\n // Request a cache flush. Do it outside update lock.\n requestFlush();\n }\n if(wrongLength){\n throw new DoNotRetryIOException(\n \"Attempted to increment field that isn't 64 bits wide\");\n }\n return result;\n }\n\n\n //\n // New HBASE-880 Helpers\n //\n\n private void checkFamily(final byte [] family)\n throws NoSuchColumnFamilyException {\n if (!this.htableDescriptor.hasFamily(family)) {\n throw new NoSuchColumnFamilyException(\"Column family \" +\n Bytes.toString(family) + \" does not exist in region \" + this\n + \" in table \" + this.htableDescriptor);\n \t}\n }\n\n public static final long FIXED_OVERHEAD = ClassSize.align(\n ClassSize.OBJECT +\n ClassSize.ARRAY +\n 34 * ClassSize.REFERENCE + Bytes.SIZEOF_INT +\n (5 * Bytes.SIZEOF_LONG) +\n Bytes.SIZEOF_BOOLEAN);\n\n public static final long DEEP_OVERHEAD = FIXED_OVERHEAD +\n ClassSize.OBJECT + // closeLock\n (2 * ClassSize.ATOMIC_BOOLEAN) + // closed, closing\n (3 * ClassSize.ATOMIC_LONG) + // memStoreSize, numPutsWithoutWAL, dataInMemoryWithoutWAL\n ClassSize.ATOMIC_INTEGER + // lockIdGenerator\n (3 * ClassSize.CONCURRENT_HASHMAP) + // lockedRows, lockIds, scannerReadPoints\n WriteState.HEAP_SIZE + // writestate\n ClassSize.CONCURRENT_SKIPLISTMAP + ClassSize.CONCURRENT_SKIPLISTMAP_ENTRY + // stores\n (2 * ClassSize.REENTRANT_LOCK) + // lock, updatesLock\n ClassSize.ARRAYLIST + // recentFlushes\n MultiVersionConsistencyControl.FIXED_SIZE // mvcc\n ;\n\n @Override\n public long heapSize() {\n long heapSize = DEEP_OVERHEAD;\n for(Store store : this.stores.values()) {\n heapSize += store.heapSize();\n }\n // this does not take into account row locks, recent flushes, mvcc entries\n return heapSize;\n }\n\n /*\n * This method calls System.exit.\n * @param message Message to print out. May be null.\n */\n private static void printUsageAndExit(final String message) {\n if (message != null && message.length() > 0) System.out.println(message);\n System.out.println(\"Usage: HRegion CATLALOG_TABLE_DIR [major_compact]\");\n System.out.println(\"Options:\");\n System.out.println(\" major_compact Pass this option to major compact \" +\n \"passed region.\");\n System.out.println(\"Default outputs scan of passed region.\");\n System.exit(1);\n }\n\n /**\n * Registers a new CoprocessorProtocol subclass and instance to\n * be available for handling {@link HRegion#exec(Exec)} calls.\n *\n * <p>\n * Only a single protocol type/handler combination may be registered per\n * region.\n * After the first registration, subsequent calls with the same protocol type\n * will fail with a return value of {@code false}.\n * </p>\n * @param protocol a {@code CoprocessorProtocol} subinterface defining the\n * protocol methods\n * @param handler an instance implementing the interface\n * @param <T> the protocol type\n * @return {@code true} if the registration was successful, {@code false}\n * otherwise\n */\n public <T extends CoprocessorProtocol> boolean registerProtocol(\n Class<T> protocol, T handler) {\n\n /* No stacking of protocol handlers is currently allowed. The\n * first to claim wins!\n */\n if (protocolHandlers.containsKey(protocol)) {\n LOG.error(\"Protocol \"+protocol.getName()+\n \" already registered, rejecting request from \"+\n handler\n );\n return false;\n }\n\n protocolHandlers.putInstance(protocol, handler);\n protocolHandlerNames.put(protocol.getName(), protocol);\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"Registered protocol handler: region=\"+\n Bytes.toStringBinary(getRegionName())+\" protocol=\"+protocol.getName());\n }\n return true;\n }\n\n /**\n * Executes a single {@link org.apache.hadoop.hbase.ipc.CoprocessorProtocol}\n * method using the registered protocol handlers.\n * {@link CoprocessorProtocol} implementations must be registered via the\n * {@link org.apache.hadoop.hbase.regionserver.HRegion#registerProtocol(Class, org.apache.hadoop.hbase.ipc.CoprocessorProtocol)}\n * method before they are available.\n *\n * @param call an {@code Exec} instance identifying the protocol, method name,\n * and parameters for the method invocation\n * @return an {@code ExecResult} instance containing the region name of the\n * invocation and the return value\n * @throws IOException if no registered protocol handler is found or an error\n * occurs during the invocation\n * @see org.apache.hadoop.hbase.regionserver.HRegion#registerProtocol(Class, org.apache.hadoop.hbase.ipc.CoprocessorProtocol)\n */\n public ExecResult exec(Exec call)\n throws IOException {\n Class<? extends CoprocessorProtocol> protocol = call.getProtocol();\n if (protocol == null) {\n String protocolName = call.getProtocolName();\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"Received dynamic protocol exec call with protocolName \" + protocolName);\n }\n // detect the actual protocol class\n protocol = protocolHandlerNames.get(protocolName);\n if (protocol == null) {\n throw new HBaseRPC.UnknownProtocolException(protocol,\n \"No matching handler for protocol \"+protocolName+\n \" in region \"+Bytes.toStringBinary(getRegionName()));\n }\n }\n if (!protocolHandlers.containsKey(protocol)) {\n throw new HBaseRPC.UnknownProtocolException(protocol,\n \"No matching handler for protocol \"+protocol.getName()+\n \" in region \"+Bytes.toStringBinary(getRegionName()));\n }\n\n CoprocessorProtocol handler = protocolHandlers.getInstance(protocol);\n Object value;\n\n try {\n Method method = protocol.getMethod(\n call.getMethodName(), call.getParameterClasses());\n method.setAccessible(true);\n\n value = method.invoke(handler, call.getParameters());\n } catch (InvocationTargetException e) {\n Throwable target = e.getTargetException();\n if (target instanceof IOException) {\n throw (IOException)target;\n }\n IOException ioe = new IOException(target.toString());\n ioe.setStackTrace(target.getStackTrace());\n throw ioe;\n } catch (Throwable e) {\n if (!(e instanceof IOException)) {\n LOG.error(\"Unexpected throwable object \", e);\n }\n IOException ioe = new IOException(e.toString());\n ioe.setStackTrace(e.getStackTrace());\n throw ioe;\n }\n\n return new ExecResult(getRegionName(), value);\n }\n\n /*\n * Process table.\n * Do major compaction or list content.\n * @param fs\n * @param p\n * @param log\n * @param c\n * @param majorCompact\n * @throws IOException\n */\n private static void processTable(final FileSystem fs, final Path p,\n final HLog log, final Configuration c,\n final boolean majorCompact)\n throws IOException {\n HRegion region = null;\n String rootStr = Bytes.toString(HConstants.ROOT_TABLE_NAME);\n String metaStr = Bytes.toString(HConstants.META_TABLE_NAME);\n // Currently expects tables have one region only.\n if (p.getName().startsWith(rootStr)) {\n region = HRegion.newHRegion(p, log, fs, c, HRegionInfo.ROOT_REGIONINFO,\n HTableDescriptor.ROOT_TABLEDESC, null);\n } else if (p.getName().startsWith(metaStr)) {\n region = HRegion.newHRegion(p, log, fs, c,\n HRegionInfo.FIRST_META_REGIONINFO, HTableDescriptor.META_TABLEDESC, null);\n } else {\n throw new IOException(\"Not a known catalog table: \" + p.toString());\n }\n try {\n region.initialize();\n if (majorCompact) {\n region.compactStores(true);\n } else {\n // Default behavior\n Scan scan = new Scan();\n // scan.addFamily(HConstants.CATALOG_FAMILY);\n RegionScanner scanner = region.getScanner(scan);\n try {\n List<KeyValue> kvs = new ArrayList<KeyValue>();\n boolean done = false;\n do {\n kvs.clear();\n done = scanner.next(kvs);\n if (kvs.size() > 0) LOG.info(kvs);\n } while (done);\n } finally {\n scanner.close();\n }\n }\n } finally {\n region.close();\n }\n }\n\n boolean shouldForceSplit() {\n return this.splitRequest;\n }\n\n byte[] getExplicitSplitPoint() {\n return this.explicitSplitPoint;\n }\n\n void forceSplit(byte[] sp) {\n // NOTE : this HRegion will go away after the forced split is successfull\n // therefore, no reason to clear this value\n this.splitRequest = true;\n if (sp != null) {\n this.explicitSplitPoint = sp;\n }\n }\n\n void clearSplit_TESTS_ONLY() {\n this.splitRequest = false;\n }\n\n /**\n * Give the region a chance to prepare before it is split.\n */\n protected void prepareToSplit() {\n // nothing\n }\n\n /**\n * Return the splitpoint. null indicates the region isn't splittable\n * If the splitpoint isn't explicitly specified, it will go over the stores\n * to find the best splitpoint. Currently the criteria of best splitpoint\n * is based on the size of the store.\n */\n public byte[] checkSplit() {\n // Can't split META\n if (getRegionInfo().isMetaRegion()) {\n if (shouldForceSplit()) {\n LOG.warn(\"Cannot split meta regions in HBase 0.20 and above\");\n }\n return null;\n }\n\n if (!splitPolicy.shouldSplit()) {\n return null;\n }\n\n byte[] ret = splitPolicy.getSplitPoint();\n\n if (ret != null) {\n try {\n checkRow(ret, \"calculated split\");\n } catch (IOException e) {\n LOG.error(\"Ignoring invalid split\", e);\n return null;\n }\n }\n return ret;\n }\n\n /**\n * @return The priority that this region should have in the compaction queue\n */\n public int getCompactPriority() {\n int count = Integer.MAX_VALUE;\n for(Store store : stores.values()) {\n count = Math.min(count, store.getCompactPriority());\n }\n return count;\n }\n\n /**\n * Checks every store to see if one has too many\n * store files\n * @return true if any store has too many store files\n */\n public boolean needsCompaction() {\n for(Store store : stores.values()) {\n if(store.needsCompaction()) {\n return true;\n }\n }\n return false;\n }\n\n /** @return the coprocessor host */\n public RegionCoprocessorHost getCoprocessorHost() {\n return coprocessorHost;\n }\n\n /** @param coprocessorHost the new coprocessor host */\n public void setCoprocessorHost(final RegionCoprocessorHost coprocessorHost) {\n this.coprocessorHost = coprocessorHost;\n }\n\n /**\n * This method needs to be called before any public call that reads or\n * modifies data. It has to be called just before a try.\n * #closeRegionOperation needs to be called in the try's finally block\n * Acquires a read lock and checks if the region is closing or closed.\n * @throws NotServingRegionException when the region is closing or closed\n */\n private void startRegionOperation() throws NotServingRegionException {\n if (this.closing.get()) {\n throw new NotServingRegionException(regionInfo.getRegionNameAsString() +\n \" is closing\");\n }\n lock.readLock().lock();\n if (this.closed.get()) {\n lock.readLock().unlock();\n throw new NotServingRegionException(regionInfo.getRegionNameAsString() +\n \" is closed\");\n }\n }\n\n /**\n * Closes the lock. This needs to be called in the finally block corresponding\n * to the try block of #startRegionOperation\n */\n private void closeRegionOperation(){\n lock.readLock().unlock();\n }\n\n /**\n * This method needs to be called before any public call that reads or\n * modifies stores in bulk. It has to be called just before a try.\n * #closeBulkRegionOperation needs to be called in the try's finally block\n * Acquires a writelock and checks if the region is closing or closed.\n * @throws NotServingRegionException when the region is closing or closed\n */\n private void startBulkRegionOperation(boolean writeLockNeeded)\n throws NotServingRegionException {\n if (this.closing.get()) {\n throw new NotServingRegionException(regionInfo.getRegionNameAsString() +\n \" is closing\");\n }\n if (writeLockNeeded) lock.writeLock().lock();\n else lock.readLock().lock();\n if (this.closed.get()) {\n if (writeLockNeeded) lock.writeLock().unlock();\n else lock.readLock().unlock();\n throw new NotServingRegionException(regionInfo.getRegionNameAsString() +\n \" is closed\");\n }\n }\n\n /**\n * Closes the lock. This needs to be called in the finally block corresponding\n * to the try block of #startRegionOperation\n */\n private void closeBulkRegionOperation(){\n if (lock.writeLock().isHeldByCurrentThread()) lock.writeLock().unlock();\n else lock.readLock().unlock();\n }\n\n /**\n * Update counters for numer of puts without wal and the size of possible data loss.\n * These information are exposed by the region server metrics.\n */\n private void recordPutWithoutWal(final Map<byte [], List<KeyValue>> familyMap) {\n if (numPutsWithoutWAL.getAndIncrement() == 0) {\n LOG.info(\"writing data to region \" + this + \n \" with WAL disabled. Data may be lost in the event of a crash.\");\n }\n\n long putSize = 0;\n for (List<KeyValue> edits : familyMap.values()) {\n for (KeyValue kv : edits) {\n putSize += kv.getKeyLength() + kv.getValueLength();\n }\n }\n\n dataInMemoryWithoutWAL.addAndGet(putSize);\n }\n\n /**\n * Calls sync with the given transaction ID if the region's table is not\n * deferring it.\n * @param txid should sync up to which transaction\n * @throws IOException If anything goes wrong with DFS\n */\n private void syncOrDefer(long txid) throws IOException {\n if (this.regionInfo.isMetaRegion() ||\n !this.htableDescriptor.isDeferredLogFlush()) {\n this.log.sync(txid);\n }\n }\n\n /**\n * A mocked list implementaion - discards all updates.\n */\n private static final List<KeyValue> MOCKED_LIST = new AbstractList<KeyValue>() {\n\n @Override\n public void add(int index, KeyValue element) {\n // do nothing\n }\n\n @Override\n public boolean addAll(int index, Collection<? extends KeyValue> c) {\n return false; // this list is never changed as a result of an update\n }\n\n @Override\n public KeyValue get(int index) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public int size() {\n return 0;\n }\n };\n\n\n /**\n * Facility for dumping and compacting catalog tables.\n * Only does catalog tables since these are only tables we for sure know\n * schema on. For usage run:\n * <pre>\n * ./bin/hbase org.apache.hadoop.hbase.regionserver.HRegion\n * </pre>\n * @param args\n * @throws IOException\n */\n public static void main(String[] args) throws IOException {\n if (args.length < 1) {\n printUsageAndExit(null);\n }\n boolean majorCompact = false;\n if (args.length > 1) {\n if (!args[1].toLowerCase().startsWith(\"major\")) {\n printUsageAndExit(\"ERROR: Unrecognized option <\" + args[1] + \">\");\n }\n majorCompact = true;\n }\n final Path tableDir = new Path(args[0]);\n final Configuration c = HBaseConfiguration.create();\n final FileSystem fs = FileSystem.get(c);\n final Path logdir = new Path(c.get(\"hbase.tmp.dir\"),\n \"hlog\" + tableDir.getName()\n + EnvironmentEdgeManager.currentTimeMillis());\n final Path oldLogDir = new Path(c.get(\"hbase.tmp.dir\"),\n HConstants.HREGION_OLDLOGDIR_NAME);\n final HLog log = new HLog(fs, logdir, oldLogDir, c);\n try {\n processTable(fs, tableDir, log, c, majorCompact);\n } finally {\n log.close();\n // TODO: is this still right?\n BlockCache bc = new CacheConfig(c).getBlockCache();\n if (bc != null) bc.shutdown();\n }\n }\n}", "public class HRegionServer implements HRegionInterface, HBaseRPCErrorHandler,\n Runnable, RegionServerServices {\n\n public static final Log LOG = LogFactory.getLog(HRegionServer.class);\n\n // Set when a report to the master comes back with a message asking us to\n // shutdown. Also set by call to stop when debugging or running unit tests\n // of HRegionServer in isolation.\n protected volatile boolean stopped = false;\n\n // A state before we go into stopped state. At this stage we're closing user\n // space regions.\n private boolean stopping = false;\n\n // Go down hard. Used if file system becomes unavailable and also in\n // debugging and unit tests.\n protected volatile boolean abortRequested;\n\n private volatile boolean killed = false;\n\n // If false, the file system has become unavailable\n protected volatile boolean fsOk;\n\n protected final Configuration conf;\n\n protected final AtomicBoolean haveRootRegion = new AtomicBoolean(false);\n private HFileSystem fs;\n private boolean useHBaseChecksum; // verify hbase checksums?\n private Path rootDir;\n private final Random rand = new Random();\n\n //RegionName vs current action in progress\n //true - if open region action in progress\n //false - if close region action in progress\n private final ConcurrentSkipListMap<byte[], Boolean> regionsInTransitionInRS =\n new ConcurrentSkipListMap<byte[], Boolean>(Bytes.BYTES_COMPARATOR);\n\n /**\n * Map of regions currently being served by this region server. Key is the\n * encoded region name. All access should be synchronized.\n */\n protected final Map<String, HRegion> onlineRegions =\n new ConcurrentHashMap<String, HRegion>();\n\n protected final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();\n\n final int numRetries;\n protected final int threadWakeFrequency;\n private final int msgInterval;\n\n protected final int numRegionsToReport;\n\n private final long maxScannerResultSize;\n\n // Remote HMaster\n private HMasterRegionInterface hbaseMaster;\n\n // Server to handle client requests. Default access so can be accessed by\n // unit tests.\n RpcServer rpcServer;\n\n private final InetSocketAddress isa;\n\n // Leases\n private Leases leases;\n\n // Request counter.\n // Do we need this? Can't we just sum region counters? St.Ack 20110412\n private AtomicInteger requestCount = new AtomicInteger();\n\n // Info server. Default access so can be used by unit tests. REGIONSERVER\n // is name of the webapp and the attribute name used stuffing this instance\n // into web context.\n InfoServer infoServer;\n\n /** region server process name */\n public static final String REGIONSERVER = \"regionserver\";\n \n /** region server configuration name */\n public static final String REGIONSERVER_CONF = \"regionserver_conf\";\n\n /*\n * Space is reserved in HRS constructor and then released when aborting to\n * recover from an OOME. See HBASE-706. TODO: Make this percentage of the heap\n * or a minimum.\n */\n private final LinkedList<byte[]> reservedSpace = new LinkedList<byte[]>();\n\n private RegionServerMetrics metrics;\n\n private RegionServerDynamicMetrics dynamicMetrics;\n\n // Compactions\n public CompactSplitThread compactSplitThread;\n\n // Cache flushing\n MemStoreFlusher cacheFlusher;\n\n /*\n * Check for compactions requests.\n */\n Chore compactionChecker;\n\n // HLog and HLog roller. log is protected rather than private to avoid\n // eclipse warning when accessed by inner classes\n protected volatile HLog hlog;\n LogRoller hlogRoller;\n\n // flag set after we're done setting up server threads (used for testing)\n protected volatile boolean isOnline;\n\n final Map<String, RegionScanner> scanners =\n new ConcurrentHashMap<String, RegionScanner>();\n\n // zookeeper connection and watcher\n private ZooKeeperWatcher zooKeeper;\n\n // master address manager and watcher\n private MasterAddressTracker masterAddressManager;\n\n // catalog tracker\n private CatalogTracker catalogTracker;\n\n // Cluster Status Tracker\n private ClusterStatusTracker clusterStatusTracker;\n\n // Log Splitting Worker\n private SplitLogWorker splitLogWorker;\n\n // A sleeper that sleeps for msgInterval.\n private final Sleeper sleeper;\n\n private final int rpcTimeout;\n\n // Instance of the hbase executor service.\n private ExecutorService service;\n\n // Replication services. If no replication, this handler will be null.\n private ReplicationSourceService replicationSourceHandler;\n private ReplicationSinkService replicationSinkHandler;\n\n private final RegionServerAccounting regionServerAccounting;\n\n // Cache configuration and block cache reference\n private final CacheConfig cacheConfig;\n\n // reference to the Thrift Server.\n volatile private HRegionThriftServer thriftServer;\n\n /**\n * The server name the Master sees us as. Its made from the hostname the\n * master passes us, port, and server startcode. Gets set after registration\n * against Master. The hostname can differ from the hostname in {@link #isa}\n * but usually doesn't if both servers resolve .\n */\n private ServerName serverNameFromMasterPOV;\n\n // Port we put up the webui on.\n private int webuiport = -1;\n\n /**\n * This servers startcode.\n */\n private final long startcode;\n\n /**\n * Go here to get table descriptors.\n */\n private TableDescriptors tableDescriptors;\n\n /*\n * Strings to be used in forming the exception message for\n * RegionsAlreadyInTransitionException.\n */\n private static final String OPEN = \"OPEN\";\n private static final String CLOSE = \"CLOSE\";\n\n /**\n * MX Bean for RegionServerInfo\n */\n private ObjectName mxBean = null;\n\n /**\n * ClusterId\n */\n private ClusterId clusterId = null;\n\n /**\n * Starts a HRegionServer at the default location\n *\n * @param conf\n * @throws IOException\n * @throws InterruptedException\n */\n public HRegionServer(Configuration conf)\n throws IOException, InterruptedException {\n this.fsOk = true;\n this.conf = conf;\n // Set how many times to retry talking to another server over HConnection.\n HConnectionManager.setServerSideHConnectionRetries(this.conf, LOG);\n this.isOnline = false;\n checkCodecs(this.conf);\n\n // do we use checksum verfication in the hbase? If hbase checksum verification\n // is enabled, then we automatically switch off hdfs checksum verification.\n this.useHBaseChecksum = conf.getBoolean(\n HConstants.HBASE_CHECKSUM_VERIFICATION, true);\n\n // Config'ed params\n this.numRetries = conf.getInt(\"hbase.client.retries.number\", 10);\n this.threadWakeFrequency = conf.getInt(HConstants.THREAD_WAKE_FREQUENCY,\n 10 * 1000);\n this.msgInterval = conf.getInt(\"hbase.regionserver.msginterval\", 3 * 1000);\n\n this.sleeper = new Sleeper(this.msgInterval, this);\n\n this.maxScannerResultSize = conf.getLong(\n HConstants.HBASE_CLIENT_SCANNER_MAX_RESULT_SIZE_KEY,\n HConstants.DEFAULT_HBASE_CLIENT_SCANNER_MAX_RESULT_SIZE);\n\n this.numRegionsToReport = conf.getInt(\n \"hbase.regionserver.numregionstoreport\", 10);\n\n this.rpcTimeout = conf.getInt(\n HConstants.HBASE_RPC_TIMEOUT_KEY,\n HConstants.DEFAULT_HBASE_RPC_TIMEOUT);\n\n this.abortRequested = false;\n this.stopped = false;\n\n // Server to handle client requests.\n String hostname = Strings.domainNamePointerToHostName(DNS.getDefaultHost(\n conf.get(\"hbase.regionserver.dns.interface\", \"default\"),\n conf.get(\"hbase.regionserver.dns.nameserver\", \"default\")));\n int port = conf.getInt(HConstants.REGIONSERVER_PORT,\n HConstants.DEFAULT_REGIONSERVER_PORT);\n // Creation of a HSA will force a resolve.\n InetSocketAddress initialIsa = new InetSocketAddress(hostname, port);\n if (initialIsa.getAddress() == null) {\n throw new IllegalArgumentException(\"Failed resolve of \" + initialIsa);\n }\n this.rpcServer = HBaseRPC.getServer(this,\n new Class<?>[]{HRegionInterface.class, HBaseRPCErrorHandler.class,\n OnlineRegions.class},\n initialIsa.getHostName(), // BindAddress is IP we got for this server.\n initialIsa.getPort(),\n conf.getInt(\"hbase.regionserver.handler.count\", 10),\n conf.getInt(\"hbase.regionserver.metahandler.count\", 10),\n conf.getBoolean(\"hbase.rpc.verbose\", false),\n conf, HConstants.QOS_THRESHOLD);\n // Set our address.\n this.isa = this.rpcServer.getListenerAddress();\n\n this.rpcServer.setErrorHandler(this);\n this.rpcServer.setQosFunction(new QosFunction());\n this.startcode = System.currentTimeMillis();\n\n // login the server principal (if using secure Hadoop)\n User.login(this.conf, \"hbase.regionserver.keytab.file\",\n \"hbase.regionserver.kerberos.principal\", this.isa.getHostName());\n regionServerAccounting = new RegionServerAccounting();\n cacheConfig = new CacheConfig(conf);\n }\n\n /**\n * Run test on configured codecs to make sure supporting libs are in place.\n * @param c\n * @throws IOException\n */\n private static void checkCodecs(final Configuration c) throws IOException {\n // check to see if the codec list is available:\n String [] codecs = c.getStrings(\"hbase.regionserver.codecs\", (String[])null);\n if (codecs == null) return;\n for (String codec : codecs) {\n if (!CompressionTest.testCompression(codec)) {\n throw new IOException(\"Compression codec \" + codec +\n \" not supported, aborting RS construction\");\n }\n }\n }\n\n\n @Retention(RetentionPolicy.RUNTIME)\n private @interface QosPriority {\n int priority() default 0;\n }\n\n /**\n * Utility used ensuring higher quality of service for priority rpcs; e.g.\n * rpcs to .META. and -ROOT-, etc.\n */\n class QosFunction implements Function<Writable,Integer> {\n private final Map<String, Integer> annotatedQos;\n\n public QosFunction() {\n Map<String, Integer> qosMap = new HashMap<String, Integer>();\n for (Method m : HRegionServer.class.getMethods()) {\n QosPriority p = m.getAnnotation(QosPriority.class);\n if (p != null) {\n qosMap.put(m.getName(), p.priority());\n }\n }\n\n annotatedQos = qosMap;\n }\n\n public boolean isMetaRegion(byte[] regionName) {\n HRegion region;\n try {\n region = getRegion(regionName);\n } catch (NotServingRegionException ignored) {\n return false;\n }\n return region.getRegionInfo().isMetaRegion();\n }\n\n @Override\n public Integer apply(Writable from) {\n if (!(from instanceof Invocation)) return HConstants.NORMAL_QOS;\n\n Invocation inv = (Invocation) from;\n String methodName = inv.getMethodName();\n\n Integer priorityByAnnotation = annotatedQos.get(methodName);\n if (priorityByAnnotation != null) {\n return priorityByAnnotation;\n }\n\n // scanner methods...\n if (methodName.equals(\"next\") || methodName.equals(\"close\")) {\n // translate!\n Long scannerId;\n try {\n scannerId = (Long) inv.getParameters()[0];\n } catch (ClassCastException ignored) {\n // LOG.debug(\"Low priority: \" + from);\n return HConstants.NORMAL_QOS;\n }\n String scannerIdString = Long.toString(scannerId);\n RegionScanner scanner = scanners.get(scannerIdString);\n if (scanner != null && scanner.getRegionInfo().isMetaRegion()) {\n // LOG.debug(\"High priority scanner request: \" + scannerId);\n return HConstants.HIGH_QOS;\n }\n } else if (inv.getParameterClasses().length == 0) {\n // Just let it through. This is getOnlineRegions, etc.\n } else if (inv.getParameterClasses()[0] == byte[].class) {\n // first arg is byte array, so assume this is a regionname:\n if (isMetaRegion((byte[]) inv.getParameters()[0])) {\n // LOG.debug(\"High priority with method: \" + methodName +\n // \" and region: \"\n // + Bytes.toString((byte[]) inv.getParameters()[0]));\n return HConstants.HIGH_QOS;\n }\n } else if (inv.getParameterClasses()[0] == MultiAction.class) {\n MultiAction<?> ma = (MultiAction<?>) inv.getParameters()[0];\n Set<byte[]> regions = ma.getRegions();\n // ok this sucks, but if any single of the actions touches a meta, the\n // whole\n // thing gets pingged high priority. This is a dangerous hack because\n // people\n // can get their multi action tagged high QOS by tossing a Get(.META.)\n // AND this\n // regionserver hosts META/-ROOT-\n for (byte[] region : regions) {\n if (isMetaRegion(region)) {\n // LOG.debug(\"High priority multi with region: \" +\n // Bytes.toString(region));\n return HConstants.HIGH_QOS; // short circuit for the win.\n }\n }\n }\n // LOG.debug(\"Low priority: \" + from.toString());\n return HConstants.NORMAL_QOS;\n }\n }\n\n /**\n * All initialization needed before we go register with Master.\n *\n * @throws IOException\n * @throws InterruptedException\n */\n private void preRegistrationInitialization(){\n try {\n initializeZooKeeper();\n\n clusterId = new ClusterId(zooKeeper, this);\n if(clusterId.hasId()) {\n conf.set(HConstants.CLUSTER_ID, clusterId.getId());\n }\n\n initializeThreads();\n int nbBlocks = conf.getInt(\"hbase.regionserver.nbreservationblocks\", 4);\n for (int i = 0; i < nbBlocks; i++) {\n reservedSpace.add(new byte[HConstants.DEFAULT_SIZE_RESERVATION_BLOCK]);\n }\n } catch (Throwable t) {\n // Call stop if error or process will stick around for ever since server\n // puts up non-daemon threads.\n this.rpcServer.stop();\n abort(\"Initialization of RS failed. Hence aborting RS.\", t);\n }\n }\n\n /**\n * Bring up connection to zk ensemble and then wait until a master for this\n * cluster and then after that, wait until cluster 'up' flag has been set.\n * This is the order in which master does things.\n * Finally put up a catalog tracker.\n * @throws IOException\n * @throws InterruptedException\n */\n private void initializeZooKeeper() throws IOException, InterruptedException {\n // Open connection to zookeeper and set primary watcher\n this.zooKeeper = new ZooKeeperWatcher(conf, REGIONSERVER + \":\" +\n this.isa.getPort(), this);\n\n // Create the master address manager, register with zk, and start it. Then\n // block until a master is available. No point in starting up if no master\n // running.\n this.masterAddressManager = new MasterAddressTracker(this.zooKeeper, this);\n this.masterAddressManager.start();\n blockAndCheckIfStopped(this.masterAddressManager);\n\n // Wait on cluster being up. Master will set this flag up in zookeeper\n // when ready.\n this.clusterStatusTracker = new ClusterStatusTracker(this.zooKeeper, this);\n this.clusterStatusTracker.start();\n blockAndCheckIfStopped(this.clusterStatusTracker);\n\n // Create the catalog tracker and start it;\n this.catalogTracker = new CatalogTracker(this.zooKeeper, this.conf,\n this, this.conf.getInt(\"hbase.regionserver.catalog.timeout\", Integer.MAX_VALUE));\n catalogTracker.start();\n }\n\n /**\n * Utilty method to wait indefinitely on a znode availability while checking\n * if the region server is shut down\n * @param tracker znode tracker to use\n * @throws IOException any IO exception, plus if the RS is stopped\n * @throws InterruptedException\n */\n private void blockAndCheckIfStopped(ZooKeeperNodeTracker tracker)\n throws IOException, InterruptedException {\n while (tracker.blockUntilAvailable(this.msgInterval, false) == null) {\n if (this.stopped) {\n throw new IOException(\"Received the shutdown message while waiting.\");\n }\n }\n }\n\n /**\n * @return False if cluster shutdown in progress\n */\n private boolean isClusterUp() {\n return this.clusterStatusTracker.isClusterUp();\n }\n\n private void initializeThreads() throws IOException {\n // Cache flushing thread.\n this.cacheFlusher = new MemStoreFlusher(conf, this);\n\n // Compaction thread\n this.compactSplitThread = new CompactSplitThread(this);\n\n // Background thread to check for compactions; needed if region\n // has not gotten updates in a while. Make it run at a lesser frequency.\n int multiplier = this.conf.getInt(HConstants.THREAD_WAKE_FREQUENCY +\n \".multiplier\", 1000);\n this.compactionChecker = new CompactionChecker(this,\n this.threadWakeFrequency * multiplier, this);\n\n this.leases = new Leases((int) conf.getLong(\n HConstants.HBASE_REGIONSERVER_LEASE_PERIOD_KEY,\n HConstants.DEFAULT_HBASE_REGIONSERVER_LEASE_PERIOD),\n this.threadWakeFrequency);\n\n // Create the thread for the ThriftServer.\n if (conf.getBoolean(\"hbase.regionserver.export.thrift\", false)) {\n thriftServer = new HRegionThriftServer(this, conf);\n thriftServer.start();\n LOG.info(\"Started Thrift API from Region Server.\");\n }\n }\n\n /**\n * The HRegionServer sticks in this loop until closed.\n */\n @SuppressWarnings(\"deprecation\")\n public void run() {\n try {\n // Do pre-registration initializations; zookeeper, lease threads, etc.\n preRegistrationInitialization();\n } catch (Throwable e) {\n abort(\"Fatal exception during initialization\", e);\n }\n\n try {\n // Try and register with the Master; tell it we are here. Break if\n // server is stopped or the clusterup flag is down or hdfs went wacky.\n while (keepLooping()) {\n MapWritable w = reportForDuty();\n if (w == null) {\n LOG.warn(\"reportForDuty failed; sleeping and then retrying.\");\n this.sleeper.sleep();\n } else {\n handleReportForDutyResponse(w);\n break;\n }\n }\n registerMBean();\n\n // We registered with the Master. Go into run mode.\n long lastMsg = 0;\n long oldRequestCount = -1;\n // The main run loop.\n while (!this.stopped && isHealthy()) {\n if (!isClusterUp()) {\n if (isOnlineRegionsEmpty()) {\n stop(\"Exiting; cluster shutdown set and not carrying any regions\");\n } else if (!this.stopping) {\n this.stopping = true;\n LOG.info(\"Closing user regions\");\n closeUserRegions(this.abortRequested);\n } else if (this.stopping) {\n boolean allUserRegionsOffline = areAllUserRegionsOffline();\n if (allUserRegionsOffline) {\n // Set stopped if no requests since last time we went around the loop.\n // The remaining meta regions will be closed on our way out.\n if (oldRequestCount == this.requestCount.get()) {\n stop(\"Stopped; only catalog regions remaining online\");\n break;\n }\n oldRequestCount = this.requestCount.get();\n } else {\n // Make sure all regions have been closed -- some regions may\n // have not got it because we were splitting at the time of\n // the call to closeUserRegions.\n closeUserRegions(this.abortRequested);\n }\n LOG.debug(\"Waiting on \" + getOnlineRegionsAsPrintableString());\n }\n }\n long now = System.currentTimeMillis();\n if ((now - lastMsg) >= msgInterval) {\n doMetrics();\n tryRegionServerReport();\n lastMsg = System.currentTimeMillis();\n }\n if (!this.stopped) this.sleeper.sleep();\n } // for\n } catch (Throwable t) {\n if (!checkOOME(t)) {\n abort(\"Unhandled exception: \" + t.getMessage(), t);\n }\n }\n // Run shutdown.\n if (mxBean != null) {\n MBeanUtil.unregisterMBean(mxBean);\n mxBean = null;\n }\n if (this.thriftServer != null) this.thriftServer.shutdown();\n this.leases.closeAfterLeasesExpire();\n this.rpcServer.stop();\n if (this.splitLogWorker != null) {\n splitLogWorker.stop();\n }\n if (this.infoServer != null) {\n LOG.info(\"Stopping infoServer\");\n try {\n this.infoServer.stop();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n // Send cache a shutdown.\n if (cacheConfig.isBlockCacheEnabled()) {\n cacheConfig.getBlockCache().shutdown();\n }\n\n // Send interrupts to wake up threads if sleeping so they notice shutdown.\n // TODO: Should we check they are alive? If OOME could have exited already\n if (this.cacheFlusher != null) this.cacheFlusher.interruptIfNecessary();\n if (this.compactSplitThread != null) this.compactSplitThread.interruptIfNecessary();\n if (this.hlogRoller != null) this.hlogRoller.interruptIfNecessary();\n if (this.compactionChecker != null)\n this.compactionChecker.interrupt();\n\n if (this.killed) {\n // Just skip out w/o closing regions. Used when testing.\n } else if (abortRequested) {\n if (this.fsOk) {\n closeUserRegions(abortRequested); // Don't leave any open file handles\n }\n LOG.info(\"aborting server \" + this.serverNameFromMasterPOV);\n } else {\n closeUserRegions(abortRequested);\n closeAllScanners();\n LOG.info(\"stopping server \" + this.serverNameFromMasterPOV);\n }\n // Interrupt catalog tracker here in case any regions being opened out in\n // handlers are stuck waiting on meta or root.\n if (this.catalogTracker != null) this.catalogTracker.stop();\n\n // Closing the compactSplit thread before closing meta regions\n if (!this.killed && containsMetaTableRegions()) {\n if (!abortRequested || this.fsOk) {\n if (this.compactSplitThread != null) {\n this.compactSplitThread.join();\n this.compactSplitThread = null;\n }\n closeMetaTableRegions(abortRequested);\n }\n }\n\n if (!this.killed && this.fsOk) {\n waitOnAllRegionsToClose(abortRequested);\n LOG.info(\"stopping server \" + this.serverNameFromMasterPOV +\n \"; all regions closed.\");\n }\n\n //fsOk flag may be changed when closing regions throws exception.\n if (!this.killed && this.fsOk) {\n closeWAL(abortRequested ? false : true);\n }\n\n // Make sure the proxy is down.\n if (this.hbaseMaster != null) {\n HBaseRPC.stopProxy(this.hbaseMaster);\n this.hbaseMaster = null;\n }\n this.leases.close();\n\n if (!killed) {\n join();\n }\n\n try {\n deleteMyEphemeralNode();\n } catch (KeeperException e) {\n LOG.warn(\"Failed deleting my ephemeral node\", e);\n }\n this.zooKeeper.close();\n LOG.info(\"stopping server \" + this.serverNameFromMasterPOV +\n \"; zookeeper connection closed.\");\n\n LOG.info(Thread.currentThread().getName() + \" exiting\");\n }\n\n private boolean containsMetaTableRegions() {\n return onlineRegions.containsKey(HRegionInfo.ROOT_REGIONINFO.getEncodedName())\n || onlineRegions.containsKey(HRegionInfo.FIRST_META_REGIONINFO.getEncodedName());\n }\n\n private boolean areAllUserRegionsOffline() {\n if (getNumberOfOnlineRegions() > 2) return false;\n boolean allUserRegionsOffline = true;\n for (Map.Entry<String, HRegion> e: this.onlineRegions.entrySet()) {\n if (!e.getValue().getRegionInfo().isMetaTable()) {\n allUserRegionsOffline = false;\n break;\n }\n }\n return allUserRegionsOffline;\n }\n\n void tryRegionServerReport()\n throws IOException {\n HServerLoad hsl = buildServerLoad();\n // Why we do this?\n this.requestCount.set(0);\n try {\n this.hbaseMaster.regionServerReport(this.serverNameFromMasterPOV.getVersionedBytes(), hsl);\n } catch (IOException ioe) {\n if (ioe instanceof RemoteException) {\n ioe = ((RemoteException)ioe).unwrapRemoteException();\n }\n if (ioe instanceof YouAreDeadException) {\n // This will be caught and handled as a fatal error in run()\n throw ioe;\n }\n // Couldn't connect to the master, get location from zk and reconnect\n // Method blocks until new master is found or we are stopped\n getMaster();\n }\n }\n\n HServerLoad buildServerLoad() {\n Collection<HRegion> regions = getOnlineRegionsLocalContext();\n TreeMap<byte [], HServerLoad.RegionLoad> regionLoads =\n new TreeMap<byte [], HServerLoad.RegionLoad>(Bytes.BYTES_COMPARATOR);\n for (HRegion region: regions) {\n regionLoads.put(region.getRegionName(), createRegionLoad(region));\n }\n MemoryUsage memory =\n ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();\n return new HServerLoad(requestCount.get(),(int)metrics.getRequests(),\n (int)(memory.getUsed() / 1024 / 1024),\n (int) (memory.getMax() / 1024 / 1024), regionLoads,\n this.hlog.getCoprocessorHost().getCoprocessors());\n }\n\n String getOnlineRegionsAsPrintableString() {\n StringBuilder sb = new StringBuilder();\n for (HRegion r: this.onlineRegions.values()) {\n if (sb.length() > 0) sb.append(\", \");\n sb.append(r.getRegionInfo().getEncodedName());\n }\n return sb.toString();\n }\n\n /**\n * Wait on regions close.\n */\n private void waitOnAllRegionsToClose(final boolean abort) {\n // Wait till all regions are closed before going out.\n int lastCount = -1;\n long previousLogTime = 0;\n Set<String> closedRegions = new HashSet<String>();\n while (!isOnlineRegionsEmpty()) {\n int count = getNumberOfOnlineRegions();\n // Only print a message if the count of regions has changed.\n if (count != lastCount) {\n // Log every second at most\n if (System.currentTimeMillis() > (previousLogTime + 1000)) {\n previousLogTime = System.currentTimeMillis();\n lastCount = count;\n LOG.info(\"Waiting on \" + count + \" regions to close\");\n // Only print out regions still closing if a small number else will\n // swamp the log.\n if (count < 10 && LOG.isDebugEnabled()) {\n LOG.debug(this.onlineRegions);\n }\n }\n }\n // Ensure all user regions have been sent a close. Use this to\n // protect against the case where an open comes in after we start the\n // iterator of onlineRegions to close all user regions.\n for (Map.Entry<String, HRegion> e : this.onlineRegions.entrySet()) {\n HRegionInfo hri = e.getValue().getRegionInfo();\n if (!this.regionsInTransitionInRS.containsKey(hri.getEncodedNameAsBytes())\n && !closedRegions.contains(hri.getEncodedName())) {\n closedRegions.add(hri.getEncodedName());\n // Don't update zk with this close transition; pass false.\n closeRegion(hri, abort, false);\n }\n }\n // No regions in RIT, we could stop waiting now.\n if (this.regionsInTransitionInRS.isEmpty()) {\n if (!isOnlineRegionsEmpty()) {\n LOG.info(\"We were exiting though online regions are not empty, because some regions failed closing\");\n }\n break;\n }\n Threads.sleep(200);\n }\n }\n\n private void closeWAL(final boolean delete) {\n try {\n if (this.hlog != null) {\n if (delete) {\n hlog.closeAndDelete();\n } else {\n hlog.close();\n }\n }\n } catch (Throwable e) {\n LOG.error(\"Close and delete failed\", RemoteExceptionHandler.checkThrowable(e));\n }\n }\n\n private void closeAllScanners() {\n // Close any outstanding scanners. Means they'll get an UnknownScanner\n // exception next time they come in.\n for (Map.Entry<String, RegionScanner> e : this.scanners.entrySet()) {\n try {\n e.getValue().close();\n } catch (IOException ioe) {\n LOG.warn(\"Closing scanner \" + e.getKey(), ioe);\n }\n }\n }\n\n /*\n * Run init. Sets up hlog and starts up all server threads.\n *\n * @param c Extra configuration.\n */\n protected void handleReportForDutyResponse(final MapWritable c)\n throws IOException {\n try {\n for (Map.Entry<Writable, Writable> e :c.entrySet()) {\n String key = e.getKey().toString();\n // The hostname the master sees us as.\n if (key.equals(HConstants.KEY_FOR_HOSTNAME_SEEN_BY_MASTER)) {\n String hostnameFromMasterPOV = e.getValue().toString();\n this.serverNameFromMasterPOV = new ServerName(hostnameFromMasterPOV,\n this.isa.getPort(), this.startcode);\n LOG.info(\"Master passed us hostname to use. Was=\" +\n this.isa.getHostName() + \", Now=\" +\n this.serverNameFromMasterPOV.getHostname());\n continue;\n }\n String value = e.getValue().toString();\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"Config from master: \" + key + \"=\" + value);\n }\n this.conf.set(key, value);\n }\n\n // hack! Maps DFSClient => RegionServer for logs. HDFS made this\n // config param for task trackers, but we can piggyback off of it.\n if (this.conf.get(\"mapred.task.id\") == null) {\n this.conf.set(\"mapred.task.id\", \"hb_rs_\" +\n this.serverNameFromMasterPOV.toString());\n }\n // Set our ephemeral znode up in zookeeper now we have a name.\n createMyEphemeralNode();\n\n // Master sent us hbase.rootdir to use. Should be fully qualified\n // path with file system specification included. Set 'fs.defaultFS'\n // to match the filesystem on hbase.rootdir else underlying hadoop hdfs\n // accessors will be going against wrong filesystem (unless all is set\n // to defaults).\n this.conf.set(\"fs.defaultFS\", this.conf.get(\"hbase.rootdir\"));\n // Get fs instance used by this RS\n this.fs = new HFileSystem(this.conf, this.useHBaseChecksum);\n this.rootDir = new Path(this.conf.get(HConstants.HBASE_DIR));\n this.tableDescriptors = new FSTableDescriptors(this.fs, this.rootDir, true);\n this.hlog = setupWALAndReplication();\n // Init in here rather than in constructor after thread name has been set\n this.metrics = new RegionServerMetrics();\n this.dynamicMetrics = RegionServerDynamicMetrics.newInstance();\n startServiceThreads();\n LOG.info(\"Serving as \" + this.serverNameFromMasterPOV +\n \", RPC listening on \" + this.isa +\n \", sessionid=0x\" +\n Long.toHexString(this.zooKeeper.getRecoverableZooKeeper().getSessionId()));\n isOnline = true;\n } catch (Throwable e) {\n this.isOnline = false;\n stop(\"Failed initialization\");\n throw convertThrowableToIOE(cleanup(e, \"Failed init\"),\n \"Region server startup failed\");\n } finally {\n sleeper.skipSleepCycle();\n }\n }\n\n private String getMyEphemeralNodePath() {\n return ZKUtil.joinZNode(this.zooKeeper.rsZNode, getServerName().toString());\n }\n\n private void createMyEphemeralNode() throws KeeperException {\n ZKUtil.createEphemeralNodeAndWatch(this.zooKeeper, getMyEphemeralNodePath(),\n HConstants.EMPTY_BYTE_ARRAY);\n }\n\n private void deleteMyEphemeralNode() throws KeeperException {\n ZKUtil.deleteNode(this.zooKeeper, getMyEphemeralNodePath());\n }\n\n public RegionServerAccounting getRegionServerAccounting() {\n return regionServerAccounting;\n }\n\n /*\n * @param r Region to get RegionLoad for.\n *\n * @return RegionLoad instance.\n *\n * @throws IOException\n */\n private HServerLoad.RegionLoad createRegionLoad(final HRegion r) {\n byte[] name = r.getRegionName();\n int stores = 0;\n int storefiles = 0;\n int storeUncompressedSizeMB = 0;\n int storefileSizeMB = 0;\n int memstoreSizeMB = (int) (r.memstoreSize.get() / 1024 / 1024);\n int storefileIndexSizeMB = 0;\n int rootIndexSizeKB = 0;\n int totalStaticIndexSizeKB = 0;\n int totalStaticBloomSizeKB = 0;\n long totalCompactingKVs = 0;\n long currentCompactedKVs = 0;\n synchronized (r.stores) {\n stores += r.stores.size();\n for (Store store : r.stores.values()) {\n storefiles += store.getStorefilesCount();\n storeUncompressedSizeMB += (int) (store.getStoreSizeUncompressed()\n / 1024 / 1024);\n storefileSizeMB += (int) (store.getStorefilesSize() / 1024 / 1024);\n storefileIndexSizeMB += (int) (store.getStorefilesIndexSize() / 1024 / 1024);\n CompactionProgress progress = store.getCompactionProgress();\n if (progress != null) {\n totalCompactingKVs += progress.totalCompactingKVs;\n currentCompactedKVs += progress.currentCompactedKVs;\n }\n\n rootIndexSizeKB +=\n (int) (store.getStorefilesIndexSize() / 1024);\n\n totalStaticIndexSizeKB +=\n (int) (store.getTotalStaticIndexSize() / 1024);\n\n totalStaticBloomSizeKB +=\n (int) (store.getTotalStaticBloomSize() / 1024);\n }\n }\n return new HServerLoad.RegionLoad(name, stores, storefiles,\n storeUncompressedSizeMB,\n storefileSizeMB, memstoreSizeMB, storefileIndexSizeMB, rootIndexSizeKB,\n totalStaticIndexSizeKB, totalStaticBloomSizeKB,\n (int) r.readRequestsCount.get(), (int) r.writeRequestsCount.get(),\n totalCompactingKVs, currentCompactedKVs,\n r.getCoprocessorHost().getCoprocessors());\n }\n\n /**\n * @param encodedRegionName\n * @return An instance of RegionLoad.\n */\n public HServerLoad.RegionLoad createRegionLoad(final String encodedRegionName) {\n HRegion r = null;\n r = this.onlineRegions.get(encodedRegionName);\n return r != null ? createRegionLoad(r) : null;\n }\n\n /*\n * Cleanup after Throwable caught invoking method. Converts <code>t</code> to\n * IOE if it isn't already.\n *\n * @param t Throwable\n *\n * @return Throwable converted to an IOE; methods can only let out IOEs.\n */\n private Throwable cleanup(final Throwable t) {\n return cleanup(t, null);\n }\n\n /*\n * Cleanup after Throwable caught invoking method. Converts <code>t</code> to\n * IOE if it isn't already.\n *\n * @param t Throwable\n *\n * @param msg Message to log in error. Can be null.\n *\n * @return Throwable converted to an IOE; methods can only let out IOEs.\n */\n private Throwable cleanup(final Throwable t, final String msg) {\n // Don't log as error if NSRE; NSRE is 'normal' operation.\n if (t instanceof NotServingRegionException) {\n LOG.debug(\"NotServingRegionException; \" + t.getMessage());\n return t;\n }\n if (msg == null) {\n LOG.error(\"\", RemoteExceptionHandler.checkThrowable(t));\n } else {\n LOG.error(msg, RemoteExceptionHandler.checkThrowable(t));\n }\n if (!checkOOME(t)) {\n checkFileSystem();\n }\n return t;\n }\n\n /*\n * @param t\n *\n * @return Make <code>t</code> an IOE if it isn't already.\n */\n private IOException convertThrowableToIOE(final Throwable t) {\n return convertThrowableToIOE(t, null);\n }\n\n /*\n * @param t\n *\n * @param msg Message to put in new IOE if passed <code>t</code> is not an IOE\n *\n * @return Make <code>t</code> an IOE if it isn't already.\n */\n private IOException convertThrowableToIOE(final Throwable t, final String msg) {\n return (t instanceof IOException ? (IOException) t : msg == null\n || msg.length() == 0 ? new IOException(t) : new IOException(msg, t));\n }\n\n /*\n * Check if an OOME and, if so, abort immediately to avoid creating more objects.\n *\n * @param e\n *\n * @return True if we OOME'd and are aborting.\n */\n public boolean checkOOME(final Throwable e) {\n boolean stop = false;\n try {\n if (e instanceof OutOfMemoryError\n || (e.getCause() != null && e.getCause() instanceof OutOfMemoryError)\n || (e.getMessage() != null && e.getMessage().contains(\n \"java.lang.OutOfMemoryError\"))) {\n stop = true;\n LOG.fatal(\n \"Run out of memory; HRegionServer will abort itself immediately\", e);\n }\n } finally {\n if (stop) {\n Runtime.getRuntime().halt(1);\n }\n }\n return stop;\n }\n\n /**\n * Checks to see if the file system is still accessible. If not, sets\n * abortRequested and stopRequested\n *\n * @return false if file system is not available\n */\n public boolean checkFileSystem() {\n if (this.fsOk && this.fs != null) {\n try {\n FSUtils.checkFileSystemAvailable(this.fs);\n } catch (IOException e) {\n abort(\"File System not available\", e);\n this.fsOk = false;\n }\n }\n return this.fsOk;\n }\n\n /*\n * Inner class that runs on a long period checking if regions need compaction.\n */\n private static class CompactionChecker extends Chore {\n private final HRegionServer instance;\n private final int majorCompactPriority;\n private final static int DEFAULT_PRIORITY = Integer.MAX_VALUE;\n\n CompactionChecker(final HRegionServer h, final int sleepTime,\n final Stoppable stopper) {\n super(\"CompactionChecker\", sleepTime, h);\n this.instance = h;\n LOG.info(\"Runs every \" + StringUtils.formatTime(sleepTime));\n\n /* MajorCompactPriority is configurable.\n * If not set, the compaction will use default priority.\n */\n this.majorCompactPriority = this.instance.conf.\n getInt(\"hbase.regionserver.compactionChecker.majorCompactPriority\",\n DEFAULT_PRIORITY);\n }\n\n @Override\n protected void chore() {\n for (HRegion r : this.instance.onlineRegions.values()) {\n if (r == null)\n continue;\n for (Store s : r.getStores().values()) {\n try {\n if (s.needsCompaction()) {\n // Queue a compaction. Will recognize if major is needed.\n this.instance.compactSplitThread.requestCompaction(r, s,\n getName() + \" requests compaction\");\n } else if (s.isMajorCompaction()) {\n if (majorCompactPriority == DEFAULT_PRIORITY ||\n majorCompactPriority > r.getCompactPriority()) {\n this.instance.compactSplitThread.requestCompaction(r, s,\n getName() + \" requests major compaction; use default priority\");\n } else {\n this.instance.compactSplitThread.requestCompaction(r, s,\n getName() + \" requests major compaction; use configured priority\",\n this.majorCompactPriority);\n }\n }\n } catch (IOException e) {\n LOG.warn(\"Failed major compaction check on \" + r, e);\n }\n }\n }\n }\n }\n\n /**\n * Report the status of the server. A server is online once all the startup is\n * completed (setting up filesystem, starting service threads, etc.). This\n * method is designed mostly to be useful in tests.\n *\n * @return true if online, false if not.\n */\n public boolean isOnline() {\n return isOnline;\n }\n\n /**\n * Setup WAL log and replication if enabled.\n * Replication setup is done in here because it wants to be hooked up to WAL.\n * @return A WAL instance.\n * @throws IOException\n */\n private HLog setupWALAndReplication() throws IOException {\n final Path oldLogDir = new Path(rootDir, HConstants.HREGION_OLDLOGDIR_NAME);\n Path logdir = new Path(rootDir,\n HLog.getHLogDirectoryName(this.serverNameFromMasterPOV.toString()));\n if (LOG.isDebugEnabled()) LOG.debug(\"logdir=\" + logdir);\n if (this.fs.exists(logdir)) {\n throw new RegionServerRunningException(\"Region server has already \" +\n \"created directory at \" + this.serverNameFromMasterPOV.toString());\n }\n\n // Instantiate replication manager if replication enabled. Pass it the\n // log directories.\n createNewReplicationInstance(conf, this, this.fs, logdir, oldLogDir);\n return instantiateHLog(logdir, oldLogDir);\n }\n\n /**\n * Called by {@link #setupWALAndReplication()} creating WAL instance.\n * @param logdir\n * @param oldLogDir\n * @return WAL instance.\n * @throws IOException\n */\n protected HLog instantiateHLog(Path logdir, Path oldLogDir) throws IOException {\n return new HLog(this.fs.getBackingFs(), logdir, oldLogDir, this.conf,\n getWALActionListeners(), this.serverNameFromMasterPOV.toString());\n }\n\n /**\n * Called by {@link #instantiateHLog(Path, Path)} setting up WAL instance.\n * Add any {@link WALActionsListener}s you want inserted before WAL startup.\n * @return List of WALActionsListener that will be passed in to\n * {@link HLog} on construction.\n */\n protected List<WALActionsListener> getWALActionListeners() {\n List<WALActionsListener> listeners = new ArrayList<WALActionsListener>();\n // Log roller.\n this.hlogRoller = new LogRoller(this, this);\n listeners.add(this.hlogRoller);\n if (this.replicationSourceHandler != null &&\n this.replicationSourceHandler.getWALActionsListener() != null) {\n // Replication handler is an implementation of WALActionsListener.\n listeners.add(this.replicationSourceHandler.getWALActionsListener());\n }\n return listeners;\n }\n\n protected LogRoller getLogRoller() {\n return hlogRoller;\n }\n\n /*\n * @param interval Interval since last time metrics were called.\n */\n protected void doMetrics() {\n try {\n metrics();\n } catch (Throwable e) {\n LOG.warn(\"Failed metrics\", e);\n }\n }\n\n protected void metrics() {\n this.metrics.regions.set(this.onlineRegions.size());\n this.metrics.incrementRequests(this.requestCount.get());\n this.metrics.requests.intervalHeartBeat();\n // Is this too expensive every three seconds getting a lock on onlineRegions\n // and then per store carried? Can I make metrics be sloppier and avoid\n // the synchronizations?\n int stores = 0;\n int storefiles = 0;\n long memstoreSize = 0;\n int readRequestsCount = 0;\n int writeRequestsCount = 0;\n long storefileIndexSize = 0;\n HDFSBlocksDistribution hdfsBlocksDistribution =\n new HDFSBlocksDistribution();\n long totalStaticIndexSize = 0;\n long totalStaticBloomSize = 0;\n long numPutsWithoutWAL = 0;\n long dataInMemoryWithoutWAL = 0;\n\n // Note that this is a map of Doubles instead of Longs. This is because we\n // do effective integer division, which would perhaps truncate more than it\n // should because we do it only on one part of our sum at a time. Rather\n // than dividing at the end, where it is difficult to know the proper\n // factor, everything is exact then truncated.\n final Map<String, MutableDouble> tempVals =\n new HashMap<String, MutableDouble>();\n\n for (Map.Entry<String, HRegion> e : this.onlineRegions.entrySet()) {\n HRegion r = e.getValue();\n memstoreSize += r.memstoreSize.get();\n numPutsWithoutWAL += r.numPutsWithoutWAL.get();\n dataInMemoryWithoutWAL += r.dataInMemoryWithoutWAL.get();\n readRequestsCount += r.readRequestsCount.get();\n writeRequestsCount += r.writeRequestsCount.get();\n synchronized (r.stores) {\n stores += r.stores.size();\n for (Map.Entry<byte[], Store> ee : r.stores.entrySet()) {\n final Store store = ee.getValue();\n final SchemaMetrics schemaMetrics = store.getSchemaMetrics();\n\n {\n long tmpStorefiles = store.getStorefilesCount();\n schemaMetrics.accumulateStoreMetric(tempVals,\n StoreMetricType.STORE_FILE_COUNT, tmpStorefiles);\n storefiles += tmpStorefiles;\n }\n\n\n {\n long tmpStorefileIndexSize = store.getStorefilesIndexSize();\n schemaMetrics.accumulateStoreMetric(tempVals,\n StoreMetricType.STORE_FILE_INDEX_SIZE,\n (long) (tmpStorefileIndexSize / (1024.0 * 1024)));\n storefileIndexSize += tmpStorefileIndexSize;\n }\n\n {\n long tmpStorefilesSize = store.getStorefilesSize();\n schemaMetrics.accumulateStoreMetric(tempVals,\n StoreMetricType.STORE_FILE_SIZE_MB,\n (long) (tmpStorefilesSize / (1024.0 * 1024)));\n }\n\n {\n long tmpStaticBloomSize = store.getTotalStaticBloomSize();\n schemaMetrics.accumulateStoreMetric(tempVals,\n StoreMetricType.STATIC_BLOOM_SIZE_KB,\n (long) (tmpStaticBloomSize / 1024.0));\n totalStaticBloomSize += tmpStaticBloomSize;\n }\n\n {\n long tmpStaticIndexSize = store.getTotalStaticIndexSize();\n schemaMetrics.accumulateStoreMetric(tempVals,\n StoreMetricType.STATIC_INDEX_SIZE_KB,\n (long) (tmpStaticIndexSize / 1024.0));\n totalStaticIndexSize += tmpStaticIndexSize;\n }\n\n schemaMetrics.accumulateStoreMetric(tempVals,\n StoreMetricType.MEMSTORE_SIZE_MB,\n (long) (store.getMemStoreSize() / (1024.0 * 1024)));\n }\n }\n\n hdfsBlocksDistribution.add(r.getHDFSBlocksDistribution());\n }\n\n for (Entry<String, MutableDouble> e : tempVals.entrySet()) {\n RegionMetricsStorage.setNumericMetric(e.getKey(), e.getValue().longValue());\n }\n\n this.metrics.stores.set(stores);\n this.metrics.storefiles.set(storefiles);\n this.metrics.memstoreSizeMB.set((int) (memstoreSize / (1024 * 1024)));\n this.metrics.mbInMemoryWithoutWAL.set((int) (dataInMemoryWithoutWAL / (1024 * 1024)));\n this.metrics.numPutsWithoutWAL.set(numPutsWithoutWAL);\n this.metrics.storefileIndexSizeMB.set(\n (int) (storefileIndexSize / (1024 * 1024)));\n this.metrics.rootIndexSizeKB.set(\n (int) (storefileIndexSize / 1024));\n this.metrics.totalStaticIndexSizeKB.set(\n (int) (totalStaticIndexSize / 1024));\n this.metrics.totalStaticBloomSizeKB.set(\n (int) (totalStaticBloomSize / 1024));\n this.metrics.readRequestsCount.set(readRequestsCount);\n this.metrics.writeRequestsCount.set(writeRequestsCount);\n this.metrics.compactionQueueSize.set(compactSplitThread\n .getCompactionQueueSize());\n this.metrics.flushQueueSize.set(cacheFlusher\n .getFlushQueueSize());\n\n BlockCache blockCache = cacheConfig.getBlockCache();\n if (blockCache != null) {\n this.metrics.blockCacheCount.set(blockCache.size());\n this.metrics.blockCacheFree.set(blockCache.getFreeSize());\n this.metrics.blockCacheSize.set(blockCache.getCurrentSize());\n CacheStats cacheStats = blockCache.getStats();\n this.metrics.blockCacheHitCount.set(cacheStats.getHitCount());\n this.metrics.blockCacheMissCount.set(cacheStats.getMissCount());\n this.metrics.blockCacheEvictedCount.set(blockCache.getEvictedCount());\n double ratio = blockCache.getStats().getHitRatio();\n int percent = (int) (ratio * 100);\n this.metrics.blockCacheHitRatio.set(percent);\n ratio = blockCache.getStats().getHitCachingRatio();\n percent = (int) (ratio * 100);\n this.metrics.blockCacheHitCachingRatio.set(percent);\n // past N period block cache hit / hit caching ratios\n cacheStats.rollMetricsPeriod();\n ratio = cacheStats.getHitRatioPastNPeriods();\n percent = (int) (ratio * 100);\n this.metrics.blockCacheHitRatioPastNPeriods.set(percent);\n ratio = cacheStats.getHitCachingRatioPastNPeriods();\n percent = (int) (ratio * 100);\n this.metrics.blockCacheHitCachingRatioPastNPeriods.set(percent);\n }\n float localityIndex = hdfsBlocksDistribution.getBlockLocalityIndex(\n getServerName().getHostname());\n int percent = (int) (localityIndex * 100);\n this.metrics.hdfsBlocksLocalityIndex.set(percent);\n\n }\n\n /**\n * @return Region server metrics instance.\n */\n public RegionServerMetrics getMetrics() {\n return this.metrics;\n }\n\n /**\n * @return Master address tracker instance.\n */\n public MasterAddressTracker getMasterAddressManager() {\n return this.masterAddressManager;\n }\n\n /*\n * Start maintanence Threads, Server, Worker and lease checker threads.\n * Install an UncaughtExceptionHandler that calls abort of RegionServer if we\n * get an unhandled exception. We cannot set the handler on all threads.\n * Server's internal Listener thread is off limits. For Server, if an OOME, it\n * waits a while then retries. Meantime, a flush or a compaction that tries to\n * run should trigger same critical condition and the shutdown will run. On\n * its way out, this server will shut down Server. Leases are sort of\n * inbetween. It has an internal thread that while it inherits from Chore, it\n * keeps its own internal stop mechanism so needs to be stopped by this\n * hosting server. Worker logs the exception and exits.\n */\n private void startServiceThreads() throws IOException {\n String n = Thread.currentThread().getName();\n UncaughtExceptionHandler handler = new UncaughtExceptionHandler() {\n public void uncaughtException(Thread t, Throwable e) {\n abort(\"Uncaught exception in service thread \" + t.getName(), e);\n }\n };\n\n // Start executor services\n this.service = new ExecutorService(getServerName().toString());\n this.service.startExecutorService(ExecutorType.RS_OPEN_REGION,\n conf.getInt(\"hbase.regionserver.executor.openregion.threads\", 3));\n this.service.startExecutorService(ExecutorType.RS_OPEN_ROOT,\n conf.getInt(\"hbase.regionserver.executor.openroot.threads\", 1));\n this.service.startExecutorService(ExecutorType.RS_OPEN_META,\n conf.getInt(\"hbase.regionserver.executor.openmeta.threads\", 1));\n this.service.startExecutorService(ExecutorType.RS_CLOSE_REGION,\n conf.getInt(\"hbase.regionserver.executor.closeregion.threads\", 3));\n this.service.startExecutorService(ExecutorType.RS_CLOSE_ROOT,\n conf.getInt(\"hbase.regionserver.executor.closeroot.threads\", 1));\n this.service.startExecutorService(ExecutorType.RS_CLOSE_META,\n conf.getInt(\"hbase.regionserver.executor.closemeta.threads\", 1));\n\n Threads.setDaemonThreadRunning(this.hlogRoller.getThread(), n + \".logRoller\", handler);\n Threads.setDaemonThreadRunning(this.cacheFlusher.getThread(), n + \".cacheFlusher\",\n handler);\n Threads.setDaemonThreadRunning(this.compactionChecker.getThread(), n +\n \".compactionChecker\", handler);\n\n // Leases is not a Thread. Internally it runs a daemon thread. If it gets\n // an unhandled exception, it will just exit.\n this.leases.setName(n + \".leaseChecker\");\n this.leases.start();\n\n // Put up the webui. Webui may come up on port other than configured if\n // that port is occupied. Adjust serverInfo if this is the case.\n this.webuiport = putUpWebUI();\n\n if (this.replicationSourceHandler == this.replicationSinkHandler &&\n this.replicationSourceHandler != null) {\n this.replicationSourceHandler.startReplicationService();\n } else if (this.replicationSourceHandler != null) {\n this.replicationSourceHandler.startReplicationService();\n } else if (this.replicationSinkHandler != null) {\n this.replicationSinkHandler.startReplicationService();\n }\n\n // Start Server. This service is like leases in that it internally runs\n // a thread.\n this.rpcServer.start();\n\n // Create the log splitting worker and start it\n this.splitLogWorker = new SplitLogWorker(this.zooKeeper,\n this.getConfiguration(), this.getServerName().toString());\n splitLogWorker.start();\n }\n\n /**\n * Puts up the webui.\n * @return Returns final port -- maybe different from what we started with.\n * @throws IOException\n */\n private int putUpWebUI() throws IOException {\n int port = this.conf.getInt(\"hbase.regionserver.info.port\", 60030);\n // -1 is for disabling info server\n if (port < 0) return port;\n String addr = this.conf.get(\"hbase.regionserver.info.bindAddress\", \"0.0.0.0\");\n // check if auto port bind enabled\n boolean auto = this.conf.getBoolean(HConstants.REGIONSERVER_INFO_PORT_AUTO,\n false);\n while (true) {\n try {\n this.infoServer = new InfoServer(\"regionserver\", addr, port, false, this.conf);\n this.infoServer.addServlet(\"status\", \"/rs-status\", RSStatusServlet.class);\n this.infoServer.addServlet(\"dump\", \"/dump\", RSDumpServlet.class);\n this.infoServer.setAttribute(REGIONSERVER, this);\n this.infoServer.setAttribute(REGIONSERVER_CONF, conf);\n this.infoServer.start();\n break;\n } catch (BindException e) {\n if (!auto) {\n // auto bind disabled throw BindException\n throw e;\n }\n // auto bind enabled, try to use another port\n LOG.info(\"Failed binding http info server to port: \" + port);\n port++;\n }\n }\n return port;\n }\n\n /*\n * Verify that server is healthy\n */\n private boolean isHealthy() {\n if (!fsOk) {\n // File system problem\n return false;\n }\n // Verify that all threads are alive\n if (!(leases.isAlive()\n && cacheFlusher.isAlive() && hlogRoller.isAlive()\n && this.compactionChecker.isAlive())) {\n stop(\"One or more threads are no longer alive -- stop\");\n return false;\n }\n return true;\n }\n\n @Override\n public HLog getWAL() {\n return this.hlog;\n }\n\n @Override\n public CatalogTracker getCatalogTracker() {\n return this.catalogTracker;\n }\n\n @Override\n public void stop(final String msg) {\n this.stopped = true;\n LOG.info(\"STOPPED: \" + msg);\n // Wakes run() if it is sleeping\n sleeper.skipSleepCycle();\n }\n\n public void waitForServerOnline(){\n while (!isOnline() && !isStopped()){\n sleeper.sleep();\n }\n }\n\n @Override\n public void postOpenDeployTasks(final HRegion r, final CatalogTracker ct,\n final boolean daughter)\n throws KeeperException, IOException {\n checkOpen();\n LOG.info(\"Post open deploy tasks for region=\" + r.getRegionNameAsString() +\n \", daughter=\" + daughter);\n // Do checks to see if we need to compact (references or too many files)\n for (Store s : r.getStores().values()) {\n if (s.hasReferences() || s.needsCompaction()) {\n getCompactionRequester().requestCompaction(r, s, \"Opening Region\");\n }\n }\n // Update ZK, ROOT or META\n if (r.getRegionInfo().isRootRegion()) {\n RootLocationEditor.setRootLocation(getZooKeeper(),\n this.serverNameFromMasterPOV);\n } else if (r.getRegionInfo().isMetaRegion()) {\n MetaEditor.updateMetaLocation(ct, r.getRegionInfo(),\n this.serverNameFromMasterPOV);\n } else {\n if (daughter) {\n // If daughter of a split, update whole row, not just location.\n MetaEditor.addDaughter(ct, r.getRegionInfo(),\n this.serverNameFromMasterPOV);\n } else {\n MetaEditor.updateRegionLocation(ct, r.getRegionInfo(),\n this.serverNameFromMasterPOV);\n }\n }\n LOG.info(\"Done with post open deploy task for region=\" +\n r.getRegionNameAsString() + \", daughter=\" + daughter);\n\n }\n\n /**\n * Return a reference to the metrics instance used for counting RPC calls.\n * @return Metrics instance.\n */\n public HBaseRpcMetrics getRpcMetrics() {\n return rpcServer.getRpcMetrics();\n }\n\n @Override\n public RpcServer getRpcServer() {\n return rpcServer;\n }\n\n /**\n * Cause the server to exit without closing the regions it is serving, the log\n * it is using and without notifying the master. Used unit testing and on\n * catastrophic events such as HDFS is yanked out from under hbase or we OOME.\n *\n * @param reason\n * the reason we are aborting\n * @param cause\n * the exception that caused the abort, or null\n */\n public void abort(String reason, Throwable cause) {\n String msg = \"ABORTING region server \" + this + \": \" + reason;\n if (cause != null) {\n LOG.fatal(msg, cause);\n } else {\n LOG.fatal(msg);\n }\n this.abortRequested = true;\n this.reservedSpace.clear();\n // HBASE-4014: show list of coprocessors that were loaded to help debug\n // regionserver crashes.Note that we're implicitly using\n // java.util.HashSet's toString() method to print the coprocessor names.\n LOG.fatal(\"RegionServer abort: loaded coprocessors are: \" +\n CoprocessorHost.getLoadedCoprocessors());\n if (this.metrics != null) {\n LOG.info(\"Dump of metrics: \" + this.metrics);\n }\n // Do our best to report our abort to the master, but this may not work\n try {\n if (cause != null) {\n msg += \"\\nCause:\\n\" + StringUtils.stringifyException(cause);\n }\n if (hbaseMaster != null) {\n hbaseMaster.reportRSFatalError(\n this.serverNameFromMasterPOV.getVersionedBytes(), msg);\n }\n } catch (Throwable t) {\n LOG.warn(\"Unable to report fatal error to master\", t);\n }\n stop(reason);\n }\n\n /**\n * @see HRegionServer#abort(String, Throwable)\n */\n public void abort(String reason) {\n abort(reason, null);\n }\n\n public boolean isAborted() {\n return this.abortRequested;\n }\n\n /*\n * Simulate a kill -9 of this server. Exits w/o closing regions or cleaninup\n * logs but it does close socket in case want to bring up server on old\n * hostname+port immediately.\n */\n protected void kill() {\n this.killed = true;\n abort(\"Simulated kill\");\n }\n\n /**\n * Wait on all threads to finish. Presumption is that all closes and stops\n * have already been called.\n */\n protected void join() {\n Threads.shutdown(this.compactionChecker.getThread());\n Threads.shutdown(this.cacheFlusher.getThread());\n if (this.hlogRoller != null) {\n Threads.shutdown(this.hlogRoller.getThread());\n }\n if (this.compactSplitThread != null) {\n this.compactSplitThread.join();\n }\n if (this.service != null) this.service.shutdown();\n if (this.replicationSourceHandler != null &&\n this.replicationSourceHandler == this.replicationSinkHandler) {\n this.replicationSourceHandler.stopReplicationService();\n } else if (this.replicationSourceHandler != null) {\n this.replicationSourceHandler.stopReplicationService();\n } else if (this.replicationSinkHandler != null) {\n this.replicationSinkHandler.stopReplicationService();\n }\n }\n\n /**\n * @return Return the object that implements the replication\n * source service.\n */\n ReplicationSourceService getReplicationSourceService() {\n return replicationSourceHandler;\n }\n\n /**\n * @return Return the object that implements the replication\n * sink service.\n */\n ReplicationSinkService getReplicationSinkService() {\n return replicationSinkHandler;\n }\n\n /**\n * Get the current master from ZooKeeper and open the RPC connection to it.\n *\n * Method will block until a master is available. You can break from this\n * block by requesting the server stop.\n *\n * @return master + port, or null if server has been stopped\n */\n private ServerName getMaster() {\n ServerName masterServerName = null;\n long previousLogTime = 0;\n HMasterRegionInterface master = null;\n InetSocketAddress masterIsa = null;\n while (keepLooping() && master == null) {\n masterServerName = this.masterAddressManager.getMasterAddress();\n if (masterServerName == null) {\n if (!keepLooping()) {\n // give up with no connection.\n LOG.debug(\"No master found and cluster is stopped; bailing out\");\n return null;\n }\n LOG.debug(\"No master found; retry\");\n previousLogTime = System.currentTimeMillis();\n\n sleeper.sleep();\n continue;\n }\n\n masterIsa =\n new InetSocketAddress(masterServerName.getHostname(), masterServerName.getPort());\n\n LOG.info(\"Attempting connect to Master server at \" +\n this.masterAddressManager.getMasterAddress());\n try {\n // Do initial RPC setup. The final argument indicates that the RPC\n // should retry indefinitely.\n master = (HMasterRegionInterface) HBaseRPC.waitForProxy(\n HMasterRegionInterface.class, HMasterRegionInterface.VERSION,\n masterIsa, this.conf, -1,\n this.rpcTimeout, this.rpcTimeout);\n } catch (IOException e) {\n e = e instanceof RemoteException ?\n ((RemoteException)e).unwrapRemoteException() : e;\n if (e instanceof ServerNotRunningYetException) {\n if (System.currentTimeMillis() > (previousLogTime+1000)){\n LOG.info(\"Master isn't available yet, retrying\");\n previousLogTime = System.currentTimeMillis();\n }\n } else {\n if (System.currentTimeMillis() > (previousLogTime + 1000)) {\n LOG.warn(\"Unable to connect to master. Retrying. Error was:\", e);\n previousLogTime = System.currentTimeMillis();\n }\n }\n try {\n Thread.sleep(200);\n } catch (InterruptedException ignored) {\n }\n }\n }\n LOG.info(\"Connected to master at \" + masterIsa);\n this.hbaseMaster = master;\n return masterServerName;\n }\n\n /**\n * @return True if we should break loop because cluster is going down or\n * this server has been stopped or hdfs has gone bad.\n */\n private boolean keepLooping() {\n return !this.stopped && isClusterUp();\n }\n\n /*\n * Let the master know we're here Run initialization using parameters passed\n * us by the master.\n * @return A Map of key/value configurations we got from the Master else\n * null if we failed to register.\n * @throws IOException\n */\n private MapWritable reportForDuty() throws IOException {\n MapWritable result = null;\n ServerName masterServerName = getMaster();\n if (masterServerName == null) return result;\n try {\n this.requestCount.set(0);\n LOG.info(\"Telling master at \" + masterServerName + \" that we are up \" +\n \"with port=\" + this.isa.getPort() + \", startcode=\" + this.startcode);\n long now = EnvironmentEdgeManager.currentTimeMillis();\n int port = this.isa.getPort();\n result = this.hbaseMaster.regionServerStartup(port, this.startcode, now);\n } catch (RemoteException e) {\n IOException ioe = e.unwrapRemoteException();\n if (ioe instanceof ClockOutOfSyncException) {\n LOG.fatal(\"Master rejected startup because clock is out of sync\", ioe);\n // Re-throw IOE will cause RS to abort\n throw ioe;\n } else {\n LOG.warn(\"remote error telling master we are up\", e);\n }\n } catch (IOException e) {\n LOG.warn(\"error telling master we are up\", e);\n }\n return result;\n }\n\n /**\n * Closes all regions. Called on our way out.\n * Assumes that its not possible for new regions to be added to onlineRegions\n * while this method runs.\n */\n protected void closeAllRegions(final boolean abort) {\n closeUserRegions(abort);\n closeMetaTableRegions(abort);\n }\n\n /**\n * Close root and meta regions if we carry them\n * @param abort Whether we're running an abort.\n */\n void closeMetaTableRegions(final boolean abort) {\n HRegion meta = null;\n HRegion root = null;\n this.lock.writeLock().lock();\n try {\n for (Map.Entry<String, HRegion> e: onlineRegions.entrySet()) {\n HRegionInfo hri = e.getValue().getRegionInfo();\n if (hri.isRootRegion()) {\n root = e.getValue();\n } else if (hri.isMetaRegion()) {\n meta = e.getValue();\n }\n if (meta != null && root != null) break;\n }\n } finally {\n this.lock.writeLock().unlock();\n }\n if (meta != null) closeRegion(meta.getRegionInfo(), abort, false);\n if (root != null) closeRegion(root.getRegionInfo(), abort, false);\n }\n\n /**\n * Schedule closes on all user regions.\n * Should be safe calling multiple times because it wont' close regions\n * that are already closed or that are closing.\n * @param abort Whether we're running an abort.\n */\n void closeUserRegions(final boolean abort) {\n this.lock.writeLock().lock();\n try {\n for (Map.Entry<String, HRegion> e: this.onlineRegions.entrySet()) {\n HRegion r = e.getValue();\n if (!r.getRegionInfo().isMetaTable() && r.isAvailable()) {\n // Don't update zk with this close transition; pass false.\n closeRegion(r.getRegionInfo(), abort, false);\n }\n }\n } finally {\n this.lock.writeLock().unlock();\n }\n }\n\n @Override\n @QosPriority(priority=HConstants.HIGH_QOS)\n public HRegionInfo getRegionInfo(final byte[] regionName)\n throws NotServingRegionException, IOException {\n checkOpen();\n requestCount.incrementAndGet();\n return getRegion(regionName).getRegionInfo();\n }\n\n public Result getClosestRowBefore(final byte[] regionName, final byte[] row,\n final byte[] family) throws IOException {\n checkOpen();\n requestCount.incrementAndGet();\n try {\n // locate the region we're operating on\n HRegion region = getRegion(regionName);\n // ask the region for all the data\n\n Result r = region.getClosestRowBefore(row, family);\n return r;\n } catch (Throwable t) {\n throw convertThrowableToIOE(cleanup(t));\n }\n }\n\n /** {@inheritDoc} */\n public Result get(byte[] regionName, Get get) throws IOException {\n checkOpen();\n requestCount.incrementAndGet();\n try {\n HRegion region = getRegion(regionName);\n return region.get(get, getLockFromId(get.getLockId()));\n } catch (Throwable t) {\n throw convertThrowableToIOE(cleanup(t));\n }\n }\n\n public boolean exists(byte[] regionName, Get get) throws IOException {\n checkOpen();\n requestCount.incrementAndGet();\n try {\n HRegion region = getRegion(regionName);\n Integer lock = getLockFromId(get.getLockId());\n if (region.getCoprocessorHost() != null) {\n Boolean result = region.getCoprocessorHost().preExists(get);\n if (result != null) {\n return result.booleanValue();\n }\n }\n Result r = region.get(get, lock);\n boolean result = r != null && !r.isEmpty();\n if (region.getCoprocessorHost() != null) {\n result = region.getCoprocessorHost().postExists(get, result);\n }\n return result;\n } catch (Throwable t) {\n throw convertThrowableToIOE(cleanup(t));\n }\n }\n\n public void put(final byte[] regionName, final Put put) throws IOException {\n if (put.getRow() == null) {\n throw new IllegalArgumentException(\"update has null row\");\n }\n\n checkOpen();\n this.requestCount.incrementAndGet();\n HRegion region = getRegion(regionName);\n try {\n if (!region.getRegionInfo().isMetaTable()) {\n this.cacheFlusher.reclaimMemStoreMemory();\n }\n boolean writeToWAL = put.getWriteToWAL();\n region.put(put, getLockFromId(put.getLockId()), writeToWAL);\n } catch (Throwable t) {\n throw convertThrowableToIOE(cleanup(t));\n }\n }\n\n public int put(final byte[] regionName, final List<Put> puts)\n throws IOException {\n checkOpen();\n HRegion region = null;\n int i = 0;\n\n try {\n region = getRegion(regionName);\n if (!region.getRegionInfo().isMetaTable()) {\n this.cacheFlusher.reclaimMemStoreMemory();\n }\n\n @SuppressWarnings(\"unchecked\")\n Pair<Mutation, Integer>[] putsWithLocks = new Pair[puts.size()];\n\n for (Put p : puts) {\n Integer lock = getLockFromId(p.getLockId());\n putsWithLocks[i++] = new Pair<Mutation, Integer>(p, lock);\n }\n\n this.requestCount.addAndGet(puts.size());\n OperationStatus codes[] = region.batchMutate(putsWithLocks);\n for (i = 0; i < codes.length; i++) {\n if (codes[i].getOperationStatusCode() != OperationStatusCode.SUCCESS) {\n return i;\n }\n }\n return -1;\n } catch (Throwable t) {\n throw convertThrowableToIOE(cleanup(t));\n }\n }\n\n private boolean checkAndMutate(final byte[] regionName, final byte[] row,\n final byte[] family, final byte[] qualifier, final CompareOp compareOp,\n final WritableByteArrayComparable comparator, final Writable w,\n Integer lock) throws IOException {\n checkOpen();\n this.requestCount.incrementAndGet();\n HRegion region = getRegion(regionName);\n try {\n if (!region.getRegionInfo().isMetaTable()) {\n this.cacheFlusher.reclaimMemStoreMemory();\n }\n return region.checkAndMutate(row, family, qualifier, compareOp,\n comparator, w, lock, true);\n } catch (Throwable t) {\n throw convertThrowableToIOE(cleanup(t));\n }\n }\n\n /**\n *\n * @param regionName\n * @param row\n * @param family\n * @param qualifier\n * @param value\n * the expected value\n * @param put\n * @throws IOException\n * @return true if the new put was execute, false otherwise\n */\n public boolean checkAndPut(final byte[] regionName, final byte[] row,\n final byte[] family, final byte[] qualifier, final byte[] value,\n final Put put) throws IOException {\n checkOpen();\n if (regionName == null) {\n throw new IOException(\"Invalid arguments to checkAndPut \"\n + \"regionName is null\");\n }\n HRegion region = getRegion(regionName);\n Integer lock = getLockFromId(put.getLockId());\n WritableByteArrayComparable comparator = new BinaryComparator(value);\n if (region.getCoprocessorHost() != null) {\n Boolean result = region.getCoprocessorHost()\n .preCheckAndPut(row, family, qualifier, CompareOp.EQUAL, comparator,\n put);\n if (result != null) {\n return result.booleanValue();\n }\n }\n boolean result = checkAndMutate(regionName, row, family, qualifier,\n CompareOp.EQUAL, comparator, put,\n lock);\n if (region.getCoprocessorHost() != null) {\n result = region.getCoprocessorHost().postCheckAndPut(row, family,\n qualifier, CompareOp.EQUAL, comparator, put, result);\n }\n return result;\n }\n\n /**\n *\n * @param regionName\n * @param row\n * @param family\n * @param qualifier\n * @param compareOp\n * @param comparator\n * @param put\n * @throws IOException\n * @return true if the new put was execute, false otherwise\n */\n public boolean checkAndPut(final byte[] regionName, final byte[] row,\n final byte[] family, final byte[] qualifier, final CompareOp compareOp,\n final WritableByteArrayComparable comparator, final Put put)\n throws IOException {\n checkOpen();\n if (regionName == null) {\n throw new IOException(\"Invalid arguments to checkAndPut \"\n + \"regionName is null\");\n }\n HRegion region = getRegion(regionName);\n Integer lock = getLockFromId(put.getLockId());\n if (region.getCoprocessorHost() != null) {\n Boolean result = region.getCoprocessorHost()\n .preCheckAndPut(row, family, qualifier, compareOp, comparator, put);\n if (result != null) {\n return result.booleanValue();\n }\n }\n boolean result = checkAndMutate(regionName, row, family, qualifier,\n compareOp, comparator, put, lock);\n if (region.getCoprocessorHost() != null) {\n result = region.getCoprocessorHost().postCheckAndPut(row, family,\n qualifier, compareOp, comparator, put, result);\n }\n return result;\n }\n\n /**\n *\n * @param regionName\n * @param row\n * @param family\n * @param qualifier\n * @param value\n * the expected value\n * @param delete\n * @throws IOException\n * @return true if the new put was execute, false otherwise\n */\n public boolean checkAndDelete(final byte[] regionName, final byte[] row,\n final byte[] family, final byte[] qualifier, final byte[] value,\n final Delete delete) throws IOException {\n checkOpen();\n\n if (regionName == null) {\n throw new IOException(\"Invalid arguments to checkAndDelete \"\n + \"regionName is null\");\n }\n HRegion region = getRegion(regionName);\n Integer lock = getLockFromId(delete.getLockId());\n WritableByteArrayComparable comparator = new BinaryComparator(value);\n if (region.getCoprocessorHost() != null) {\n Boolean result = region.getCoprocessorHost().preCheckAndDelete(row,\n family, qualifier, CompareOp.EQUAL, comparator, delete);\n if (result != null) {\n return result.booleanValue();\n }\n }\n boolean result = checkAndMutate(regionName, row, family, qualifier,\n CompareOp.EQUAL, comparator, delete, lock);\n if (region.getCoprocessorHost() != null) {\n result = region.getCoprocessorHost().postCheckAndDelete(row, family,\n qualifier, CompareOp.EQUAL, comparator, delete, result);\n }\n return result;\n }\n\n @Override\n public List<String> getStoreFileList(byte[] regionName, byte[] columnFamily)\n throws IllegalArgumentException {\n return getStoreFileList(regionName, new byte[][]{columnFamily});\n }\n\n @Override\n public List<String> getStoreFileList(byte[] regionName, byte[][] columnFamilies)\n throws IllegalArgumentException {\n HRegion region = getOnlineRegion(regionName);\n if (region == null) {\n throw new IllegalArgumentException(\"No region: \" + new String(regionName)\n + \" available\");\n }\n return region.getStoreFileList(columnFamilies);\n }\n\n public List<String> getStoreFileList(byte[] regionName)\n throws IllegalArgumentException {\n HRegion region = getOnlineRegion(regionName);\n if (region == null) {\n throw new IllegalArgumentException(\"No region: \" + new String(regionName)\n + \" available\");\n }\n Set<byte[]> columnFamilies = region.getStores().keySet();\n int nCF = columnFamilies.size();\n return region.getStoreFileList(columnFamilies.toArray(new byte[nCF][]));\n }\n \n /**\n * Flushes the given region\n */\n public void flushRegion(byte[] regionName)\n throws IllegalArgumentException, IOException {\n HRegion region = getOnlineRegion(regionName);\n if (region == null) {\n throw new IllegalArgumentException(\"No region : \" + new String(regionName)\n + \" available\");\n }\n region.flushcache();\n }\n\n /**\n * Flushes the given region if lastFlushTime < ifOlderThanTS\n */\n public void flushRegion(byte[] regionName, long ifOlderThanTS)\n throws IllegalArgumentException, IOException {\n HRegion region = getOnlineRegion(regionName);\n if (region == null) {\n throw new IllegalArgumentException(\"No region : \" + new String(regionName)\n + \" available\");\n }\n if (region.getLastFlushTime() < ifOlderThanTS) region.flushcache();\n }\n\n /**\n * Gets last flush time for the given region\n * @return the last flush time for a region\n */\n public long getLastFlushTime(byte[] regionName) {\n HRegion region = getOnlineRegion(regionName);\n if (region == null) {\n throw new IllegalArgumentException(\"No region : \" + new String(regionName)\n + \" available\");\n }\n return region.getLastFlushTime();\n }\n \n /**\n *\n * @param regionName\n * @param row\n * @param family\n * @param qualifier\n * @param compareOp\n * @param comparator\n * @param delete\n * @throws IOException\n * @return true if the new put was execute, false otherwise\n */\n public boolean checkAndDelete(final byte[] regionName, final byte[] row,\n final byte[] family, final byte[] qualifier, final CompareOp compareOp,\n final WritableByteArrayComparable comparator, final Delete delete)\n throws IOException {\n checkOpen();\n\n if (regionName == null) {\n throw new IOException(\"Invalid arguments to checkAndDelete \"\n + \"regionName is null\");\n }\n HRegion region = getRegion(regionName);\n Integer lock = getLockFromId(delete.getLockId());\n if (region.getCoprocessorHost() != null) {\n Boolean result = region.getCoprocessorHost().preCheckAndDelete(row,\n family, qualifier, compareOp, comparator, delete);\n if (result != null) {\n return result.booleanValue();\n }\n }\n boolean result = checkAndMutate(regionName, row, family, qualifier,\n compareOp, comparator, delete, lock);\n if (region.getCoprocessorHost() != null) {\n result = region.getCoprocessorHost().postCheckAndDelete(row, family,\n qualifier, compareOp, comparator, delete, result);\n }\n return result;\n }\n\n //\n // remote scanner interface\n //\n\n public long openScanner(byte[] regionName, Scan scan) throws IOException {\n checkOpen();\n NullPointerException npe = null;\n if (regionName == null) {\n npe = new NullPointerException(\"regionName is null\");\n } else if (scan == null) {\n npe = new NullPointerException(\"scan is null\");\n }\n if (npe != null) {\n throw new IOException(\"Invalid arguments to openScanner\", npe);\n }\n requestCount.incrementAndGet();\n try {\n HRegion r = getRegion(regionName);\n r.checkRow(scan.getStartRow(), \"Scan\");\n r.prepareScanner(scan);\n RegionScanner s = null;\n if (r.getCoprocessorHost() != null) {\n s = r.getCoprocessorHost().preScannerOpen(scan);\n }\n if (s == null) {\n s = r.getScanner(scan);\n }\n if (r.getCoprocessorHost() != null) {\n RegionScanner savedScanner = r.getCoprocessorHost().postScannerOpen(\n scan, s);\n if (savedScanner == null) {\n LOG.warn(\"PostScannerOpen impl returning null. \"\n + \"Check the RegionObserver implementation.\");\n } else {\n s = savedScanner;\n }\n }\n return addScanner(s);\n } catch (Throwable t) {\n throw convertThrowableToIOE(cleanup(t, \"Failed openScanner\"));\n }\n }\n\n protected long addScanner(RegionScanner s) throws LeaseStillHeldException {\n long scannerId = -1L;\n scannerId = rand.nextLong();\n String scannerName = String.valueOf(scannerId);\n scanners.put(scannerName, s);\n this.leases.createLease(scannerName, new ScannerListener(scannerName));\n return scannerId;\n }\n\n public Result next(final long scannerId) throws IOException {\n Result[] res = next(scannerId, 1);\n if (res == null || res.length == 0) {\n return null;\n }\n return res[0];\n }\n\n public Result[] next(final long scannerId, int nbRows) throws IOException {\n String scannerName = String.valueOf(scannerId);\n RegionScanner s = this.scanners.get(scannerName);\n if (s == null) throw new UnknownScannerException(\"Name: \" + scannerName);\n try {\n checkOpen();\n } catch (IOException e) {\n // If checkOpen failed, server not running or filesystem gone,\n // cancel this lease; filesystem is gone or we're closing or something.\n try {\n this.leases.cancelLease(scannerName);\n } catch (LeaseException le) {\n LOG.info(\"Server shutting down and client tried to access missing scanner \" +\n scannerName);\n }\n throw e;\n }\n Leases.Lease lease = null;\n try {\n // Remove lease while its being processed in server; protects against case\n // where processing of request takes > lease expiration time.\n lease = this.leases.removeLease(scannerName);\n List<Result> results = new ArrayList<Result>(nbRows);\n long currentScanResultSize = 0;\n List<KeyValue> values = new ArrayList<KeyValue>();\n\n // Call coprocessor. Get region info from scanner.\n HRegion region = getRegion(s.getRegionInfo().getRegionName());\n if (region != null && region.getCoprocessorHost() != null) {\n Boolean bypass = region.getCoprocessorHost().preScannerNext(s,\n results, nbRows);\n if (!results.isEmpty()) {\n for (Result r : results) {\n for (KeyValue kv : r.raw()) {\n currentScanResultSize += kv.heapSize();\n }\n }\n }\n if (bypass != null) {\n return s.isFilterDone() && results.isEmpty() ? null\n : results.toArray(new Result[0]);\n }\n }\n\n for (int i = 0; i < nbRows\n && currentScanResultSize < maxScannerResultSize; i++) {\n requestCount.incrementAndGet();\n // Collect values to be returned here\n boolean moreRows = s.next(values, SchemaMetrics.METRIC_NEXTSIZE);\n if (!values.isEmpty()) {\n for (KeyValue kv : values) {\n currentScanResultSize += kv.heapSize();\n }\n results.add(new Result(values));\n }\n if (!moreRows) {\n break;\n }\n values.clear();\n }\n\n // coprocessor postNext hook\n if (region != null && region.getCoprocessorHost() != null) {\n region.getCoprocessorHost().postScannerNext(s, results, nbRows, true);\n }\n\n // If the scanner's filter - if any - is done with the scan\n // and wants to tell the client to stop the scan. This is done by passing\n // a null result.\n return s.isFilterDone() && results.isEmpty() ? null\n : results.toArray(new Result[0]);\n } catch (Throwable t) {\n if (t instanceof NotServingRegionException) {\n this.scanners.remove(scannerName);\n }\n throw convertThrowableToIOE(cleanup(t));\n } finally {\n // We're done. On way out readd the above removed lease. Adding resets\n // expiration time on lease.\n if (this.scanners.containsKey(scannerName)) {\n if (lease != null) this.leases.addLease(lease);\n }\n }\n }\n\n public void close(final long scannerId) throws IOException {\n try {\n checkOpen();\n requestCount.incrementAndGet();\n String scannerName = String.valueOf(scannerId);\n RegionScanner s = scanners.get(scannerName);\n\n HRegion region = null;\n if (s != null) {\n // call coprocessor.\n region = getRegion(s.getRegionInfo().getRegionName());\n if (region != null && region.getCoprocessorHost() != null) {\n if (region.getCoprocessorHost().preScannerClose(s)) {\n return; // bypass\n }\n }\n }\n\n s = scanners.remove(scannerName);\n if (s != null) {\n s.close();\n this.leases.cancelLease(scannerName);\n\n if (region != null && region.getCoprocessorHost() != null) {\n region.getCoprocessorHost().postScannerClose(s);\n }\n }\n } catch (Throwable t) {\n throw convertThrowableToIOE(cleanup(t));\n }\n }\n\n /**\n * Instantiated as a scanner lease. If the lease times out, the scanner is\n * closed\n */\n private class ScannerListener implements LeaseListener {\n private final String scannerName;\n\n ScannerListener(final String n) {\n this.scannerName = n;\n }\n\n public void leaseExpired() {\n RegionScanner s = scanners.remove(this.scannerName);\n if (s != null) {\n LOG.info(\"Scanner \" + this.scannerName + \" lease expired on region \"\n + s.getRegionInfo().getRegionNameAsString());\n try {\n HRegion region = getRegion(s.getRegionInfo().getRegionName());\n if (region != null && region.getCoprocessorHost() != null) {\n region.getCoprocessorHost().preScannerClose(s);\n }\n\n s.close();\n if (region != null && region.getCoprocessorHost() != null) {\n region.getCoprocessorHost().postScannerClose(s);\n }\n } catch (IOException e) {\n LOG.error(\"Closing scanner for \"\n + s.getRegionInfo().getRegionNameAsString(), e);\n }\n } else {\n LOG.info(\"Scanner \" + this.scannerName + \" lease expired\");\n }\n }\n }\n\n //\n // Methods that do the actual work for the remote API\n //\n public void delete(final byte[] regionName, final Delete delete)\n throws IOException {\n checkOpen();\n try {\n boolean writeToWAL = delete.getWriteToWAL();\n this.requestCount.incrementAndGet();\n HRegion region = getRegion(regionName);\n if (!region.getRegionInfo().isMetaTable()) {\n this.cacheFlusher.reclaimMemStoreMemory();\n }\n Integer lid = getLockFromId(delete.getLockId());\n region.delete(delete, lid, writeToWAL);\n } catch (Throwable t) {\n throw convertThrowableToIOE(cleanup(t));\n }\n }\n\n public int delete(final byte[] regionName, final List<Delete> deletes)\n throws IOException {\n checkOpen();\n // Count of Deletes processed.\n int i = 0;\n HRegion region = null;\n try {\n region = getRegion(regionName);\n if (!region.getRegionInfo().isMetaTable()) {\n this.cacheFlusher.reclaimMemStoreMemory();\n }\n int size = deletes.size();\n Integer[] locks = new Integer[size];\n for (Delete delete : deletes) {\n this.requestCount.incrementAndGet();\n locks[i] = getLockFromId(delete.getLockId());\n region.delete(delete, locks[i], delete.getWriteToWAL());\n i++;\n }\n } catch (WrongRegionException ex) {\n LOG.debug(\"Batch deletes: \" + i, ex);\n return i;\n } catch (NotServingRegionException ex) {\n return i;\n } catch (Throwable t) {\n throw convertThrowableToIOE(cleanup(t));\n }\n return -1;\n }\n\n public long lockRow(byte[] regionName, byte[] row) throws IOException {\n checkOpen();\n NullPointerException npe = null;\n if (regionName == null) {\n npe = new NullPointerException(\"regionName is null\");\n } else if (row == null) {\n npe = new NullPointerException(\"row to lock is null\");\n }\n if (npe != null) {\n IOException io = new IOException(\"Invalid arguments to lockRow\");\n io.initCause(npe);\n throw io;\n }\n requestCount.incrementAndGet();\n try {\n HRegion region = getRegion(regionName);\n Integer r = region.obtainRowLock(row);\n long lockId = addRowLock(r, region);\n LOG.debug(\"Row lock \" + lockId + \" explicitly acquired by client\");\n return lockId;\n } catch (Throwable t) {\n throw convertThrowableToIOE(cleanup(t, \"Error obtaining row lock (fsOk: \"\n + this.fsOk + \")\"));\n }\n }\n\n protected long addRowLock(Integer r, HRegion region)\n throws LeaseStillHeldException {\n long lockId = -1L;\n lockId = rand.nextLong();\n String lockName = String.valueOf(lockId);\n rowlocks.put(lockName, r);\n this.leases.createLease(lockName, new RowLockListener(lockName, region));\n return lockId;\n }\n\n /**\n * Method to get the Integer lock identifier used internally from the long\n * lock identifier used by the client.\n *\n * @param lockId\n * long row lock identifier from client\n * @return intId Integer row lock used internally in HRegion\n * @throws IOException\n * Thrown if this is not a valid client lock id.\n */\n Integer getLockFromId(long lockId) throws IOException {\n if (lockId == -1L) {\n return null;\n }\n String lockName = String.valueOf(lockId);\n Integer rl = rowlocks.get(lockName);\n if (rl == null) {\n throw new UnknownRowLockException(\"Invalid row lock\");\n }\n this.leases.renewLease(lockName);\n return rl;\n }\n\n @Override\n @QosPriority(priority=HConstants.HIGH_QOS)\n public void unlockRow(byte[] regionName, long lockId) throws IOException {\n checkOpen();\n NullPointerException npe = null;\n if (regionName == null) {\n npe = new NullPointerException(\"regionName is null\");\n } else if (lockId == -1L) {\n npe = new NullPointerException(\"lockId is null\");\n }\n if (npe != null) {\n IOException io = new IOException(\"Invalid arguments to unlockRow\");\n io.initCause(npe);\n throw io;\n }\n requestCount.incrementAndGet();\n try {\n HRegion region = getRegion(regionName);\n String lockName = String.valueOf(lockId);\n Integer r = rowlocks.remove(lockName);\n if (r == null) {\n throw new UnknownRowLockException(lockName);\n }\n region.releaseRowLock(r);\n this.leases.cancelLease(lockName);\n LOG.debug(\"Row lock \" + lockId\n + \" has been explicitly released by client\");\n } catch (Throwable t) {\n throw convertThrowableToIOE(cleanup(t));\n }\n }\n\n /**\n * Atomically bulk load several HFiles into an open region\n * @return true if successful, false is failed but recoverably (no action)\n * @throws IOException if failed unrecoverably\n */\n @Override\n public boolean bulkLoadHFiles(List<Pair<byte[], String>> familyPaths,\n byte[] regionName) throws IOException {\n checkOpen();\n HRegion region = getRegion(regionName);\n boolean bypass = false;\n if (region.getCoprocessorHost() != null) {\n bypass = region.getCoprocessorHost().preBulkLoadHFile(familyPaths);\n }\n boolean loaded = false;\n if (!bypass) {\n loaded = region.bulkLoadHFiles(familyPaths);\n }\n if (region.getCoprocessorHost() != null) {\n loaded = region.getCoprocessorHost().postBulkLoadHFile(familyPaths, loaded);\n }\n return loaded;\n }\n\n Map<String, Integer> rowlocks = new ConcurrentHashMap<String, Integer>();\n\n /**\n * Instantiated as a row lock lease. If the lease times out, the row lock is\n * released\n */\n private class RowLockListener implements LeaseListener {\n private final String lockName;\n private final HRegion region;\n\n RowLockListener(final String lockName, final HRegion region) {\n this.lockName = lockName;\n this.region = region;\n }\n\n public void leaseExpired() {\n LOG.info(\"Row Lock \" + this.lockName + \" lease expired\");\n Integer r = rowlocks.remove(this.lockName);\n if (r != null) {\n region.releaseRowLock(r);\n }\n }\n }\n\n // Region open/close direct RPCs\n\n @Override\n @QosPriority(priority=HConstants.HIGH_QOS)\n public RegionOpeningState openRegion(HRegionInfo region)\n throws IOException {\n return openRegion(region, -1);\n }\n\n @Override\n @QosPriority(priority = HConstants.HIGH_QOS)\n public RegionOpeningState openRegion(HRegionInfo region, int versionOfOfflineNode)\n throws IOException {\n return openRegion(region, versionOfOfflineNode, null);\n }\n\n private RegionOpeningState openRegion(HRegionInfo region, int versionOfOfflineNode,\n Map<String, HTableDescriptor> htds) throws IOException {\n checkOpen();\n checkIfRegionInTransition(region, OPEN);\n HRegion onlineRegion = this.getFromOnlineRegions(region.getEncodedName());\n if (null != onlineRegion) {\n // See HBASE-5094. Cross check with META if still this RS is owning the\n // region.\n Pair<HRegionInfo, ServerName> p = MetaReader.getRegion(\n this.catalogTracker, region.getRegionName());\n if (this.getServerName().equals(p.getSecond())) {\n LOG.warn(\"Attempted open of \" + region.getEncodedName()\n + \" but already online on this server\");\n return RegionOpeningState.ALREADY_OPENED;\n } else {\n LOG.warn(\"The region \" + region.getEncodedName()\n + \" is online on this server but META does not have this server.\");\n this.removeFromOnlineRegions(region.getEncodedName());\n }\n }\n LOG.info(\"Received request to open region: \" +\n region.getRegionNameAsString());\n HTableDescriptor htd = null;\n if (htds == null) {\n htd = this.tableDescriptors.get(region.getTableName());\n } else {\n htd = htds.get(region.getTableNameAsString());\n if (htd == null) {\n htd = this.tableDescriptors.get(region.getTableName());\n htds.put(region.getRegionNameAsString(), htd);\n }\n }\n this.regionsInTransitionInRS.putIfAbsent(region.getEncodedNameAsBytes(),\n true);\n // Need to pass the expected version in the constructor.\n if (region.isRootRegion()) {\n this.service.submit(new OpenRootHandler(this, this, region, htd,\n versionOfOfflineNode));\n } else if (region.isMetaRegion()) {\n this.service.submit(new OpenMetaHandler(this, this, region, htd,\n versionOfOfflineNode));\n } else {\n this.service.submit(new OpenRegionHandler(this, this, region, htd,\n versionOfOfflineNode));\n }\n return RegionOpeningState.OPENED;\n }\n\n private void checkIfRegionInTransition(HRegionInfo region,\n String currentAction) throws RegionAlreadyInTransitionException {\n byte[] encodedName = region.getEncodedNameAsBytes();\n if (this.regionsInTransitionInRS.containsKey(encodedName)) {\n boolean openAction = this.regionsInTransitionInRS.get(encodedName);\n // The below exception message will be used in master.\n throw new RegionAlreadyInTransitionException(\"Received:\" + currentAction +\n \" for the region:\" + region.getRegionNameAsString() +\n \" ,which we are already trying to \" +\n (openAction ? OPEN : CLOSE)+ \".\");\n }\n }\n\n @Override\n @QosPriority(priority=HConstants.HIGH_QOS)\n public void openRegions(List<HRegionInfo> regions)\n throws IOException {\n checkOpen();\n LOG.info(\"Received request to open \" + regions.size() + \" region(s)\");\n Map<String, HTableDescriptor> htds = new HashMap<String, HTableDescriptor>(regions.size());\n for (HRegionInfo region : regions) openRegion(region, -1, htds);\n }\n\n @Override\n @QosPriority(priority=HConstants.HIGH_QOS)\n public boolean closeRegion(HRegionInfo region)\n throws IOException {\n return closeRegion(region, true, -1);\n }\n\n @Override\n @QosPriority(priority=HConstants.HIGH_QOS)\n public boolean closeRegion(final HRegionInfo region,\n final int versionOfClosingNode)\n throws IOException {\n return closeRegion(region, true, versionOfClosingNode);\n }\n\n @Override\n @QosPriority(priority=HConstants.HIGH_QOS)\n public boolean closeRegion(HRegionInfo region, final boolean zk)\n throws IOException {\n return closeRegion(region, zk, -1);\n }\n\n @QosPriority(priority=HConstants.HIGH_QOS)\n protected boolean closeRegion(HRegionInfo region, final boolean zk,\n final int versionOfClosingNode)\n throws IOException {\n checkOpen();\n LOG.info(\"Received close region: \" + region.getRegionNameAsString() +\n \". Version of ZK closing node:\" + versionOfClosingNode);\n boolean hasit = this.onlineRegions.containsKey(region.getEncodedName());\n if (!hasit) {\n LOG.warn(\"Received close for region we are not serving; \" +\n region.getEncodedName());\n throw new NotServingRegionException(\"Received close for \"\n + region.getRegionNameAsString() + \" but we are not serving it\");\n }\n checkIfRegionInTransition(region, CLOSE);\n return closeRegion(region, false, zk, versionOfClosingNode);\n }\n\n @Override\n @QosPriority(priority=HConstants.HIGH_QOS)\n public boolean closeRegion(byte[] encodedRegionName, boolean zk)\n throws IOException {\n return closeRegion(encodedRegionName, false, zk);\n }\n\n /**\n * @param region Region to close\n * @param abort True if we are aborting\n * @param zk True if we are to update zk about the region close; if the close\n * was orchestrated by master, then update zk. If the close is being run by\n * the regionserver because its going down, don't update zk.\n * @return True if closed a region.\n */\n protected boolean closeRegion(HRegionInfo region, final boolean abort,\n final boolean zk) {\n return closeRegion(region, abort, zk, -1);\n }\n\n\n /**\n * @param region Region to close\n * @param abort True if we are aborting\n * @param zk True if we are to update zk about the region close; if the close\n * was orchestrated by master, then update zk. If the close is being run by\n * the regionserver because its going down, don't update zk.\n * @param versionOfClosingNode\n * the version of znode to compare when RS transitions the znode from\n * CLOSING state.\n * @return True if closed a region.\n */\n protected boolean closeRegion(HRegionInfo region, final boolean abort,\n final boolean zk, final int versionOfClosingNode) {\n if (this.regionsInTransitionInRS.containsKey(region.getEncodedNameAsBytes())) {\n LOG.warn(\"Received close for region we are already opening or closing; \" +\n region.getEncodedName());\n return false;\n }\n this.regionsInTransitionInRS.putIfAbsent(region.getEncodedNameAsBytes(), false);\n CloseRegionHandler crh = null;\n if (region.isRootRegion()) {\n crh = new CloseRootHandler(this, this, region, abort, zk,\n versionOfClosingNode);\n } else if (region.isMetaRegion()) {\n crh = new CloseMetaHandler(this, this, region, abort, zk,\n versionOfClosingNode);\n } else {\n crh = new CloseRegionHandler(this, this, region, abort, zk,\n versionOfClosingNode);\n }\n this.service.submit(crh);\n return true;\n }\n\n /**\n * @param encodedRegionName\n * encodedregionName to close\n * @param abort\n * True if we are aborting\n * @param zk\n * True if we are to update zk about the region close; if the close\n * was orchestrated by master, then update zk. If the close is being\n * run by the regionserver because its going down, don't update zk.\n * @return True if closed a region.\n */\n protected boolean closeRegion(byte[] encodedRegionName, final boolean abort,\n final boolean zk) throws IOException {\n String encodedRegionNameStr = Bytes.toString(encodedRegionName);\n HRegion region = this.getFromOnlineRegions(encodedRegionNameStr);\n if (null != region) {\n return closeRegion(region.getRegionInfo(), abort, zk);\n }\n LOG.error(\"The specified region name\" + encodedRegionNameStr\n + \" does not exist to close the region.\");\n return false;\n }\n\n // Manual remote region administration RPCs\n\n @Override\n @QosPriority(priority=HConstants.HIGH_QOS)\n public void flushRegion(HRegionInfo regionInfo)\n throws NotServingRegionException, IOException {\n checkOpen();\n LOG.info(\"Flushing \" + regionInfo.getRegionNameAsString());\n HRegion region = getRegion(regionInfo.getRegionName());\n region.flushcache();\n }\n\n @Override\n @QosPriority(priority=HConstants.HIGH_QOS)\n public void splitRegion(HRegionInfo regionInfo)\n throws NotServingRegionException, IOException {\n splitRegion(regionInfo, null);\n }\n\n @Override\n public void splitRegion(HRegionInfo regionInfo, byte[] splitPoint)\n throws NotServingRegionException, IOException {\n checkOpen();\n HRegion region = getRegion(regionInfo.getRegionName());\n region.flushcache();\n region.forceSplit(splitPoint);\n compactSplitThread.requestSplit(region, region.checkSplit());\n }\n\n @Override\n @QosPriority(priority=HConstants.HIGH_QOS)\n public void compactRegion(HRegionInfo regionInfo, boolean major)\n throws NotServingRegionException, IOException {\n checkOpen();\n HRegion region = getRegion(regionInfo.getRegionName());\n if (major) {\n region.triggerMajorCompaction();\n }\n LOG.trace(\"User-triggered compaction requested for region \" +\n region.getRegionNameAsString());\n compactSplitThread.requestCompaction(region, \"User-triggered \"\n + (major ? \"major \" : \"\") + \"compaction\",\n Store.PRIORITY_USER);\n }\n\n /** @return the info server */\n public InfoServer getInfoServer() {\n return infoServer;\n }\n\n /**\n * @return true if a stop has been requested.\n */\n public boolean isStopped() {\n return this.stopped;\n }\n\n @Override\n public boolean isStopping() {\n return this.stopping;\n }\n\n /**\n *\n * @return the configuration\n */\n public Configuration getConfiguration() {\n return conf;\n }\n\n /** @return the write lock for the server */\n ReentrantReadWriteLock.WriteLock getWriteLock() {\n return lock.writeLock();\n }\n\n @Override\n @QosPriority(priority=HConstants.HIGH_QOS)\n public List<HRegionInfo> getOnlineRegions() throws IOException {\n checkOpen();\n List<HRegionInfo> list = new ArrayList<HRegionInfo>(onlineRegions.size());\n for (Map.Entry<String,HRegion> e: this.onlineRegions.entrySet()) {\n list.add(e.getValue().getRegionInfo());\n }\n Collections.sort(list);\n return list;\n }\n\n public int getNumberOfOnlineRegions() {\n return this.onlineRegions.size();\n }\n\n boolean isOnlineRegionsEmpty() {\n return this.onlineRegions.isEmpty();\n }\n\n /**\n * @param encodedRegionName\n * @return JSON Map of labels to values for passed in <code>encodedRegionName</code>\n * @throws IOException\n */\n public byte [] getRegionStats(final String encodedRegionName)\n throws IOException {\n HRegion r = null;\n synchronized (this.onlineRegions) {\n r = this.onlineRegions.get(encodedRegionName);\n }\n if (r == null) return null;\n ObjectMapper mapper = new ObjectMapper();\n int stores = 0;\n int storefiles = 0;\n int storefileSizeMB = 0;\n int memstoreSizeMB = (int) (r.memstoreSize.get() / 1024 / 1024);\n int storefileIndexSizeMB = 0;\n long totalCompactingKVs = 0;\n long currentCompactedKVs = 0;\n synchronized (r.stores) {\n stores += r.stores.size();\n for (Store store : r.stores.values()) {\n storefiles += store.getStorefilesCount();\n storefileSizeMB += (int) (store.getStorefilesSize() / 1024 / 1024);\n storefileIndexSizeMB += (int) (store.getStorefilesIndexSize() / 1024 / 1024);\n }\n }\n Map<String, Integer> map = new TreeMap<String, Integer>();\n map.put(\"stores\", stores);\n map.put(\"storefiles\", storefiles);\n map.put(\"storefileSizeMB\", storefileIndexSizeMB);\n map.put(\"memstoreSizeMB\", memstoreSizeMB);\n StringWriter w = new StringWriter();\n mapper.writeValue(w, map);\n w.close();\n return Bytes.toBytes(w.toString());\n }\n\n /**\n * For tests and web ui.\n * This method will only work if HRegionServer is in the same JVM as client;\n * HRegion cannot be serialized to cross an rpc.\n * @see #getOnlineRegions()\n */\n public Collection<HRegion> getOnlineRegionsLocalContext() {\n Collection<HRegion> regions = this.onlineRegions.values();\n return Collections.unmodifiableCollection(regions);\n }\n\n @Override\n public void addToOnlineRegions(HRegion region) {\n this.onlineRegions.put(region.getRegionInfo().getEncodedName(), region);\n }\n\n @Override\n public boolean removeFromOnlineRegions(final String encodedName) {\n HRegion toReturn = null;\n toReturn = this.onlineRegions.remove(encodedName);\n \n //Clear all of the dynamic metrics as they are now probably useless.\n //This is a clear because dynamic metrics could include metrics per cf and\n //per hfile. Figuring out which cfs, hfiles, and regions are still relevant to\n //this region server would be an onerous task. Instead just clear everything\n //and on the next tick of the metrics everything that is still relevant will be\n //re-added.\n this.dynamicMetrics.clear();\n return toReturn != null;\n }\n\n /**\n * @return A new Map of online regions sorted by region size with the first\n * entry being the biggest.\n */\n public SortedMap<Long, HRegion> getCopyOfOnlineRegionsSortedBySize() {\n // we'll sort the regions in reverse\n SortedMap<Long, HRegion> sortedRegions = new TreeMap<Long, HRegion>(\n new Comparator<Long>() {\n public int compare(Long a, Long b) {\n return -1 * a.compareTo(b);\n }\n });\n // Copy over all regions. Regions are sorted by size with biggest first.\n for (HRegion region : this.onlineRegions.values()) {\n sortedRegions.put(Long.valueOf(region.memstoreSize.get()), region);\n }\n return sortedRegions;\n }\n\n @Override\n public HRegion getFromOnlineRegions(final String encodedRegionName) {\n HRegion r = null;\n r = this.onlineRegions.get(encodedRegionName);\n return r;\n }\n\n /**\n * @param regionName\n * @return HRegion for the passed binary <code>regionName</code> or null if\n * named region is not member of the online regions.\n */\n public HRegion getOnlineRegion(final byte[] regionName) {\n return getFromOnlineRegions(HRegionInfo.encodeRegionName(regionName));\n }\n\n /** @return the request count */\n public AtomicInteger getRequestCount() {\n return this.requestCount;\n }\n\n /**\n * @return time stamp in millis of when this region server was started\n */\n public long getStartcode() {\n return this.startcode;\n }\n\n /** @return reference to FlushRequester */\n public FlushRequester getFlushRequester() {\n return this.cacheFlusher;\n }\n\n /**\n * Protected utility method for safely obtaining an HRegion handle.\n *\n * @param regionName\n * Name of online {@link HRegion} to return\n * @return {@link HRegion} for <code>regionName</code>\n * @throws NotServingRegionException\n */\n protected HRegion getRegion(final byte[] regionName)\n throws NotServingRegionException {\n HRegion region = null;\n region = getOnlineRegion(regionName);\n if (region == null) {\n throw new NotServingRegionException(\"Region is not online: \" +\n Bytes.toStringBinary(regionName));\n }\n return region;\n }\n\n /**\n * Get the top N most loaded regions this server is serving so we can tell the\n * master which regions it can reallocate if we're overloaded. TODO: actually\n * calculate which regions are most loaded. (Right now, we're just grabbing\n * the first N regions being served regardless of load.)\n */\n protected HRegionInfo[] getMostLoadedRegions() {\n ArrayList<HRegionInfo> regions = new ArrayList<HRegionInfo>();\n for (HRegion r : onlineRegions.values()) {\n if (!r.isAvailable()) {\n continue;\n }\n if (regions.size() < numRegionsToReport) {\n regions.add(r.getRegionInfo());\n } else {\n break;\n }\n }\n return regions.toArray(new HRegionInfo[regions.size()]);\n }\n\n /**\n * Called to verify that this server is up and running.\n *\n * @throws IOException\n */\n protected void checkOpen() throws IOException {\n if (this.stopped || this.abortRequested) {\n throw new RegionServerStoppedException(\"Server \" + getServerName() +\n \" not running\" + (this.abortRequested ? \", aborting\" : \"\"));\n }\n if (!fsOk) {\n throw new RegionServerStoppedException(\"File system not available\");\n }\n }\n\n @Override\n @QosPriority(priority=HConstants.HIGH_QOS)\n public ProtocolSignature getProtocolSignature(\n String protocol, long version, int clientMethodsHashCode)\n throws IOException {\n if (protocol.equals(HRegionInterface.class.getName())) {\n return new ProtocolSignature(HRegionInterface.VERSION, null);\n }\n throw new IOException(\"Unknown protocol: \" + protocol);\n }\n\n @Override\n @QosPriority(priority=HConstants.HIGH_QOS)\n public long getProtocolVersion(final String protocol, final long clientVersion)\n throws IOException {\n if (protocol.equals(HRegionInterface.class.getName())) {\n return HRegionInterface.VERSION;\n }\n throw new IOException(\"Unknown protocol: \" + protocol);\n }\n\n @Override\n public Leases getLeases() {\n return leases;\n }\n\n /**\n * @return Return the rootDir.\n */\n protected Path getRootDir() {\n return rootDir;\n }\n\n /**\n * @return Return the fs.\n */\n public FileSystem getFileSystem() {\n return fs;\n }\n\n /**\n * @return This servers {@link HServerInfo}\n */\n // TODO: Deprecate and do getServerName instead.\n public HServerInfo getServerInfo() {\n try {\n return getHServerInfo();\n } catch (IOException e) {\n e.printStackTrace();\n }\n return null;\n }\n\n @Override\n public void mutateRow(byte[] regionName, RowMutations rm)\n throws IOException {\n checkOpen();\n if (regionName == null) {\n throw new IOException(\"Invalid arguments to mutateRow \" +\n \"regionName is null\");\n }\n requestCount.incrementAndGet();\n try {\n HRegion region = getRegion(regionName);\n if (!region.getRegionInfo().isMetaTable()) {\n this.cacheFlusher.reclaimMemStoreMemory();\n }\n region.mutateRow(rm);\n } catch (IOException e) {\n checkFileSystem();\n throw e;\n }\n }\n\n @Override\n public Result append(byte[] regionName, Append append)\n throws IOException {\n checkOpen();\n if (regionName == null) {\n throw new IOException(\"Invalid arguments to increment \" +\n \"regionName is null\");\n }\n requestCount.incrementAndGet();\n try {\n HRegion region = getRegion(regionName);\n Integer lock = getLockFromId(append.getLockId());\n Append appVal = append;\n Result resVal;\n if (region.getCoprocessorHost() != null) {\n resVal = region.getCoprocessorHost().preAppend(appVal);\n if (resVal != null) {\n return resVal;\n }\n }\n resVal = region.append(appVal, lock, append.getWriteToWAL());\n if (region.getCoprocessorHost() != null) {\n region.getCoprocessorHost().postAppend(appVal, resVal);\n }\n return resVal;\n } catch (IOException e) {\n checkFileSystem();\n throw e;\n }\n }\n\n @Override\n public Result increment(byte[] regionName, Increment increment)\n throws IOException {\n checkOpen();\n if (regionName == null) {\n throw new IOException(\"Invalid arguments to increment \" +\n \"regionName is null\");\n }\n requestCount.incrementAndGet();\n try {\n HRegion region = getRegion(regionName);\n Integer lock = getLockFromId(increment.getLockId());\n Increment incVal = increment;\n Result resVal;\n if (region.getCoprocessorHost() != null) {\n resVal = region.getCoprocessorHost().preIncrement(incVal);\n if (resVal != null) {\n return resVal;\n }\n }\n resVal = region.increment(incVal, lock,\n increment.getWriteToWAL());\n if (region.getCoprocessorHost() != null) {\n resVal = region.getCoprocessorHost().postIncrement(incVal, resVal);\n }\n return resVal;\n } catch (IOException e) {\n checkFileSystem();\n throw e;\n }\n }\n\n /** {@inheritDoc} */\n public long incrementColumnValue(byte[] regionName, byte[] row,\n byte[] family, byte[] qualifier, long amount, boolean writeToWAL)\n throws IOException {\n checkOpen();\n\n if (regionName == null) {\n throw new IOException(\"Invalid arguments to incrementColumnValue \"\n + \"regionName is null\");\n }\n requestCount.incrementAndGet();\n try {\n HRegion region = getRegion(regionName);\n if (region.getCoprocessorHost() != null) {\n Long amountVal = region.getCoprocessorHost().preIncrementColumnValue(row,\n family, qualifier, amount, writeToWAL);\n if (amountVal != null) {\n return amountVal.longValue();\n }\n }\n long retval = region.incrementColumnValue(row, family, qualifier, amount,\n writeToWAL);\n if (region.getCoprocessorHost() != null) {\n retval = region.getCoprocessorHost().postIncrementColumnValue(row,\n family, qualifier, amount, writeToWAL, retval);\n }\n return retval;\n } catch (IOException e) {\n checkFileSystem();\n throw e;\n }\n }\n\n /** {@inheritDoc}\n * @deprecated Use {@link #getServerName()} instead.\n */\n @Override\n @QosPriority(priority=HConstants.HIGH_QOS)\n public HServerInfo getHServerInfo() throws IOException {\n checkOpen();\n return new HServerInfo(new HServerAddress(this.isa),\n this.startcode, this.webuiport);\n }\n\n @SuppressWarnings(\"unchecked\")\n @Override\n public <R> MultiResponse multi(MultiAction<R> multi) throws IOException {\n checkOpen();\n MultiResponse response = new MultiResponse();\n for (Map.Entry<byte[], List<Action<R>>> e : multi.actions.entrySet()) {\n byte[] regionName = e.getKey();\n List<Action<R>> actionsForRegion = e.getValue();\n // sort based on the row id - this helps in the case where we reach the\n // end of a region, so that we don't have to try the rest of the\n // actions in the list.\n Collections.sort(actionsForRegion);\n Row action;\n List<Action<R>> mutations = new ArrayList<Action<R>>();\n for (Action<R> a : actionsForRegion) {\n action = a.getAction();\n int originalIndex = a.getOriginalIndex();\n\n try {\n if (action instanceof Delete || action instanceof Put) {\n mutations.add(a); \n } else if (action instanceof Get) {\n response.add(regionName, originalIndex,\n get(regionName, (Get)action));\n } else if (action instanceof Exec) {\n ExecResult result = execCoprocessor(regionName, (Exec)action);\n response.add(regionName, new Pair<Integer, Object>(\n a.getOriginalIndex(), result.getValue()\n ));\n } else if (action instanceof Increment) {\n response.add(regionName, originalIndex,\n increment(regionName, (Increment)action));\n } else if (action instanceof Append) {\n response.add(regionName, originalIndex,\n append(regionName, (Append)action));\n } else if (action instanceof RowMutations) {\n mutateRow(regionName, (RowMutations)action);\n response.add(regionName, originalIndex, new Result());\n } else {\n LOG.debug(\"Error: invalid Action, row must be a Get, Delete, \" +\n \"Put, Exec, Increment, or Append.\");\n throw new DoNotRetryIOException(\"Invalid Action, row must be a \" +\n \"Get, Delete, Put, Exec, Increment, or Append.\");\n }\n } catch (IOException ex) {\n response.add(regionName, originalIndex, ex);\n }\n }\n\n // We do the puts with result.put so we can get the batching efficiency\n // we so need. All this data munging doesn't seem great, but at least\n // we arent copying bytes or anything.\n if (!mutations.isEmpty()) {\n try {\n HRegion region = getRegion(regionName);\n\n if (!region.getRegionInfo().isMetaTable()) {\n this.cacheFlusher.reclaimMemStoreMemory();\n }\n\n List<Pair<Mutation,Integer>> mutationsWithLocks =\n Lists.newArrayListWithCapacity(mutations.size());\n for (Action<R> a : mutations) {\n Mutation m = (Mutation) a.getAction();\n\n Integer lock;\n try {\n lock = getLockFromId(m.getLockId());\n } catch (UnknownRowLockException ex) {\n response.add(regionName, a.getOriginalIndex(), ex);\n continue;\n }\n mutationsWithLocks.add(new Pair<Mutation, Integer>(m, lock));\n }\n\n this.requestCount.addAndGet(mutations.size());\n\n OperationStatus[] codes =\n region.batchMutate(mutationsWithLocks.toArray(new Pair[]{}));\n\n for( int i = 0 ; i < codes.length ; i++) {\n OperationStatus code = codes[i];\n\n Action<R> theAction = mutations.get(i);\n Object result = null;\n\n if (code.getOperationStatusCode() == OperationStatusCode.SUCCESS) {\n result = new Result();\n } else if (code.getOperationStatusCode()\n == OperationStatusCode.SANITY_CHECK_FAILURE) {\n // Don't send a FailedSanityCheckException as older clients will not know about\n // that class being a subclass of DoNotRetryIOException\n // and will retry mutations that will never succeed.\n result = new DoNotRetryIOException(code.getExceptionMsg());\n } else if (code.getOperationStatusCode() == OperationStatusCode.BAD_FAMILY) {\n result = new NoSuchColumnFamilyException(code.getExceptionMsg());\n }\n // FAILURE && NOT_RUN becomes null, aka: need to run again.\n\n response.add(regionName, theAction.getOriginalIndex(), result);\n }\n } catch (IOException ioe) {\n // fail all the puts with the ioe in question.\n for (Action<R> a: mutations) {\n response.add(regionName, a.getOriginalIndex(), ioe);\n }\n }\n }\n }\n return response;\n }\n\n /**\n * Executes a single {@link org.apache.hadoop.hbase.ipc.CoprocessorProtocol}\n * method using the registered protocol handlers.\n * {@link CoprocessorProtocol} implementations must be registered per-region\n * via the\n * {@link org.apache.hadoop.hbase.regionserver.HRegion#registerProtocol(Class, org.apache.hadoop.hbase.ipc.CoprocessorProtocol)}\n * method before they are available.\n *\n * @param regionName name of the region against which the invocation is executed\n * @param call an {@code Exec} instance identifying the protocol, method name,\n * and parameters for the method invocation\n * @return an {@code ExecResult} instance containing the region name of the\n * invocation and the return value\n * @throws IOException if no registered protocol handler is found or an error\n * occurs during the invocation\n * @see org.apache.hadoop.hbase.regionserver.HRegion#registerProtocol(Class, org.apache.hadoop.hbase.ipc.CoprocessorProtocol)\n */\n @Override\n public ExecResult execCoprocessor(byte[] regionName, Exec call)\n throws IOException {\n checkOpen();\n requestCount.incrementAndGet();\n try {\n HRegion region = getRegion(regionName);\n return region.exec(call);\n } catch (Throwable t) {\n throw convertThrowableToIOE(cleanup(t));\n }\n }\n\n public String toString() {\n return getServerName().toString();\n }\n\n /**\n * Interval at which threads should run\n *\n * @return the interval\n */\n public int getThreadWakeFrequency() {\n return threadWakeFrequency;\n }\n\n @Override\n public ZooKeeperWatcher getZooKeeper() {\n return zooKeeper;\n }\n\n @Override\n public ServerName getServerName() {\n // Our servername could change after we talk to the master.\n return this.serverNameFromMasterPOV == null?\n new ServerName(this.isa.getHostName(), this.isa.getPort(), this.startcode):\n this.serverNameFromMasterPOV;\n }\n\n @Override\n public CompactionRequestor getCompactionRequester() {\n return this.compactSplitThread;\n }\n\n public ZooKeeperWatcher getZooKeeperWatcher() {\n return this.zooKeeper;\n }\n\n\n public ConcurrentSkipListMap<byte[], Boolean> getRegionsInTransitionInRS() {\n return this.regionsInTransitionInRS;\n }\n\n public ExecutorService getExecutorService() {\n return service;\n }\n\n //\n // Main program and support routines\n //\n\n /**\n * Load the replication service objects, if any\n */\n static private void createNewReplicationInstance(Configuration conf,\n HRegionServer server, FileSystem fs, Path logDir, Path oldLogDir) throws IOException{\n\n // If replication is not enabled, then return immediately.\n if (!conf.getBoolean(HConstants.REPLICATION_ENABLE_KEY, false)) {\n return;\n }\n\n // read in the name of the source replication class from the config file.\n String sourceClassname = conf.get(HConstants.REPLICATION_SOURCE_SERVICE_CLASSNAME,\n HConstants.REPLICATION_SERVICE_CLASSNAME_DEFAULT);\n\n // read in the name of the sink replication class from the config file.\n String sinkClassname = conf.get(HConstants.REPLICATION_SINK_SERVICE_CLASSNAME,\n HConstants.REPLICATION_SERVICE_CLASSNAME_DEFAULT);\n\n // If both the sink and the source class names are the same, then instantiate\n // only one object.\n if (sourceClassname.equals(sinkClassname)) {\n server.replicationSourceHandler = (ReplicationSourceService)\n newReplicationInstance(sourceClassname,\n conf, server, fs, logDir, oldLogDir);\n server.replicationSinkHandler = (ReplicationSinkService)\n server.replicationSourceHandler;\n }\n else {\n server.replicationSourceHandler = (ReplicationSourceService)\n newReplicationInstance(sourceClassname,\n conf, server, fs, logDir, oldLogDir);\n server.replicationSinkHandler = (ReplicationSinkService)\n newReplicationInstance(sinkClassname,\n conf, server, fs, logDir, oldLogDir);\n }\n }\n\n static private ReplicationService newReplicationInstance(String classname,\n Configuration conf, HRegionServer server, FileSystem fs, Path logDir,\n Path oldLogDir) throws IOException{\n\n Class<?> clazz = null;\n try {\n ClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n clazz = Class.forName(classname, true, classLoader);\n } catch (java.lang.ClassNotFoundException nfe) {\n throw new IOException(\"Cound not find class for \" + classname);\n }\n\n // create an instance of the replication object.\n ReplicationService service = (ReplicationService)\n ReflectionUtils.newInstance(clazz, conf);\n service.initialize(server, fs, logDir, oldLogDir);\n return service;\n }\n\n /**\n * @param hrs\n * @return Thread the RegionServer is running in correctly named.\n * @throws IOException\n */\n public static Thread startRegionServer(final HRegionServer hrs)\n throws IOException {\n return startRegionServer(hrs, \"regionserver\" + hrs.isa.getPort());\n }\n\n /**\n * @param hrs\n * @param name\n * @return Thread the RegionServer is running in correctly named.\n * @throws IOException\n */\n public static Thread startRegionServer(final HRegionServer hrs,\n final String name) throws IOException {\n Thread t = new Thread(hrs);\n t.setName(name);\n t.start();\n // Install shutdown hook that will catch signals and run an orderly shutdown\n // of the hrs.\n ShutdownHook.install(hrs.getConfiguration(), FileSystem.get(hrs\n .getConfiguration()), hrs, t);\n return t;\n }\n\n /**\n * Utility for constructing an instance of the passed HRegionServer class.\n *\n * @param regionServerClass\n * @param conf2\n * @return HRegionServer instance.\n */\n public static HRegionServer constructRegionServer(\n Class<? extends HRegionServer> regionServerClass,\n final Configuration conf2) {\n try {\n Constructor<? extends HRegionServer> c = regionServerClass\n .getConstructor(Configuration.class);\n return c.newInstance(conf2);\n } catch (Exception e) {\n throw new RuntimeException(\"Failed construction of \" + \"Regionserver: \"\n + regionServerClass.toString(), e);\n }\n }\n\n @Override\n @QosPriority(priority=HConstants.REPLICATION_QOS)\n public void replicateLogEntries(final HLog.Entry[] entries)\n throws IOException {\n checkOpen();\n if (this.replicationSinkHandler == null) return;\n this.replicationSinkHandler.replicateLogEntries(entries);\n }\n\n /**\n * @see org.apache.hadoop.hbase.regionserver.HRegionServerCommandLine\n */\n public static void main(String[] args) throws Exception {\n\tVersionInfo.logVersion();\n Configuration conf = HBaseConfiguration.create();\n @SuppressWarnings(\"unchecked\")\n Class<? extends HRegionServer> regionServerClass = (Class<? extends HRegionServer>) conf\n .getClass(HConstants.REGION_SERVER_IMPL, HRegionServer.class);\n\n new HRegionServerCommandLine(regionServerClass).doMain(args);\n }\n\n @Override\n public List<BlockCacheColumnFamilySummary> getBlockCacheColumnFamilySummaries() throws IOException {\n BlockCache c = new CacheConfig(this.conf).getBlockCache();\n return c.getBlockCacheColumnFamilySummaries(this.conf);\n }\n\n @Override\n public byte[][] rollHLogWriter() throws IOException, FailedLogCloseException {\n HLog wal = this.getWAL();\n return wal.rollWriter(true);\n }\n\n /**\n * Gets the online regions of the specified table.\n * This method looks at the in-memory onlineRegions. It does not go to <code>.META.</code>.\n * Only returns <em>online</em> regions. If a region on this table has been\n * closed during a disable, etc., it will not be included in the returned list.\n * So, the returned list may not necessarily be ALL regions in this table, its\n * all the ONLINE regions in the table.\n * @param tableName\n * @return Online regions from <code>tableName</code>\n */\n public List<HRegion> getOnlineRegions(byte[] tableName) {\n List<HRegion> tableRegions = new ArrayList<HRegion>();\n synchronized (this.onlineRegions) {\n for (HRegion region: this.onlineRegions.values()) {\n HRegionInfo regionInfo = region.getRegionInfo();\n if(Bytes.equals(regionInfo.getTableName(), tableName)) {\n tableRegions.add(region);\n }\n }\n }\n return tableRegions;\n }\n\n // used by org/apache/hbase/tmpl/regionserver/RSStatusTmpl.jamon (HBASE-4070).\n public String[] getCoprocessors() {\n HServerLoad hsl = buildServerLoad();\n return hsl == null? null: hsl.getCoprocessors();\n }\n\n /**\n * Register bean with platform management server\n */\n @SuppressWarnings(\"deprecation\")\n void registerMBean() {\n MXBeanImpl mxBeanInfo = MXBeanImpl.init(this);\n mxBean = MBeanUtil.registerMBean(\"RegionServer\", \"RegionServer\",\n mxBeanInfo);\n LOG.info(\"Registered RegionServer MXBean\");\n }\n\n /**\n * Get the current compaction state of the region.\n *\n * @param regionName the name of the region to check compaction statte.\n * @return the compaction state name.\n * @throws IOException exception\n */\n public String getCompactionState(final byte[] regionName) throws IOException {\n checkOpen();\n requestCount.incrementAndGet();\n HRegion region = getRegion(regionName);\n HRegionInfo info = region.getRegionInfo();\n return CompactionRequest.getCompactionState(info.getRegionId()).name();\n }\n}", "public class Threads {\n protected static final Log LOG = LogFactory.getLog(Threads.class);\n private static final AtomicInteger poolNumber = new AtomicInteger(1);\n\n /**\n * Utility method that sets name, daemon status and starts passed thread.\n * @param t thread to run\n * @return Returns the passed Thread <code>t</code>.\n */\n public static Thread setDaemonThreadRunning(final Thread t) {\n return setDaemonThreadRunning(t, t.getName());\n }\n\n /**\n * Utility method that sets name, daemon status and starts passed thread.\n * @param t thread to frob\n * @param name new name\n * @return Returns the passed Thread <code>t</code>.\n */\n public static Thread setDaemonThreadRunning(final Thread t,\n final String name) {\n return setDaemonThreadRunning(t, name, null);\n }\n\n /**\n * Utility method that sets name, daemon status and starts passed thread.\n * @param t thread to frob\n * @param name new name\n * @param handler A handler to set on the thread. Pass null if want to\n * use default handler.\n * @return Returns the passed Thread <code>t</code>.\n */\n public static Thread setDaemonThreadRunning(final Thread t,\n final String name, final UncaughtExceptionHandler handler) {\n t.setName(name);\n if (handler != null) {\n t.setUncaughtExceptionHandler(handler);\n }\n t.setDaemon(true);\n t.start();\n return t;\n }\n\n /**\n * Shutdown passed thread using isAlive and join.\n * @param t Thread to shutdown\n */\n public static void shutdown(final Thread t) {\n shutdown(t, 0);\n }\n\n /**\n * Shutdown passed thread using isAlive and join.\n * @param joinwait Pass 0 if we're to wait forever.\n * @param t Thread to shutdown\n */\n public static void shutdown(final Thread t, final long joinwait) {\n if (t == null) return;\n while (t.isAlive()) {\n try {\n t.join(joinwait);\n } catch (InterruptedException e) {\n LOG.warn(t.getName() + \"; joinwait=\" + joinwait, e);\n }\n }\n }\n\n\n /**\n * @param t Waits on the passed thread to die dumping a threaddump every\n * minute while its up.\n * @throws InterruptedException\n */\n public static void threadDumpingIsAlive(final Thread t)\n throws InterruptedException {\n if (t == null) {\n return;\n }\n\n while (t.isAlive()) {\n t.join(60 * 1000);\n if (t.isAlive()) {\n ReflectionUtils.printThreadInfo(new PrintWriter(System.out),\n \"Automatic Stack Trace every 60 seconds waiting on \" +\n t.getName());\n }\n }\n }\n\n /**\n * @param millis How long to sleep for in milliseconds.\n */\n public static void sleep(int millis) {\n try {\n Thread.sleep(millis);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n\n /**\n * Sleeps for the given amount of time even if interrupted. Preserves\n * the interrupt status.\n * @param msToWait the amount of time to sleep in milliseconds\n */\n public static void sleepWithoutInterrupt(final long msToWait) {\n long timeMillis = System.currentTimeMillis();\n long endTime = timeMillis + msToWait;\n boolean interrupted = false;\n while (timeMillis < endTime) {\n try {\n Thread.sleep(endTime - timeMillis);\n } catch (InterruptedException ex) {\n interrupted = true;\n }\n timeMillis = System.currentTimeMillis();\n }\n\n if (interrupted) {\n Thread.currentThread().interrupt();\n }\n }\n\n /**\n * Create a new CachedThreadPool with a bounded number as the maximum \n * thread size in the pool.\n * \n * @param maxCachedThread the maximum thread could be created in the pool\n * @param timeout the maximum time to wait\n * @param unit the time unit of the timeout argument\n * @param threadFactory the factory to use when creating new threads\n * @return threadPoolExecutor the cachedThreadPool with a bounded number \n * as the maximum thread size in the pool. \n */\n public static ThreadPoolExecutor getBoundedCachedThreadPool(\n int maxCachedThread, long timeout, TimeUnit unit,\n ThreadFactory threadFactory) {\n ThreadPoolExecutor boundedCachedThreadPool =\n new ThreadPoolExecutor(maxCachedThread, maxCachedThread, timeout,\n TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory);\n // allow the core pool threads timeout and terminate\n boundedCachedThreadPool.allowCoreThreadTimeOut(true);\n return boundedCachedThreadPool;\n }\n \n \n /**\n * Returns a {@link java.util.concurrent.ThreadFactory} that names each created thread uniquely,\n * with a common prefix.\n * @param prefix The prefix of every created Thread's name\n * @return a {@link java.util.concurrent.ThreadFactory} that names threads\n */\n public static ThreadFactory getNamedThreadFactory(final String prefix) {\n SecurityManager s = System.getSecurityManager();\n final ThreadGroup threadGroup = (s != null) ? s.getThreadGroup() : Thread.currentThread()\n .getThreadGroup();\n\n return new ThreadFactory() {\n final AtomicInteger threadNumber = new AtomicInteger(1);\n private final int poolNumber = Threads.poolNumber.getAndIncrement();\n final ThreadGroup group = threadGroup;\n\n @Override\n public Thread newThread(Runnable r) {\n final String name = prefix + \"pool-\" + poolNumber + \"-thread-\"\n + threadNumber.getAndIncrement();\n return new Thread(group, r, name);\n }\n };\n }\n\n /**\n * Get a named {@link ThreadFactory} that just builds daemon threads\n * @param prefix name prefix for all threads created from the factory\n * @return a thread factory that creates named, daemon threads\n */\n public static ThreadFactory newDaemonThreadFactory(final String prefix) {\n final ThreadFactory namedFactory = getNamedThreadFactory(prefix);\n return new ThreadFactory() {\n @Override\n public Thread newThread(Runnable r) {\n Thread t = namedFactory.newThread(r);\n if (!t.isDaemon()) {\n t.setDaemon(true);\n }\n if (t.getPriority() != Thread.NORM_PRIORITY) {\n t.setPriority(Thread.NORM_PRIORITY);\n }\n return t;\n }\n\n };\n }\n}" ]
import org.apache.hadoop.hbase.regionserver.HRegion; import org.apache.hadoop.hbase.regionserver.HRegionServer; import org.apache.hadoop.hbase.security.User; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.JVMClusterUtil; import org.apache.hadoop.hbase.util.Threads; import org.apache.hadoop.io.MapWritable; import java.io.IOException; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.hbase.client.HConnectionManager; import org.apache.hadoop.hbase.master.HMaster;
/** * Copyright 2008 The Apache Software Foundation * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase; /** * This class creates a single process HBase cluster. * each server. The master uses the 'default' FileSystem. The RegionServers, * if we are running on DistributedFilesystem, create a FileSystem instance * each and will close down their instance on the way out. */ public class MiniHBaseCluster { static final Log LOG = LogFactory.getLog(MiniHBaseCluster.class.getName()); private Configuration conf; public LocalHBaseCluster hbaseCluster; private static int index; /** * Start a MiniHBaseCluster. * @param conf Configuration to be used for cluster * @param numRegionServers initial number of region servers to start. * @throws IOException */ public MiniHBaseCluster(Configuration conf, int numRegionServers) throws IOException, InterruptedException { this(conf, 1, numRegionServers); } /** * Start a MiniHBaseCluster. * @param conf Configuration to be used for cluster * @param numMasters initial number of masters to start. * @param numRegionServers initial number of region servers to start. * @throws IOException */ public MiniHBaseCluster(Configuration conf, int numMasters, int numRegionServers) throws IOException, InterruptedException { this.conf = conf; conf.set(HConstants.MASTER_PORT, "0"); init(numMasters, numRegionServers); } public Configuration getConfiguration() { return this.conf; } /** * Subclass so can get at protected methods (none at moment). Also, creates * a FileSystem instance per instantiation. Adds a shutdown own FileSystem * on the way out. Shuts down own Filesystem only, not All filesystems as * the FileSystem system exit hook does. */
public static class MiniHBaseClusterRegionServer extends HRegionServer {
3
lingochamp/FileDownloader
library/src/main/java/com/liulishuo/filedownloader/FileDownloadServiceSharedTransmit.java
[ "public class DownloadServiceConnectChangedEvent extends IDownloadEvent {\n public static final String ID = \"event.service.connect.changed\";\n\n public DownloadServiceConnectChangedEvent(final ConnectStatus status,\n final Class<?> serviceClass) {\n super(ID);\n\n this.status = status;\n this.serviceClass = serviceClass;\n }\n\n private final ConnectStatus status;\n\n public enum ConnectStatus {\n connected, disconnected,\n // the process hosting the service has crashed or been killed. (do not be unbound manually)\n lost\n }\n\n public ConnectStatus getStatus() {\n return status;\n }\n\n private final Class<?> serviceClass;\n\n public boolean isSuchService(final Class<?> serviceClass) {\n return this.serviceClass != null\n && this.serviceClass.getName().equals(serviceClass.getName());\n\n }\n}", "public class FileDownloadHeader implements Parcelable {\n\n private HashMap<String, List<String>> mHeaderMap;\n\n /**\n * We have already handled etag, and will add 'If-Match' & 'Range' value if it works.\n *\n * @see com.liulishuo.filedownloader.download.ConnectTask#addUserRequiredHeader\n */\n public void add(String name, String value) {\n if (name == null) throw new NullPointerException(\"name == null\");\n if (name.isEmpty()) throw new IllegalArgumentException(\"name is empty\");\n if (value == null) throw new NullPointerException(\"value == null\");\n\n if (mHeaderMap == null) {\n mHeaderMap = new HashMap<>();\n }\n\n List<String> values = mHeaderMap.get(name);\n if (values == null) {\n values = new ArrayList<>();\n mHeaderMap.put(name, values);\n }\n\n if (!values.contains(value)) {\n values.add(value);\n }\n }\n\n /**\n * We have already handled etag, and will add 'If-Match' & 'Range' value if it works.\n *\n * @see com.liulishuo.filedownloader.download.ConnectTask#addUserRequiredHeader\n */\n public void add(String line) {\n String[] parsed = line.split(\":\");\n final String name = parsed[0].trim();\n final String value = parsed[1].trim();\n\n add(name, value);\n }\n\n /**\n * Remove all files with the name.\n */\n public void removeAll(String name) {\n if (mHeaderMap == null) {\n return;\n }\n\n mHeaderMap.remove(name);\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeMap(mHeaderMap);\n }\n\n public HashMap<String, List<String>> getHeaders() {\n return mHeaderMap;\n }\n\n public FileDownloadHeader() {\n }\n\n protected FileDownloadHeader(Parcel in) {\n //noinspection unchecked\n this.mHeaderMap = in.readHashMap(String.class.getClassLoader());\n }\n\n public static final Creator<FileDownloadHeader> CREATOR = new Creator<FileDownloadHeader>() {\n public FileDownloadHeader createFromParcel(Parcel source) {\n return new FileDownloadHeader(source);\n }\n\n public FileDownloadHeader[] newArray(int size) {\n return new FileDownloadHeader[size];\n }\n };\n\n @Override\n public String toString() {\n return mHeaderMap.toString();\n }\n}", "public class FDServiceSharedHandler extends IFileDownloadIPCService.Stub\n implements IFileDownloadServiceHandler {\n private final FileDownloadManager downloadManager;\n private final WeakReference<FileDownloadService> wService;\n\n FDServiceSharedHandler(WeakReference<FileDownloadService> wService,\n FileDownloadManager manager) {\n this.wService = wService;\n this.downloadManager = manager;\n }\n\n @Override\n public void registerCallback(IFileDownloadIPCCallback callback) {\n }\n\n @Override\n public void unregisterCallback(IFileDownloadIPCCallback callback) {\n }\n\n @Override\n public boolean checkDownloading(String url, String path) {\n return downloadManager.isDownloading(url, path);\n }\n\n @Override\n public void start(String url, String path, boolean pathAsDirectory, int callbackProgressTimes,\n int callbackProgressMinIntervalMillis, int autoRetryTimes,\n boolean forceReDownload,\n FileDownloadHeader header, boolean isWifiRequired) {\n downloadManager.start(url, path, pathAsDirectory, callbackProgressTimes,\n callbackProgressMinIntervalMillis, autoRetryTimes, forceReDownload, header,\n isWifiRequired);\n }\n\n @Override\n public boolean pause(int downloadId) {\n return downloadManager.pause(downloadId);\n }\n\n @Override\n public void pauseAllTasks() {\n downloadManager.pauseAll();\n }\n\n @Override\n public boolean setMaxNetworkThreadCount(int count) {\n return downloadManager.setMaxNetworkThreadCount(count);\n }\n\n @Override\n public long getSofar(int downloadId) {\n return downloadManager.getSoFar(downloadId);\n }\n\n @Override\n public long getTotal(int downloadId) {\n return downloadManager.getTotal(downloadId);\n }\n\n @Override\n public byte getStatus(int downloadId) {\n return downloadManager.getStatus(downloadId);\n }\n\n @Override\n public boolean isIdle() {\n return downloadManager.isIdle();\n }\n\n @Override\n public void startForeground(int id, Notification notification) {\n if (this.wService != null && this.wService.get() != null) {\n this.wService.get().startForeground(id, notification);\n }\n }\n\n @Override\n public void stopForeground(boolean removeNotification) {\n if (this.wService != null && this.wService.get() != null) {\n this.wService.get().stopForeground(removeNotification);\n }\n }\n\n @Override\n public boolean clearTaskData(int id) {\n return downloadManager.clearTaskData(id);\n }\n\n @Override\n public void clearAllTaskData() {\n downloadManager.clearAllTaskData();\n }\n\n @Override\n public void onStartCommand(Intent intent, int flags, int startId) {\n //noinspection ConstantConditions\n FileDownloadServiceProxy.getConnectionListener().onConnected(this);\n }\n\n @Override\n public IBinder onBind(Intent intent) {\n return null;\n }\n\n @Override\n public void onDestroy() {\n //noinspection ConstantConditions\n FileDownloadServiceProxy.getConnectionListener().onDisconnected();\n }\n\n public interface FileDownloadServiceSharedConnection {\n void onConnected(FDServiceSharedHandler handler);\n\n void onDisconnected();\n }\n}", "public interface FileDownloadServiceSharedConnection {\n void onConnected(FDServiceSharedHandler handler);\n\n void onDisconnected();\n}", "public static class SharedMainProcessService extends FileDownloadService {\n}", "public class DownloadServiceNotConnectedHelper {\n\n private static final String CAUSE = \", but the download service isn't connected yet.\";\n private static final String TIPS = \"\\nYou can use FileDownloader#isServiceConnected() to check\"\n + \" whether the service has been connected, \\nbesides you can use following functions\"\n + \" easier to control your code invoke after the service has been connected: \\n\"\n + \"1. FileDownloader#bindService(Runnable)\\n\"\n + \"2. FileDownloader#insureServiceBind()\\n\"\n + \"3. FileDownloader#insureServiceBindAsync()\";\n\n public static boolean start(final String url, final String path,\n final boolean pathAsDirectory) {\n log(\"request start the task([%s], [%s], [%B]) in the download service\", url, path,\n pathAsDirectory);\n return false;\n }\n\n public static boolean pause(final int id) {\n log(\"request pause the task[%d] in the download service\", id);\n return false;\n }\n\n public static boolean isDownloading(final String url, final String path) {\n log(\"request check the task([%s], [%s]) is downloading in the download service\", url, path);\n return false;\n }\n\n public static long getSofar(final int id) {\n log(\"request get the downloaded so far byte for the task[%d] in the download service\", id);\n return 0;\n }\n\n public static long getTotal(final int id) {\n log(\"request get the total byte for the task[%d] in the download service\", id);\n return 0;\n }\n\n public static byte getStatus(final int id) {\n log(\"request get the status for the task[%d] in the download service\", id);\n return FileDownloadStatus.INVALID_STATUS;\n }\n\n public static void pauseAllTasks() {\n log(\"request pause all tasks in the download service\");\n }\n\n public static boolean isIdle() {\n log(\"request check the download service is idle\");\n return true;\n }\n\n public static void startForeground(int notificationId, Notification notification) {\n log(\"request set the download service as the foreground service([%d],[%s]),\",\n notificationId, notification);\n }\n\n public static void stopForeground(boolean removeNotification) {\n log(\"request cancel the foreground status[%B] for the download service\",\n removeNotification);\n }\n\n public static boolean setMaxNetworkThreadCount(int count) {\n log(\"request set the max network thread count[%d] in the download service\", count);\n return false;\n }\n\n public static boolean clearTaskData(int id) {\n log(\"request clear the task[%d] data in the database\", id);\n return false;\n }\n\n public static boolean clearAllTaskData() {\n log(\"request clear all tasks data in the database\");\n return false;\n }\n\n private static void log(String message, Object... args) {\n FileDownloadLog.w(DownloadServiceNotConnectedHelper.class, message + CAUSE + TIPS, args);\n }\n\n}", "public class ExtraKeys {\n\n public static final String IS_FOREGROUND = \"is_foreground\";\n}", "public class FileDownloadLog {\n\n public static boolean NEED_LOG = false;\n\n private static final String TAG = \"FileDownloader.\";\n\n public static void e(Object o, Throwable e, String msg, Object... args) {\n log(Log.ERROR, o, e, msg, args);\n }\n\n public static void e(Object o, String msg, Object... args) {\n log(Log.ERROR, o, msg, args);\n }\n\n public static void i(Object o, String msg, Object... args) {\n log(Log.INFO, o, msg, args);\n }\n\n public static void d(Object o, String msg, Object... args) {\n log(Log.DEBUG, o, msg, args);\n }\n\n public static void w(Object o, String msg, Object... args) {\n log(Log.WARN, o, msg, args);\n }\n\n public static void v(Object o, String msg, Object... args) {\n log(Log.VERBOSE, o, msg, args);\n }\n\n private static void log(int priority, Object o, String message, Object... args) {\n log(priority, o, null, message, args);\n }\n\n private static void log(int priority, Object o, Throwable throwable, String message,\n Object... args) {\n final boolean force = priority >= Log.WARN;\n if (!force && !NEED_LOG) {\n return;\n }\n\n Log.println(priority, getTag(o), FileDownloadUtils.formatString(message, args));\n if (throwable != null) {\n throwable.printStackTrace();\n }\n }\n\n private static String getTag(final Object o) {\n return TAG + ((o instanceof Class)\n ? ((Class) o).getSimpleName() : o.getClass().getSimpleName());\n }\n}", "@SuppressWarnings({\"SameParameterValue\", \"WeakerAccess\"})\npublic class FileDownloadUtils {\n\n private static int minProgressStep = 65536;\n private static long minProgressTime = 2000;\n\n /**\n * @param minProgressStep The minimum bytes interval in per step to sync to the file and the\n * database.\n * <p>\n * Used for adjudging whether is time to sync the downloaded so far bytes\n * to database and make sure sync the downloaded buffer to local file.\n * <p/>\n * More smaller more frequently, then download more slowly, but will more\n * safer in scene of the process is killed unexpected.\n * <p/>\n * Default 65536, which follow the value in\n * com.android.providers.downloads.Constants.\n * @see com.liulishuo.filedownloader.download.DownloadStatusCallback#onProgress(long)\n * @see #setMinProgressTime(long)\n */\n public static void setMinProgressStep(int minProgressStep) throws IllegalAccessException {\n if (isDownloaderProcess(FileDownloadHelper.getAppContext())) {\n FileDownloadUtils.minProgressStep = minProgressStep;\n } else {\n throw new IllegalAccessException(\"This value is used in the :filedownloader process,\"\n + \" so set this value in your process is without effect. You can add \"\n + \"'process.non-separate=true' in 'filedownloader.properties' to share the main\"\n + \" process to FileDownloadService. Or you can configure this value in \"\n + \"'filedownloader.properties' by 'download.min-progress-step'.\");\n }\n }\n\n /**\n * @param minProgressTime The minimum millisecond interval in per time to sync to the file and\n * the database.\n * <p>\n * Used for adjudging whether is time to sync the downloaded so far bytes\n * to database and make sure sync the downloaded buffer to local file.\n * <p/>\n * More smaller more frequently, then download more slowly, but will more\n * safer in scene of the process is killed unexpected.\n * <p/>\n * Default 2000, which follow the value in\n * com.android.providers.downloads.Constants.\n * @see com.liulishuo.filedownloader.download.DownloadStatusCallback#onProgress(long)\n * @see #setMinProgressStep(int)\n */\n public static void setMinProgressTime(long minProgressTime) throws IllegalAccessException {\n if (isDownloaderProcess(FileDownloadHelper.getAppContext())) {\n FileDownloadUtils.minProgressTime = minProgressTime;\n } else {\n throw new IllegalAccessException(\"This value is used in the :filedownloader process,\"\n + \" so set this value in your process is without effect. You can add \"\n + \"'process.non-separate=true' in 'filedownloader.properties' to share the main\"\n + \" process to FileDownloadService. Or you can configure this value in \"\n + \"'filedownloader.properties' by 'download.min-progress-time'.\");\n }\n }\n\n public static int getMinProgressStep() {\n return minProgressStep;\n }\n\n public static long getMinProgressTime() {\n return minProgressTime;\n }\n\n /**\n * Checks whether the filename looks legitimate.\n */\n @SuppressWarnings({\"SameReturnValue\", \"UnusedParameters\"})\n public static boolean isFilenameValid(String filename) {\n// filename = filename.replaceFirst(\"/+\", \"/\"); // normalize leading\n // slashes\n// return filename.startsWith(Environment.getDownloadCacheDirectory()\n// .toString())\n// || filename.startsWith(Environment\n// .getExternalStorageDirectory().toString());\n return true;\n }\n\n private static String defaultSaveRootPath;\n\n public static String getDefaultSaveRootPath() {\n if (!TextUtils.isEmpty(defaultSaveRootPath)) {\n return defaultSaveRootPath;\n }\n\n boolean useExternalStorage = false;\n if (FileDownloadHelper.getAppContext().getExternalCacheDir() != null) {\n if (Environment.getExternalStorageState().equals(\"mounted\")) {\n if (Environment.getExternalStorageDirectory().getFreeSpace() > 0) {\n useExternalStorage = true;\n }\n }\n }\n\n if (useExternalStorage) {\n return FileDownloadHelper.getAppContext().getExternalCacheDir().getAbsolutePath();\n } else {\n return FileDownloadHelper.getAppContext().getCacheDir().getAbsolutePath();\n }\n }\n\n public static String getDefaultSaveFilePath(final String url) {\n return generateFilePath(getDefaultSaveRootPath(), generateFileName(url));\n }\n\n public static String generateFileName(final String url) {\n return md5(url);\n }\n\n /**\n * @see #getTargetFilePath(String, boolean, String)\n */\n public static String generateFilePath(String directory, String filename) {\n if (filename == null) {\n throw new IllegalStateException(\"can't generate real path, the file name is null\");\n }\n\n if (directory == null) {\n throw new IllegalStateException(\"can't generate real path, the directory is null\");\n }\n\n return formatString(\"%s%s%s\", directory, File.separator, filename);\n }\n\n /**\n * The path is used as the default directory in the case of the task without set path.\n *\n * @param path default root path for save download file.\n * @see com.liulishuo.filedownloader.BaseDownloadTask#setPath(String, boolean)\n */\n public static void setDefaultSaveRootPath(final String path) {\n defaultSaveRootPath = path;\n }\n\n /**\n * @param targetPath The target path for the download task.\n * @return The temp path is {@code targetPath} in downloading status; The temp path is used for\n * storing the file not completed downloaded yet.\n */\n public static String getTempPath(final String targetPath) {\n return FileDownloadUtils.formatString(\"%s.temp\", targetPath);\n }\n\n /**\n * @param url The downloading URL.\n * @param path The absolute file path.\n * @return The download id.\n */\n public static int generateId(final String url, final String path) {\n return CustomComponentHolder.getImpl().getIdGeneratorInstance()\n .generateId(url, path, false);\n }\n\n /**\n * @param url The downloading URL.\n * @param path If {@code pathAsDirectory} is {@code true}, {@code path} would be the absolute\n * directory to place the file;\n * If {@code pathAsDirectory} is {@code false}, {@code path} would be the absolute\n * file path.\n * @return The download id.\n */\n public static int generateId(final String url, final String path,\n final boolean pathAsDirectory) {\n return CustomComponentHolder.getImpl().getIdGeneratorInstance()\n .generateId(url, path, pathAsDirectory);\n }\n\n public static String md5(String string) {\n byte[] hash;\n try {\n hash = MessageDigest.getInstance(\"MD5\").digest(string.getBytes(\"UTF-8\"));\n } catch (NoSuchAlgorithmException e) {\n throw new RuntimeException(\"Huh, MD5 should be supported?\", e);\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(\"Huh, UTF-8 should be supported?\", e);\n }\n\n StringBuilder hex = new StringBuilder(hash.length * 2);\n for (byte b : hash) {\n if ((b & 0xFF) < 0x10) hex.append(\"0\");\n hex.append(Integer.toHexString(b & 0xFF));\n }\n return hex.toString();\n }\n\n\n public static String getStack() {\n return getStack(true);\n }\n\n public static String getStack(final boolean printLine) {\n StackTraceElement[] stackTrace = new Throwable().getStackTrace();\n return getStack(stackTrace, printLine);\n }\n\n public static String getStack(final StackTraceElement[] stackTrace, final boolean printLine) {\n if ((stackTrace == null) || (stackTrace.length < 4)) {\n return \"\";\n }\n\n StringBuilder t = new StringBuilder();\n\n for (int i = 3; i < stackTrace.length; i++) {\n if (!stackTrace[i].getClassName().contains(\"com.liulishuo.filedownloader\")) {\n continue;\n }\n t.append(\"[\");\n t.append(stackTrace[i].getClassName()\n .substring(\"com.liulishuo.filedownloader\".length()));\n t.append(\":\");\n t.append(stackTrace[i].getMethodName());\n if (printLine) {\n t.append(\"(\").append(stackTrace[i].getLineNumber()).append(\")]\");\n } else {\n t.append(\"]\");\n }\n }\n return t.toString();\n }\n\n private static Boolean isDownloaderProcess;\n\n /**\n * @param context the context\n * @return {@code true} if the FileDownloadService is allowed to run on the current process,\n * {@code false} otherwise.\n */\n public static boolean isDownloaderProcess(final Context context) {\n if (isDownloaderProcess != null) {\n return isDownloaderProcess;\n }\n\n boolean result = false;\n do {\n if (FileDownloadProperties.getImpl().processNonSeparate) {\n result = true;\n break;\n }\n\n int pid = android.os.Process.myPid();\n final ActivityManager activityManager = (ActivityManager) context.\n getSystemService(Context.ACTIVITY_SERVICE);\n\n if (activityManager == null) {\n FileDownloadLog.w(FileDownloadUtils.class, \"fail to get the activity manager!\");\n return false;\n }\n\n final List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfoList =\n activityManager.getRunningAppProcesses();\n\n if (null == runningAppProcessInfoList || runningAppProcessInfoList.isEmpty()) {\n FileDownloadLog\n .w(FileDownloadUtils.class, \"The running app process info list from\"\n + \" ActivityManager is null or empty, maybe current App is not \"\n + \"running.\");\n return false;\n }\n\n for (ActivityManager.RunningAppProcessInfo processInfo : runningAppProcessInfoList) {\n if (processInfo.pid == pid) {\n result = processInfo.processName.endsWith(\":filedownloader\");\n break;\n }\n }\n\n } while (false);\n\n isDownloaderProcess = result;\n return isDownloaderProcess;\n }\n\n public static String[] convertHeaderString(final String nameAndValuesString) {\n final String[] lineString = nameAndValuesString.split(\"\\n\");\n final String[] namesAndValues = new String[lineString.length * 2];\n\n for (int i = 0; i < lineString.length; i++) {\n final String[] nameAndValue = lineString[i].split(\": \");\n /**\n * @see Headers#toString()\n * @see Headers#name(int)\n * @see Headers#value(int)\n */\n namesAndValues[i * 2] = nameAndValue[0];\n namesAndValues[i * 2 + 1] = nameAndValue[1];\n }\n\n return namesAndValues;\n }\n\n public static long getFreeSpaceBytes(final String path) {\n long freeSpaceBytes;\n final StatFs statFs = new StatFs(path);\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {\n freeSpaceBytes = statFs.getAvailableBytes();\n } else {\n //noinspection deprecation\n freeSpaceBytes = statFs.getAvailableBlocks() * (long) statFs.getBlockSize();\n }\n\n return freeSpaceBytes;\n }\n\n public static String formatString(final String msg, Object... args) {\n return String.format(Locale.ENGLISH, msg, args);\n }\n\n private static final String INTERNAL_DOCUMENT_NAME = \"filedownloader\";\n private static final String OLD_FILE_CONVERTED_FILE_NAME = \".old_file_converted\";\n\n @SuppressWarnings(\"ResultOfMethodCallIgnored\")\n public static void markConverted(final Context context) {\n final File file = getConvertedMarkedFile(context);\n try {\n file.getParentFile().mkdirs();\n file.createNewFile();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n private static Boolean filenameConverted = null;\n\n /**\n * @return Whether has converted all files' name from 'filename'(in old architecture) to\n * 'filename.temp', if it's in downloading state.\n * <p>\n * If {@code true}, You can check whether the file has completed downloading with\n * {@link File#exists()} directly.\n * <p>\n * when {@link FileDownloadService#onCreate()} is invoked, This value will be assigned to\n * {@code true} only once since you upgrade the filedownloader version to 0.3.3 or higher.\n */\n public static boolean isFilenameConverted(final Context context) {\n if (filenameConverted == null) {\n filenameConverted = getConvertedMarkedFile(context).exists();\n }\n\n return filenameConverted;\n }\n\n public static File getConvertedMarkedFile(final Context context) {\n return new File(context.getFilesDir().getAbsolutePath() + File.separator\n + INTERNAL_DOCUMENT_NAME, OLD_FILE_CONVERTED_FILE_NAME);\n }\n\n // note on https://tools.ietf.org/html/rfc5987\n private static final Pattern CONTENT_DISPOSITION_WITH_ASTERISK_PATTERN =\n Pattern.compile(\"attachment;\\\\s*filename\\\\*\\\\s*=\\\\s*\\\"*([^\\\"]*)'\\\\S*'([^\\\"]*)\\\"*\");\n // note on http://www.ietf.org/rfc/rfc1806.txt\n private static final Pattern CONTENT_DISPOSITION_WITHOUT_ASTERISK_PATTERN =\n Pattern.compile(\"attachment;\\\\s*filename\\\\s*=\\\\s*\\\"*([^\\\"\\\\n]*)\\\"*\");\n\n public static long parseContentRangeFoInstanceLength(String contentRange) {\n if (contentRange == null) return -1;\n\n final String[] session = contentRange.split(\"/\");\n if (session.length >= 2) {\n try {\n return Long.parseLong(session[1]);\n } catch (NumberFormatException e) {\n FileDownloadLog.w(FileDownloadUtils.class, \"parse instance length failed with %s\",\n contentRange);\n }\n }\n\n return -1;\n }\n\n /**\n * The same to com.android.providers.downloads.Helpers#parseContentDisposition.\n * </p>\n * Parse the Content-Disposition HTTP Header. The format of the header\n * is defined here: http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html\n * This header provides a filename for content that is going to be\n * downloaded to the file system. We only support the attachment type.\n */\n public static String parseContentDisposition(String contentDisposition) {\n if (contentDisposition == null) {\n return null;\n }\n\n try {\n Matcher m = CONTENT_DISPOSITION_WITH_ASTERISK_PATTERN.matcher(contentDisposition);\n if (m.find()) {\n String charset = m.group(1);\n String encodeFileName = m.group(2);\n return URLDecoder.decode(encodeFileName, charset);\n }\n\n m = CONTENT_DISPOSITION_WITHOUT_ASTERISK_PATTERN.matcher(contentDisposition);\n if (m.find()) {\n return m.group(1);\n }\n } catch (IllegalStateException | UnsupportedEncodingException ignore) {\n // This function is defined as returning null when it can't parse the header\n }\n return null;\n }\n\n /**\n * @param path If {@code pathAsDirectory} is true, the {@code path} would be the\n * absolute directory to settle down the file;\n * If {@code pathAsDirectory} is false, the {@code path} would be the\n * absolute file path.\n * @param pathAsDirectory whether the {@code path} is a directory.\n * @param filename the file's name.\n * @return the absolute path of the file. If can't find by params, will return {@code null}.\n */\n public static String getTargetFilePath(String path, boolean pathAsDirectory, String filename) {\n if (path == null) {\n return null;\n }\n\n if (pathAsDirectory) {\n if (filename == null) {\n return null;\n }\n\n return FileDownloadUtils.generateFilePath(path, filename);\n } else {\n return path;\n }\n }\n\n /**\n * The same to {@link File#getParent()}, for non-creating a file object.\n *\n * @return this file's parent pathname or {@code null}.\n */\n public static String getParent(final String path) {\n int length = path.length(), firstInPath = 0;\n if (File.separatorChar == '\\\\' && length > 2 && path.charAt(1) == ':') {\n firstInPath = 2;\n }\n int index = path.lastIndexOf(File.separatorChar);\n if (index == -1 && firstInPath > 0) {\n index = 2;\n }\n if (index == -1 || path.charAt(length - 1) == File.separatorChar) {\n return null;\n }\n if (path.indexOf(File.separatorChar) == index\n && path.charAt(firstInPath) == File.separatorChar) {\n return path.substring(0, index + 1);\n }\n return path.substring(0, index);\n }\n\n private static final String FILEDOWNLOADER_PREFIX = \"FileDownloader\";\n\n public static String getThreadPoolName(String name) {\n return FILEDOWNLOADER_PREFIX + \"-\" + name;\n }\n\n public static boolean isNetworkNotOnWifiType() {\n final ConnectivityManager manager = (ConnectivityManager) FileDownloadHelper.getAppContext()\n .\n getSystemService(Context.CONNECTIVITY_SERVICE);\n\n if (manager == null) {\n FileDownloadLog.w(FileDownloadUtils.class, \"failed to get connectivity manager!\");\n return true;\n }\n\n //noinspection MissingPermission, because we check permission accessable when invoked\n final NetworkInfo info = manager.getActiveNetworkInfo();\n\n return info == null || info.getType() != ConnectivityManager.TYPE_WIFI;\n }\n\n public static boolean checkPermission(String permission) {\n final int perm = FileDownloadHelper.getAppContext()\n .checkCallingOrSelfPermission(permission);\n return perm == PackageManager.PERMISSION_GRANTED;\n }\n\n public static long convertContentLengthString(String s) {\n if (s == null) return -1;\n try {\n return Long.parseLong(s);\n } catch (NumberFormatException e) {\n return -1;\n }\n }\n\n public static String findEtag(final int id, FileDownloadConnection connection) {\n if (connection == null) {\n throw new RuntimeException(\"connection is null when findEtag\");\n }\n\n final String newEtag = connection.getResponseHeaderField(\"Etag\");\n\n if (FileDownloadLog.NEED_LOG) {\n FileDownloadLog.d(FileDownloadUtils.class, \"etag find %s for task(%d)\", newEtag, id);\n }\n\n return newEtag;\n }\n\n // accept range is effect by response code and Accept-Ranges header field.\n public static boolean isAcceptRange(int responseCode, FileDownloadConnection connection) {\n if (responseCode == HttpURLConnection.HTTP_PARTIAL\n || responseCode == FileDownloadConnection.RESPONSE_CODE_FROM_OFFSET) return true;\n\n final String acceptRanges = connection.getResponseHeaderField(\"Accept-Ranges\");\n return \"bytes\".equals(acceptRanges);\n }\n\n // because of we using one of two HEAD method to request or using range:0-0 to trial connection\n // only if connection api not support, so we test content-range first and then test\n // content-length.\n public static long findInstanceLengthForTrial(FileDownloadConnection connection) {\n long length = findInstanceLengthFromContentRange(connection);\n if (length < 0) {\n length = TOTAL_VALUE_IN_CHUNKED_RESOURCE;\n FileDownloadLog.w(FileDownloadUtils.class, \"don't get instance length from\"\n + \"Content-Range header\");\n }\n // the response of HEAD method is not very canonical sometimes(it depends on server\n // implementation)\n // so that it's uncertain the content-length is the same as the response of GET method if\n // content-length=0, so we have to filter this case in here.\n if (length == 0 && FileDownloadProperties.getImpl().trialConnectionHeadMethod) {\n length = TOTAL_VALUE_IN_CHUNKED_RESOURCE;\n }\n\n return length;\n }\n\n public static long findInstanceLengthFromContentRange(FileDownloadConnection connection) {\n return parseContentRangeFoInstanceLength(getContentRangeHeader(connection));\n }\n\n private static String getContentRangeHeader(FileDownloadConnection connection) {\n return connection.getResponseHeaderField(\"Content-Range\");\n }\n\n public static long findContentLength(final int id, FileDownloadConnection connection) {\n long contentLength = convertContentLengthString(\n connection.getResponseHeaderField(\"Content-Length\"));\n final String transferEncoding = connection.getResponseHeaderField(\"Transfer-Encoding\");\n\n if (contentLength < 0) {\n final boolean isEncodingChunked = transferEncoding != null && transferEncoding\n .equals(\"chunked\");\n if (!isEncodingChunked) {\n // not chunked transfer encoding data\n if (FileDownloadProperties.getImpl().httpLenient) {\n // do not response content-length either not chunk transfer encoding,\n // but HTTP lenient is true, so handle as the case of transfer encoding chunk\n contentLength = TOTAL_VALUE_IN_CHUNKED_RESOURCE;\n if (FileDownloadLog.NEED_LOG) {\n FileDownloadLog\n .d(FileDownloadUtils.class, \"%d response header is not legal but \"\n + \"HTTP lenient is true, so handle as the case of \"\n + \"transfer encoding chunk\", id);\n }\n } else {\n throw new FileDownloadGiveUpRetryException(\"can't know the size of the \"\n + \"download file, and its Transfer-Encoding is not Chunked \"\n + \"either.\\nyou can ignore such exception by add \"\n + \"http.lenient=true to the filedownloader.properties\");\n }\n } else {\n contentLength = TOTAL_VALUE_IN_CHUNKED_RESOURCE;\n }\n }\n\n return contentLength;\n }\n\n public static long findContentLengthFromContentRange(FileDownloadConnection connection) {\n final String contentRange = getContentRangeHeader(connection);\n long contentLength = parseContentLengthFromContentRange(contentRange);\n if (contentLength < 0) contentLength = TOTAL_VALUE_IN_CHUNKED_RESOURCE;\n return contentLength;\n }\n\n public static long parseContentLengthFromContentRange(String contentRange) {\n if (contentRange == null || contentRange.length() == 0) return -1;\n final String pattern = \"bytes (\\\\d+)-(\\\\d+)/\\\\d+\";\n try {\n final Pattern r = Pattern.compile(pattern);\n final Matcher m = r.matcher(contentRange);\n if (m.find()) {\n final long rangeStart = Long.parseLong(m.group(1));\n final long rangeEnd = Long.parseLong(m.group(2));\n return rangeEnd - rangeStart + 1;\n }\n } catch (Exception e) {\n FileDownloadLog.e(FileDownloadUtils.class, e, \"parse content length\"\n + \" from content range error\");\n }\n return -1;\n }\n\n public static String findFilename(FileDownloadConnection connection, String url)\n throws FileDownloadSecurityException {\n String filename = FileDownloadUtils.parseContentDisposition(connection.\n getResponseHeaderField(\"Content-Disposition\"));\n\n if (TextUtils.isEmpty(filename)) {\n filename = findFileNameFromUrl(url);\n }\n\n if (TextUtils.isEmpty(filename)) {\n filename = FileDownloadUtils.generateFileName(url);\n } else if (filename.contains(\"../\")) {\n throw new FileDownloadSecurityException(FileDownloadUtils.formatString(\n \"The filename [%s] from the response is not allowable, because it contains \"\n + \"'../', which can raise the directory traversal vulnerability\",\n filename));\n }\n\n return filename;\n }\n\n public static FileDownloadOutputStream createOutputStream(final String path)\n throws IOException {\n\n if (TextUtils.isEmpty(path)) {\n throw new RuntimeException(\"found invalid internal destination path, empty\");\n }\n\n //noinspection ConstantConditions\n if (!FileDownloadUtils.isFilenameValid(path)) {\n throw new RuntimeException(\n FileDownloadUtils.formatString(\"found invalid internal destination filename\"\n + \" %s\", path));\n }\n\n File file = new File(path);\n\n if (file.exists() && file.isDirectory()) {\n throw new RuntimeException(\n FileDownloadUtils.formatString(\"found invalid internal destination path[%s],\"\n + \" & path is directory[%B]\", path, file.isDirectory()));\n }\n if (!file.exists()) {\n if (!file.createNewFile()) {\n throw new IOException(\n FileDownloadUtils.formatString(\"create new file error %s\",\n file.getAbsolutePath()));\n }\n }\n\n return CustomComponentHolder.getImpl().createOutputStream(file);\n }\n\n public static boolean isBreakpointAvailable(final int id, final FileDownloadModel model) {\n return isBreakpointAvailable(id, model, null);\n }\n\n /**\n * @return can resume by break point\n */\n public static boolean isBreakpointAvailable(final int id, final FileDownloadModel model,\n final Boolean outputStreamSupportSeek) {\n if (model == null) {\n if (FileDownloadLog.NEED_LOG) {\n FileDownloadLog.d(FileDownloadUtils.class, \"can't continue %d model == null\", id);\n }\n return false;\n }\n\n if (model.getTempFilePath() == null) {\n if (FileDownloadLog.NEED_LOG) {\n FileDownloadLog\n .d(FileDownloadUtils.class, \"can't continue %d temp path == null\", id);\n }\n return false;\n }\n\n return isBreakpointAvailable(id, model, model.getTempFilePath(), outputStreamSupportSeek);\n }\n\n public static boolean isBreakpointAvailable(final int id, final FileDownloadModel model,\n final String path,\n final Boolean outputStreamSupportSeek) {\n boolean result = false;\n\n do {\n if (path == null) {\n if (FileDownloadLog.NEED_LOG) {\n FileDownloadLog.d(FileDownloadUtils.class, \"can't continue %d path = null\", id);\n }\n break;\n }\n\n File file = new File(path);\n final boolean isExists = file.exists();\n final boolean isDirectory = file.isDirectory();\n\n if (!isExists || isDirectory) {\n if (FileDownloadLog.NEED_LOG) {\n FileDownloadLog.d(FileDownloadUtils.class,\n \"can't continue %d file not suit, exists[%B], directory[%B]\",\n id, isExists, isDirectory);\n }\n break;\n }\n\n final long fileLength = file.length();\n final long currentOffset = model.getSoFar();\n\n if (model.getConnectionCount() <= 1 && currentOffset == 0) {\n // the sofar is stored on connection table\n if (FileDownloadLog.NEED_LOG) {\n FileDownloadLog.d(FileDownloadUtils.class,\n \"can't continue %d the downloaded-record is zero.\",\n id);\n }\n break;\n }\n\n final long totalLength = model.getTotal();\n if (fileLength < currentOffset\n || (totalLength != TOTAL_VALUE_IN_CHUNKED_RESOURCE // not chunk transfer\n && (fileLength > totalLength || currentOffset >= totalLength))\n ) {\n // dirty data.\n if (FileDownloadLog.NEED_LOG) {\n FileDownloadLog.d(FileDownloadUtils.class, \"can't continue %d dirty data\"\n + \" fileLength[%d] sofar[%d] total[%d]\",\n id, fileLength, currentOffset, totalLength);\n }\n break;\n }\n\n if (outputStreamSupportSeek != null && !outputStreamSupportSeek\n && totalLength == fileLength) {\n if (FileDownloadLog.NEED_LOG) {\n FileDownloadLog.d(FileDownloadUtils.class, \"can't continue %d, because of the \"\n + \"output stream doesn't support seek, but the task has \"\n + \"already pre-allocated, so we only can download it from the\"\n + \" very beginning.\",\n id);\n }\n break;\n }\n\n result = true;\n } while (false);\n\n\n return result;\n }\n\n public static void deleteTaskFiles(String targetFilepath, String tempFilePath) {\n deleteTempFile(tempFilePath);\n deleteTargetFile(targetFilepath);\n }\n\n public static void deleteTempFile(String tempFilePath) {\n if (tempFilePath != null) {\n final File tempFile = new File(tempFilePath);\n if (tempFile.exists()) {\n //noinspection ResultOfMethodCallIgnored\n tempFile.delete();\n }\n }\n }\n\n public static void deleteTargetFile(String targetFilePath) {\n if (targetFilePath != null) {\n final File targetFile = new File(targetFilePath);\n if (targetFile.exists()) {\n //noinspection ResultOfMethodCallIgnored\n targetFile.delete();\n }\n }\n }\n\n public static boolean isNeedSync(long bytesDelta, long timestampDelta) {\n return bytesDelta > FileDownloadUtils.getMinProgressStep()\n && timestampDelta > FileDownloadUtils.getMinProgressTime();\n }\n\n public static String defaultUserAgent() {\n return formatString(\"FileDownloader/%s\", BuildConfig.VERSION_NAME);\n }\n\n private static boolean isAppOnForeground(Context context) {\n ActivityManager activityManager = (ActivityManager) context.getApplicationContext()\n .getSystemService(Context.ACTIVITY_SERVICE);\n if (activityManager == null) return false;\n\n List<ActivityManager.RunningAppProcessInfo> appProcesses =\n activityManager.getRunningAppProcesses();\n if (appProcesses == null) return false;\n\n PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);\n if (pm == null) return false;\n if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {\n if (!pm.isInteractive()) return false;\n } else {\n if (!pm.isScreenOn()) return false;\n }\n\n String packageName = context.getApplicationContext().getPackageName();\n for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {\n // The name of the process that this object is associated with.\n if (appProcess.processName.equals(packageName) && appProcess.importance\n == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {\n return true;\n }\n\n }\n return false;\n }\n\n public static boolean needMakeServiceForeground(Context context) {\n return Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && !isAppOnForeground(context);\n }\n\n static String findFileNameFromUrl(String url) {\n if (url == null || url.isEmpty()) {\n return null;\n }\n try {\n final URL parseUrl = new URL(url);\n final String path = parseUrl.getPath();\n String fileName = path.substring(path.lastIndexOf('/') + 1);\n if (fileName.isEmpty()) return null;\n return fileName;\n } catch (MalformedURLException ignore) {\n }\n return null;\n }\n}" ]
import java.util.ArrayList; import java.util.List; import android.app.Notification; import android.content.Context; import android.content.Intent; import android.os.Build; import com.liulishuo.filedownloader.event.DownloadServiceConnectChangedEvent; import com.liulishuo.filedownloader.model.FileDownloadHeader; import com.liulishuo.filedownloader.services.FDServiceSharedHandler; import com.liulishuo.filedownloader.services.FDServiceSharedHandler.FileDownloadServiceSharedConnection; import com.liulishuo.filedownloader.services.FileDownloadService.SharedMainProcessService; import com.liulishuo.filedownloader.util.DownloadServiceNotConnectedHelper; import com.liulishuo.filedownloader.util.ExtraKeys; import com.liulishuo.filedownloader.util.FileDownloadLog; import com.liulishuo.filedownloader.util.FileDownloadUtils;
/* * Copyright (c) 2015 LingoChamp Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.liulishuo.filedownloader; /** * This transmit layer is used for the FileDownloader-Process is shared the main process. * <p/> * If you want use this transmit and want the FileDownloadService share the main process, not in the * separate process, just add a command `process.non-separate=true` in `/filedownloader.properties`. * * @see FileDownloadServiceUIGuard */ class FileDownloadServiceSharedTransmit implements IFileDownloadServiceProxy, FileDownloadServiceSharedConnection { private static final Class<?> SERVICE_CLASS = SharedMainProcessService.class; private boolean runServiceForeground = false; @Override public boolean start(String url, String path, boolean pathAsDirectory, int callbackProgressTimes, int callbackProgressMinIntervalMillis, int autoRetryTimes, boolean forceReDownload, FileDownloadHeader header, boolean isWifiRequired) { if (!isConnected()) { return DownloadServiceNotConnectedHelper.start(url, path, pathAsDirectory); } handler.start(url, path, pathAsDirectory, callbackProgressTimes, callbackProgressMinIntervalMillis, autoRetryTimes, forceReDownload, header, isWifiRequired); return true; } @Override public boolean pause(int id) { if (!isConnected()) { return DownloadServiceNotConnectedHelper.pause(id); } return handler.pause(id); } @Override public boolean isDownloading(String url, String path) { if (!isConnected()) { return DownloadServiceNotConnectedHelper.isDownloading(url, path); } return handler.checkDownloading(url, path); } @Override public long getSofar(int id) { if (!isConnected()) { return DownloadServiceNotConnectedHelper.getSofar(id); } return handler.getSofar(id); } @Override public long getTotal(int id) { if (!isConnected()) { return DownloadServiceNotConnectedHelper.getTotal(id); } return handler.getTotal(id); } @Override public byte getStatus(int id) { if (!isConnected()) { return DownloadServiceNotConnectedHelper.getStatus(id); } return handler.getStatus(id); } @Override public void pauseAllTasks() { if (!isConnected()) { DownloadServiceNotConnectedHelper.pauseAllTasks(); return; } handler.pauseAllTasks(); } @Override public boolean isIdle() { if (!isConnected()) { return DownloadServiceNotConnectedHelper.isIdle(); } return handler.isIdle(); } @Override public boolean isConnected() { return handler != null; } @Override public void bindStartByContext(Context context) { bindStartByContext(context, null); } private final ArrayList<Runnable> connectedRunnableList = new ArrayList<>(); @Override public void bindStartByContext(Context context, Runnable connectedRunnable) { if (connectedRunnable != null) { if (!connectedRunnableList.contains(connectedRunnable)) { connectedRunnableList.add(connectedRunnable); } } Intent i = new Intent(context, SERVICE_CLASS); runServiceForeground = FileDownloadUtils.needMakeServiceForeground(context); i.putExtra(ExtraKeys.IS_FOREGROUND, runServiceForeground); if (runServiceForeground) {
if (FileDownloadLog.NEED_LOG) FileDownloadLog.d(this, "start foreground service");
7
guiying712/AndroidModulePattern
module_girls/src/main/java/com/guiying/module/girls/data/source/RemoteGirlsDataSource.java
[ "public class DataType {\n\n /*返回数据为String*/\n public static final int STRING = 1;\n /*返回数据为xml类型*/\n public static final int XML = 2;\n /*返回数据为json对象*/\n public static final int JSON_OBJECT = 3;\n /*返回数据为json数组*/\n public static final int JSON_ARRAY = 4;\n\n /**\n * 自定义一个播放器状态注解\n */\n @Retention(RetentionPolicy.SOURCE)\n @IntDef({STRING, XML, JSON_OBJECT, JSON_ARRAY})\n public @interface Type {\n }\n\n}", "public class HttpClient {\n\n /*The certificate's password*/\n private static final String STORE_PASS = \"6666666\";\n private static final String STORE_ALIAS = \"666666\";\n /*用户设置的BASE_URL*/\n private static String BASE_URL = \"\";\n /*本地使用的baseUrl*/\n private String baseUrl = \"\";\n private static OkHttpClient okHttpClient;\n private Builder mBuilder;\n private Retrofit retrofit;\n private Call<ResponseBody> mCall;\n private static final Map<String, Call> CALL_MAP = new HashMap<>();\n\n /**\n * 获取HttpClient的单例\n *\n * @return HttpClient的唯一对象\n */\n private static HttpClient getIns() {\n return HttpClientHolder.sInstance;\n }\n\n /**\n * 单例模式中的静态内部类写法\n */\n private static class HttpClientHolder {\n private static final HttpClient sInstance = new HttpClient();\n }\n\n private HttpClient() {\n ClearableCookieJar cookieJar = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(Utils.getContext()));\n //HttpsUtil.SSLParams sslParams = HttpsUtil.getSslSocketFactory(Utils.getContext(), R.raw.cer,STORE_PASS , STORE_ALIAS);\n okHttpClient = new OkHttpClient.Builder()\n .connectTimeout(10000L, TimeUnit.MILLISECONDS)\n //.sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)\n // .hostnameVerifier(HttpsUtil.getHostnameVerifier())\n .addInterceptor(new LoggerInterceptor(null, true))\n .cookieJar(cookieJar)\n .build();\n }\n\n public Builder getBuilder() {\n return mBuilder;\n }\n\n private void setBuilder(Builder builder) {\n this.mBuilder = builder;\n }\n\n /**\n * 获取的Retrofit的实例,\n * 引起Retrofit变化的因素只有静态变量BASE_URL的改变。\n */\n private void getRetrofit() {\n if (!BASE_URL.equals(baseUrl) || retrofit == null) {\n baseUrl = BASE_URL;\n retrofit = new Retrofit.Builder()\n .baseUrl(baseUrl)\n .client(okHttpClient)\n .build();\n }\n }\n\n public void post(final OnResultListener onResultListener) {\n Builder builder = mBuilder;\n mCall = retrofit.create(ApiService.class)\n .executePost(builder.url, builder.params);\n putCall(builder, mCall);\n request(builder, onResultListener);\n }\n\n\n public void get(final OnResultListener onResultListener) {\n Builder builder = mBuilder;\n if (!builder.params.isEmpty()) {\n String value = \"\";\n for (Map.Entry<String, String> entry : builder.params.entrySet()) {\n String mapKey = entry.getKey();\n String mapValue = entry.getValue();\n String span = value.equals(\"\") ? \"\" : \"&\";\n String part = StringUtils.buffer(span, mapKey, \"=\", mapValue);\n value = StringUtils.buffer(value, part);\n }\n builder.url(StringUtils.buffer(builder.url, \"?\", value));\n }\n mCall = retrofit.create(ApiService.class).executeGet(builder.url);\n putCall(builder, mCall);\n request(builder, onResultListener);\n }\n\n\n private void request(final Builder builder, final OnResultListener onResultListener) {\n if (!NetworkUtils.isConnected()) {\n ToastUtils.showLongToastSafe(R.string.current_internet_invalid);\n onResultListener.onFailure(Utils.getString(R.string.current_internet_invalid));\n return;\n }\n mCall.enqueue(new Callback<ResponseBody>() {\n @Override\n public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {\n if (200 == response.code()) {\n try {\n String result = response.body().string();\n parseData(result, builder.clazz, builder.bodyType, onResultListener);\n } catch (IOException | IllegalStateException e) {\n e.printStackTrace();\n }\n }\n if (!response.isSuccessful() || 200 != response.code()) {\n onResultListener.onError(response.code(), response.message());\n }\n if (null != builder.tag) {\n removeCall(builder.url);\n }\n }\n\n @Override\n public void onFailure(Call<ResponseBody> call, Throwable t) {\n t.printStackTrace();\n onResultListener.onFailure(t.getMessage());\n if (null != builder.tag) {\n removeCall(builder.url);\n }\n }\n\n });\n }\n\n\n /**\n * 添加某个请求\n */\n private synchronized void putCall(Builder builder, Call call) {\n if (builder.tag == null)\n return;\n synchronized (CALL_MAP) {\n CALL_MAP.put(builder.tag.toString() + builder.url, call);\n }\n }\n\n\n /**\n * 取消某个界面都所有请求,或者是取消某个tag的所有请求;\n * 如果要取消某个tag单独请求,tag需要传入tag+url\n *\n * @param tag 请求标签\n */\n public synchronized void cancel(Object tag) {\n if (tag == null)\n return;\n List<String> list = new ArrayList<>();\n synchronized (CALL_MAP) {\n for (String key : CALL_MAP.keySet()) {\n if (key.startsWith(tag.toString())) {\n CALL_MAP.get(key).cancel();\n list.add(key);\n }\n }\n }\n for (String s : list) {\n removeCall(s);\n }\n\n }\n\n /**\n * 移除某个请求\n *\n * @param url 添加的url\n */\n private synchronized void removeCall(String url) {\n synchronized (CALL_MAP) {\n for (String key : CALL_MAP.keySet()) {\n if (key.contains(url)) {\n url = key;\n break;\n }\n }\n CALL_MAP.remove(url);\n }\n }\n\n /**\n * Build a new HttpClient.\n * url is required before calling. All other methods are optional.\n */\n public static final class Builder {\n private String builderBaseUrl = \"\";\n private String url;\n private Object tag;\n private Map<String, String> params = new HashMap<>();\n /*返回数据的类型,默认是string类型*/\n @DataType.Type\n private int bodyType = DataType.STRING;\n /*解析类*/\n private Class clazz;\n\n public Builder() {\n }\n\n /**\n * 请求地址的baseUrl,最后会被赋值给HttpClient的静态变量BASE_URL;\n *\n * @param baseUrl 请求地址的baseUrl\n */\n public Builder baseUrl(String baseUrl) {\n this.builderBaseUrl = baseUrl;\n return this;\n }\n\n /**\n * 除baseUrl以外的部分,\n * 例如:\"mobile/login\"\n *\n * @param url path路径\n */\n public Builder url(String url) {\n this.url = url;\n return this;\n }\n\n /**\n * 给当前网络请求添加标签,用于取消这个网络请求\n *\n * @param tag 标签\n */\n public Builder tag(Object tag) {\n this.tag = tag;\n return this;\n }\n\n /**\n * 添加请求参数\n *\n * @param key 键\n * @param value 值\n */\n public Builder params(String key, String value) {\n this.params.put(key, value);\n return this;\n }\n\n /**\n * 响应体类型设置,如果要响应体类型为STRING,请不要使用这个方法\n *\n * @param bodyType 响应体类型,分别:STRING,JSON_OBJECT,JSON_ARRAY,XML\n * @param clazz 指定的解析类\n * @param <T> 解析类\n */\n public <T> Builder bodyType(@DataType.Type int bodyType, @NonNull Class<T> clazz) {\n this.bodyType = bodyType;\n this.clazz = clazz;\n return this;\n }\n\n public HttpClient build() {\n if (!TextUtils.isEmpty(builderBaseUrl)) {\n BASE_URL = builderBaseUrl;\n }\n HttpClient client = HttpClient.getIns();\n client.getRetrofit();\n client.setBuilder(this);\n return client;\n }\n }\n\n /**\n * 数据解析方法\n *\n * @param data 要解析的数据\n * @param clazz 解析类\n * @param bodyType 解析数据类型\n * @param onResultListener 回调方数据接口\n */\n @SuppressWarnings(\"unchecked\")\n private void parseData(String data, Class clazz, @DataType.Type int bodyType, OnResultListener onResultListener) {\n switch (bodyType) {\n case DataType.STRING:\n onResultListener.onSuccess(data);\n break;\n case DataType.JSON_OBJECT:\n onResultListener.onSuccess(DataParseUtil.parseObject(data, clazz));\n break;\n case DataType.JSON_ARRAY:\n onResultListener.onSuccess(DataParseUtil.parseToArrayList(data, clazz));\n break;\n case DataType.XML:\n onResultListener.onSuccess(DataParseUtil.parseXml(data, clazz));\n break;\n default:\n Logger.e(\"http parse tip:\", \"if you want return object, please use bodyType() set data type\");\n break;\n }\n }\n\n}", "public class OnResultListener<T> {\n\n /**\n * 请求成功的情况\n *\n * @param result 需要解析的解析类\n */\n public void onSuccess(T result) {\n }\n\n /**\n * 响应成功,但是出错的情况\n *\n * @param code 错误码\n * @param message 错误信息\n */\n public void onError(int code, String message) {\n }\n\n /**\n * 请求失败的情况\n *\n * @param message 失败信息\n */\n public void onFailure(String message) {\n }\n\n}", "public interface Constants {\n\n /**\n * http://gank.io/api/data/福利/10/1\n */\n String GAN_HUO_API = \"http://gank.io/api/data/\";\n\n String INTENT_GIRLS = \"girls\";\n String INTENT_INDEX = \"index\";\n\n}", "public interface GirlsDataSource {\n\n interface LoadGirlsCallback {\n\n void onGirlsLoaded(GirlsParser girlsParser);\n\n void onDataNotAvailable();\n }\n\n void getGirls(int size, int page, LoadGirlsCallback callback);\n\n}", "public class GirlsParser {\n\n /**\n * error : false\n * results : [{\"_id\":\"5771d5eb421aa931ddcc50d6\",\"createdAt\":\"2016-06-28T09:42:03.761Z\",\"desc\":\"Dagger2图文完全教程\",\"publishedAt\":\"2016-06-28T11:33:25.276Z\",\"source\":\"web\",\"type\":\"Android\",\"url\":\"https://github.com/luxiaoming/dagger2Demo\",\"used\":true,\"who\":\"代码GG陆晓明\"},{\"_id\":\"5771c9ca421aa931ca5a7e59\",\"createdAt\":\"2016-06-28T08:50:18.731Z\",\"desc\":\"Android Design 设计模板\",\"publishedAt\":\"2016-06-28T11:33:25.276Z\",\"source\":\"chrome\",\"type\":\"Android\",\"url\":\"https://github.com/andreasschrade/android-design-template\",\"used\":true,\"who\":\"代码家\"}]\n */\n\n private boolean error;\n /**\n * _id : 5771d5eb421aa931ddcc50d6\n * createdAt : 2016-06-28T09:42:03.761Z\n * desc : Dagger2图文完全教程\n * publishedAt : 2016-06-28T11:33:25.276Z\n * source : web\n * type : Android\n * url : https://github.com/luxiaoming/dagger2Demo\n * used : true\n * who : 代码GG陆晓明\n */\n\n private List<Girls> results;\n\n public void setError(boolean error) {\n this.error = error;\n }\n\n public void setResults(List<Girls> results) {\n this.results = results;\n }\n\n public boolean isError() {\n return error;\n }\n\n public List<Girls> getResults() {\n return results;\n }\n\n\n}" ]
import com.guiying.module.common.http.DataType; import com.guiying.module.common.http.HttpClient; import com.guiying.module.common.http.OnResultListener; import com.guiying.module.girls.Constants; import com.guiying.module.girls.data.GirlsDataSource; import com.guiying.module.girls.data.bean.GirlsParser;
package com.guiying.module.girls.data.source; public class RemoteGirlsDataSource implements GirlsDataSource { @Override public void getGirls(int size, int page, final LoadGirlsCallback callback) { HttpClient client = new HttpClient.Builder() .baseUrl(Constants.GAN_HUO_API) .url("福利/" + size + "/" + page)
.bodyType(DataType.JSON_OBJECT, GirlsParser.class)
5
iychoi/libra
src/libra/merge/Merge.java
[ "public class CommandArgumentsParser<T extends CommandArgumentsBase> {\n public boolean parse(String[] args, T cmdargs) {\n CmdLineParser parser = new CmdLineParser(cmdargs);\n CmdLineException parseException = null;\n try {\n parser.parseArgument(args);\n } catch (CmdLineException e) {\n // handling of wrong arguments\n parseException = e;\n }\n \n if(cmdargs.isHelp() || !cmdargs.checkValidity()) {\n parser.printUsage(System.err);\n return false;\n }\n \n if(parseException != null) {\n System.err.println(parseException.getMessage());\n parser.printUsage(System.err);\n return false;\n }\n return true;\n }\n}", "public class MergeConfig {\n \n public static final String DEFAULT_OUTPUT_PATH = \"./libra_merge_output\";\n public static final int DEFAULT_TASKNUM = PreprocessorConfig.DEFAULT_TASKNUM; // use system default\n \n private static final String HADOOP_CONFIG_KEY = \"libra.merge.common.mergeconfig\";\n \n private String reportFilePath;\n \n private int taskNum = DEFAULT_TASKNUM;\n private String fileTablePath;\n private String kmerIndexPath;\n private String kmerStatisticsPath;\n private String outputPath = DEFAULT_OUTPUT_PATH;\n \n private List<FileTable> fileTables = new ArrayList<FileTable>();\n \n public static MergeConfig createInstance(File file) throws IOException {\n JsonSerializer serializer = new JsonSerializer();\n return (MergeConfig) serializer.fromJsonFile(file, MergeConfig.class);\n }\n \n public static MergeConfig createInstance(String json) throws IOException {\n JsonSerializer serializer = new JsonSerializer();\n return (MergeConfig) serializer.fromJson(json, MergeConfig.class);\n }\n \n public static MergeConfig createInstance(Configuration conf) throws IOException {\n JsonSerializer serializer = new JsonSerializer();\n return (MergeConfig) serializer.fromJsonConfiguration(conf, HADOOP_CONFIG_KEY, MergeConfig.class);\n }\n \n public static MergeConfig createInstance(FileSystem fs, Path file) throws IOException {\n JsonSerializer serializer = new JsonSerializer();\n return (MergeConfig) serializer.fromJsonFile(fs, file, MergeConfig.class);\n }\n \n public MergeConfig() {\n \n }\n\n @JsonIgnore\n public void setPreprocessRootPath(String preprocessRootPath) {\n this.fileTablePath = FileTableHelper.makeFileTableDirPath(preprocessRootPath);\n this.kmerIndexPath = KmerIndexHelper.makeKmerIndexDirPath(preprocessRootPath);\n this.kmerStatisticsPath = KmerStatisticsHelper.makeKmerStatisticsDirPath(preprocessRootPath);\n }\n \n @JsonProperty(\"task_num\")\n public int getTaskNum() {\n return this.taskNum;\n }\n \n @JsonProperty(\"task_num\")\n public void setTaskNum(int taskNum) {\n this.taskNum = taskNum;\n }\n \n @JsonProperty(\"file_table_path\")\n public String getFileTablePath() {\n return this.fileTablePath;\n }\n \n @JsonProperty(\"file_table_path\")\n public void setFileTablePath(String fileTablePath) {\n this.fileTablePath = fileTablePath;\n }\n \n @JsonProperty(\"kmer_index_path\")\n public String getKmerIndexPath() {\n return this.kmerIndexPath;\n }\n \n @JsonProperty(\"kmer_index_path\")\n public void setKmerIndexPath(String kmerIndexPath) {\n this.kmerIndexPath = kmerIndexPath;\n }\n \n @JsonProperty(\"statistics_path\")\n public String getKmerStatisticsPath() {\n return this.kmerStatisticsPath;\n }\n \n @JsonProperty(\"statistics_path\")\n public void setKmerStatisticsPath(String kmerStatisticsPath) {\n this.kmerStatisticsPath = kmerStatisticsPath;\n }\n \n @JsonProperty(\"output_path\")\n public void setOutputPath(String outputPath) {\n this.outputPath = outputPath;\n }\n \n @JsonProperty(\"output_path\")\n public String getOutputPath() {\n return this.outputPath;\n }\n \n @JsonProperty(\"report_path\")\n public void setReportPath(String reportFilePath) {\n this.reportFilePath = reportFilePath;\n }\n \n @JsonProperty(\"report_path\")\n public String getReportPath() {\n return this.reportFilePath;\n }\n \n @JsonProperty(\"file_table\")\n public Collection<FileTable> getFileTables() {\n return this.fileTables;\n }\n \n @JsonProperty(\"file_table\")\n public void addFileTables(Collection<FileTable> fileTable) {\n this.fileTables.addAll(fileTable);\n }\n \n @JsonIgnore\n public void addFileTable(FileTable fileTable) {\n this.fileTables.add(fileTable);\n }\n \n @JsonIgnore\n public void saveTo(Configuration conf) throws IOException {\n JsonSerializer serializer = new JsonSerializer();\n serializer.toJsonConfiguration(conf, HADOOP_CONFIG_KEY, this);\n }\n \n @JsonIgnore\n public void saveTo(FileSystem fs, Path file) throws IOException {\n JsonSerializer serializer = new JsonSerializer();\n serializer.toJsonFile(fs, file, this);\n }\n}", "public class MergeMap {\n private static final Log LOG = LogFactory.getLog(MergeMap.class);\n \n private static final int DEFAULT_INPUT_SPLITS = 100;\n \n public MergeMap() {\n \n }\n \n private void validateMergeConfig(MergeConfig mConfig) throws MergeConfigException {\n if(mConfig.getKmerIndexPath() == null) {\n throw new MergeConfigException(\"cannot find input kmer index path\");\n }\n \n if(mConfig.getFileTables() == null || mConfig.getFileTables().size() <= 0) {\n throw new MergeConfigException(\"cannot find input path\");\n }\n \n if(mConfig.getKmerStatisticsPath() == null) {\n throw new MergeConfigException(\"cannot find kmer statistics path\");\n }\n \n if(mConfig.getOutputPath() == null) {\n throw new MergeConfigException(\"cannot find output path\");\n }\n }\n \n public int runJob(Configuration conf, MergeConfig mConfig) throws Exception {\n // check config\n validateMergeConfig(mConfig);\n \n Job job = Job.getInstance(conf, \"Libra - Mergeing preprocessed results\");\n conf = job.getConfiguration();\n \n // set user configuration\n mConfig.saveTo(conf);\n \n Report report = new Report();\n \n job.setJarByClass(MergeMap.class);\n \n // Mapper\n job.setMapperClass(MergeMapper.class);\n job.setInputFormatClass(KmerMatchInputFormat.class);\n job.setMapOutputKeyClass(CompressedSequenceWritable.class);\n job.setMapOutputValueClass(IntArrayWritable.class);\n \n // Specify key / value\n job.setOutputKeyClass(CompressedSequenceWritable.class);\n job.setOutputValueClass(IntArrayWritable.class);\n\n // Inputs\n List<Path> inputFileTableFiles = new ArrayList<Path>();\n for(FileTable fileTable : mConfig.getFileTables()) {\n String fileTableFileName = FileTableHelper.makeFileTableFileName(fileTable.getName());\n Path fileTableFilePath = new Path(mConfig.getFileTablePath(), fileTableFileName);\n inputFileTableFiles.add(fileTableFilePath);\n }\n \n KmerMatchInputFormat.addInputPaths(job, FileSystemHelper.makeCommaSeparated(inputFileTableFiles.toArray(new Path[0])));\n\n LOG.info(\"Input file table files : \" + inputFileTableFiles.size());\n for(Path inputFile : inputFileTableFiles) {\n LOG.info(\"> \" + inputFile.toString());\n }\n \n KmerMatchFileMapping fileMapping = new KmerMatchFileMapping();\n for(FileTable fileTable : mConfig.getFileTables()) {\n for(String sample : fileTable.getSamples()) {\n fileMapping.addSampleFile(sample);\n }\n }\n fileMapping.saveTo(conf);\n \n int kmerSize = 0;\n Iterator<FileTable> iterator = mConfig.getFileTables().iterator();\n if(iterator.hasNext()) {\n FileTable tbl = iterator.next();\n kmerSize = tbl.getKmerSize();\n }\n \n int tasks = DEFAULT_INPUT_SPLITS;\n if(mConfig.getTaskNum() > 0) {\n tasks = mConfig.getTaskNum();\n }\n \n KmerMatchInputFormatConfig matchInputFormatConfig = new KmerMatchInputFormatConfig();\n matchInputFormatConfig.setKmerSize(kmerSize);\n matchInputFormatConfig.setFileTablePath(mConfig.getFileTablePath());\n matchInputFormatConfig.setKmerIndexPath(mConfig.getKmerIndexPath());\n \n KmerMatchInputFormat.setInputFormatConfig(job, matchInputFormatConfig);\n \n // output\n String tempOutputPath = mConfig.getOutputPath() + \"_temp\";\n FileOutputFormat.setOutputPath(job, new Path(tempOutputPath));\n job.setOutputFormatClass(MapFileOutputFormat.class);\n\n // Reducer\n job.setNumReduceTasks(0);\n \n // Execute job and return status\n boolean result = job.waitForCompletion(true);\n\n // commit results\n if(result) {\n //commit(mConfig.getFileTables(), new Path(tempOutputPath), new Path(mConfig.getOutputPath()), conf);\n \n // create index of index\n //createIndexTable(new Path(ppConfig.getKmerIndexPath()), ppConfig.getFileTables(), conf);\n \n // create statistics of index\n //createStatistics(new Path(ppConfig.getKmerStatisticsPath()), ppConfig.getFileTables(), conf);\n \n \n //commit(new Path(mConfig.getOutputPath()), conf);\n /*\n // create a file mapping table file\n Path fileMappingTablePath = new Path(mConfig.getOutputPath(), KmerSimilarityHelper.makeKmerSimilarityFileMappingTableFileName());\n FileSystem fs = fileMappingTablePath.getFileSystem(conf);\n fileMapping.saveTo(fs, fileMappingTablePath);\n \n // combine results\n combineResults(fileMapping, new Path(mConfig.getOutputPath()), ScoreFactory.getScore(mConfig.getScoreAlgorithm()), conf);\n */\n }\n \n report.addJob(job);\n \n // report\n if(mConfig.getReportPath() != null && !mConfig.getReportPath().isEmpty()) {\n report.writeTo(mConfig.getReportPath());\n }\n \n return result ? 0 : 1;\n }\n \n private void commit(Path outputPath, Configuration conf) throws IOException {\n FileSystem fs = outputPath.getFileSystem(conf);\n \n FileStatus status = fs.getFileStatus(outputPath);\n if (status.isDirectory()) {\n FileStatus[] entries = fs.listStatus(outputPath);\n for (FileStatus entry : entries) {\n Path entryPath = entry.getPath();\n \n // remove unnecessary outputs\n if(MapReduceHelper.isLogFiles(entryPath)) {\n fs.delete(entryPath, true);\n } else if(MapReduceHelper.isPartialOutputFiles(entryPath)) {\n // rename outputs\n int mapreduceID = MapReduceHelper.getMapReduceID(entryPath);\n String newName = KmerSimilarityHelper.makeKmerSimilarityResultPartFileName(mapreduceID);\n Path toPath = new Path(entryPath.getParent(), newName);\n\n LOG.info(String.format(\"rename %s ==> %s\", entryPath.toString(), toPath.toString()));\n fs.rename(entryPath, toPath);\n } else {\n // let it be\n }\n }\n } else {\n throw new IOException(\"path not found : \" + outputPath.toString());\n }\n }\n \n private void combineResults(KmerMatchFileMapping fileMapping, Path outputPath, AbstractScore scoreFunction, Configuration conf) throws IOException {\n int valuesLen = fileMapping.getSize();\n \n double[] accumulatedScore = new double[valuesLen * valuesLen];\n for(int i=0;i<accumulatedScore.length;i++) {\n accumulatedScore[i] = 0;\n }\n \n Path[] resultPartFiles = KmerSimilarityHelper.getKmerSimilarityResultPartFilePath(conf, outputPath);\n FileSystem fs = outputPath.getFileSystem(conf);\n \n for(Path resultPartFile : resultPartFiles) {\n LOG.info(\"Combining a score file : \" + resultPartFile.toString());\n \n FSDataInputStream is = fs.open(resultPartFile);\n FileStatus status = fs.getFileStatus(resultPartFile);\n \n LineRecordReader reader = new LineRecordReader(is, 0, status.getLen(), conf);\n \n LongWritable off = new LongWritable();\n Text val = new Text();\n\n while(reader.next(off, val)) {\n KmerSimilarityResultPartRecordGroup group = KmerSimilarityResultPartRecordGroup.createInstance(val.toString());\n for(KmerSimilarityResultPartRecord scoreRec : group.getScore()) {\n int file1ID = scoreRec.getFile1ID();\n int file2ID = scoreRec.getFile2ID();\n double score = scoreRec.getScore();\n\n accumulatedScore[file1ID*valuesLen + file2ID] = scoreFunction.accumulateScore(accumulatedScore[file1ID*valuesLen + file2ID], score);\n }\n }\n \n reader.close();\n }\n \n String resultFilename = KmerSimilarityHelper.makeKmerSimilarityResultFileName();\n Path resultFilePath = new Path(outputPath, resultFilename);\n \n LOG.info(\"Creating a final score file : \" + resultFilePath.toString());\n \n FSDataOutputStream os = fs.create(resultFilePath);\n int n = (int)Math.sqrt(accumulatedScore.length);\n for(int i=0;i<accumulatedScore.length;i++) {\n int x = i/n;\n int y = i%n;\n double score = scoreFunction.finalizeScore(accumulatedScore[i]);\n \n String k = x + \"\\t\" + y;\n String v = Double.toString(score);\n String out = k + \"\\t\" + v + \"\\n\";\n os.write(out.getBytes());\n }\n \n os.close();\n \n for(Path resultPartFile : resultPartFiles) {\n fs.delete(resultPartFile, true);\n }\n }\n}", "public class FileTable {\n \n private static final Log LOG = LogFactory.getLog(FileTable.class);\n \n private static final String HADOOP_CONFIG_KEY = \"libra.preprocess.common.filetable.filetable\";\n \n private String name;\n private int kmerSize;\n private List<String> samples = new ArrayList<String>();\n private Hashtable<String, Integer> sampleIDCacheTable = new Hashtable<String, Integer>();\n \n public static FileTable createInstance(File file) throws IOException {\n JsonSerializer serializer = new JsonSerializer();\n return (FileTable) serializer.fromJsonFile(file, FileTable.class);\n }\n \n public static FileTable createInstance(String json) throws IOException {\n JsonSerializer serializer = new JsonSerializer();\n return (FileTable) serializer.fromJson(json, FileTable.class);\n }\n \n public static FileTable createInstance(Configuration conf) throws IOException {\n JsonSerializer serializer = new JsonSerializer();\n return (FileTable) serializer.fromJsonConfiguration(conf, HADOOP_CONFIG_KEY, FileTable.class);\n }\n \n public static FileTable createInstance(FileSystem fs, Path file) throws IOException {\n JsonSerializer serializer = new JsonSerializer();\n return (FileTable) serializer.fromJsonFile(fs, file, FileTable.class);\n }\n \n public FileTable() {\n }\n \n public FileTable(String name, int kmerSize) {\n this.name = name;\n this.kmerSize = kmerSize;\n }\n \n public FileTable(SampleGroup group, int kmerSize) {\n this.name = group.getName();\n this.kmerSize = kmerSize;\n \n Collection<SampleInfo> samples = group.getSamples();\n for(SampleInfo sample : samples) {\n this.samples.add(sample.getPath());\n }\n }\n \n @JsonProperty(\"name\")\n public String getName() {\n return this.name;\n }\n \n @JsonProperty(\"name\")\n public void setName(String name) {\n this.name = name;\n }\n \n @JsonProperty(\"kmer_size\")\n public int getKmerSize() {\n return this.kmerSize;\n }\n \n @JsonProperty(\"kmer_size\")\n public void setKmerSize(int kmerSize) {\n this.kmerSize = kmerSize;\n }\n \n @JsonIgnore\n public int samples() {\n return this.samples.size();\n }\n \n @JsonProperty(\"samples\")\n public Collection<String> getSamples() {\n return this.samples;\n }\n \n @JsonIgnore\n public int getSampleID(String sample) {\n Integer sampleID = this.sampleIDCacheTable.get(sample);\n if(sampleID == null) {\n int sid = -1; // not found\n for(int i=0;i<this.samples.size();i++) {\n if(this.samples.get(i).compareTo(sample) == 0) {\n sid = i;\n break;\n }\n }\n \n if(sid < 0) {\n String sample_target_name = sample;\n int idx = sample_target_name.lastIndexOf(\"/\");\n if(idx >= 0) {\n sample_target_name = sample_target_name.substring(idx + 1);\n }\n \n for(int j=0;j<this.samples.size();j++) {\n String sample_name = this.samples.get(j);\n idx = sample_name.lastIndexOf(\"/\");\n if(idx >= 0) {\n sample_name = sample_name.substring(idx + 1);\n }\n \n if(sample_name.compareTo(sample_target_name) == 0) {\n sid = j;\n break;\n }\n }\n }\n \n sampleID = sid;\n // cache\n this.sampleIDCacheTable.put(sample, sampleID);\n }\n return sampleID;\n }\n \n @JsonProperty(\"samples\")\n public void addSample(Collection<String> samples) {\n this.samples.addAll(samples);\n }\n \n @JsonIgnore\n public void addSample(String sample) {\n this.samples.add(sample);\n }\n \n @JsonIgnore\n public void clearSample() {\n this.samples.clear();\n }\n \n @JsonIgnore\n public void saveTo(Configuration conf) throws IOException {\n JsonSerializer serializer = new JsonSerializer();\n serializer.toJsonConfiguration(conf, HADOOP_CONFIG_KEY, this);\n }\n \n @JsonIgnore\n public void saveTo(FileSystem fs, Path file) throws IOException {\n JsonSerializer serializer = new JsonSerializer();\n serializer.toJsonFile(fs, file, this);\n }\n}", "public class FileTableHelper {\n private final static String FILE_TABLE_PATH_EXP = \".+\\\\.\" + PreprocessorConstants.FILE_TABLE_FILENAME_EXTENSION + \"$\";\n private final static Pattern FILE_TABLE_PATH_PATTERN = Pattern.compile(FILE_TABLE_PATH_EXP);\n \n public static String makeFileTableFileName(String sampleFileName) {\n return sampleFileName + \".\" + PreprocessorConstants.FILE_TABLE_FILENAME_EXTENSION;\n }\n \n public static String makeFileTableDirPath(String rootPath) {\n return PathHelper.concatPath(rootPath, PreprocessorConstants.FILE_TABLE_DIRNAME);\n }\n \n public static boolean isFileTableFile(Path path) {\n return isFileTableFile(path.getName());\n }\n \n public static boolean isFileTableFile(String path) {\n Matcher matcher = FILE_TABLE_PATH_PATTERN.matcher(path.toLowerCase());\n if(matcher.matches()) {\n return true;\n }\n return false;\n }\n \n public static Path[] getFileTableFilePaths(Configuration conf, Path inputPath) throws IOException {\n List<Path> inputFiles = new ArrayList<Path>();\n FileTablePathFilter filter = new FileTablePathFilter();\n \n FileSystem fs = inputPath.getFileSystem(conf);\n if(fs.exists(inputPath)) {\n FileStatus status = fs.getFileStatus(inputPath);\n if(status.isDirectory()) {\n // check child\n FileStatus[] entries = fs.listStatus(inputPath);\n for (FileStatus entry : entries) {\n if(entry.isFile()) {\n if (filter.accept(entry.getPath())) {\n inputFiles.add(entry.getPath());\n }\n }\n }\n } else {\n if (filter.accept(inputPath)) {\n inputFiles.add(inputPath);\n }\n }\n }\n \n Path[] files = inputFiles.toArray(new Path[0]);\n return files;\n }\n}" ]
import libra.common.cmdargs.CommandArgumentsParser; import libra.merge.common.MergeConfig; import libra.merge.merge.MergeMap; import libra.preprocess.common.filetable.FileTable; import libra.preprocess.common.helpers.FileTableHelper; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner;
/* * Copyright 2016 iychoi. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package libra.merge; /** * * @author iychoi */ public class Merge extends Configured implements Tool { private static final Log LOG = LogFactory.getLog(Merge.class); public static void main(String[] args) throws Exception { int res = ToolRunner.run(new Configuration(), new Merge(), args); System.exit(res); } @Override public int run(String[] args) throws Exception { Configuration common_conf = this.getConf();
CommandArgumentsParser<MergeCmdArgs> parser = new CommandArgumentsParser<MergeCmdArgs>();
0
PuffOpenSource/Puff-Android
app/src/main/java/sun/bob/leela/App.java
[ "public class AccountHelper {\n private static AccountHelper ourInstance;\n private Context context;\n private DaoMaster daoMaster;\n private DaoSession daoSession;\n private AccountDao accountDao;\n\n public static AccountHelper getInstance(Context context) {\n if (ourInstance == null) {\n ourInstance = new AccountHelper(context);\n }\n return ourInstance;\n }\n\n private AccountHelper(Context context) {\n this.context = context;\n getDaoMaster();\n getDaoSession();\n accountDao = daoSession.getAccountDao();\n }\n\n public DaoMaster getDaoMaster(){\n if (daoMaster == null) {\n DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, AppConstants.DB_NAME, null);\n daoMaster = new DaoMaster(helper.getWritableDatabase());\n }\n return daoMaster;\n }\n\n public DaoSession getDaoSession(){\n if (daoSession == null) {\n if (daoMaster == null) {\n daoMaster = getDaoMaster();\n }\n daoSession = daoMaster.newSession();\n }\n return daoSession;\n }\n\n public Account getAccount(long id) {\n return accountDao.load(id);\n }\n\n public ArrayList<Account> getAllAccount() {\n return (ArrayList<Account>) accountDao.loadAll();\n }\n\n public ArrayList<Account> queryAccount(String where,String ... params) {\n return (ArrayList<Account>) accountDao.queryRaw(where, params);\n }\n\n public long saveAccount(Account account) {\n if (account.getId() == null || getAccount(account.getId()) == null)\n return accountDao.insertOrReplace(account);\n accountDao.update(account);\n return account.getId();\n }\n\n public void deleteAccount(long id) {\n accountDao.deleteByKey(id);\n }\n\n public void deleteAccount(Account account) {\n accountDao.delete(account);\n }\n\n public boolean hasMasterPassword() {\n List result = accountDao.queryBuilder()\n .where(AccountDao.Properties.Type.eq(AppConstants.TYPE_MASTER))\n .list();\n return result.size() != 0;\n }\n\n public boolean hasQuickAccess() {\n List result = accountDao.queryBuilder()\n .where(AccountDao.Properties.Type.eq(AppConstants.TYPE_QUICK))\n .list();\n return result.size() != 0;\n }\n\n public Account getMasterAccount() {\n List result = accountDao.queryBuilder()\n .where(AccountDao.Properties.Type.eq(AppConstants.TYPE_MASTER))\n .list();\n return result.size() == 0 ? null : (Account) result.get(0);\n }\n\n public Account getQuickAccount() {\n List result = accountDao.queryBuilder()\n .where(AccountDao.Properties.Type.eq(AppConstants.TYPE_QUICK))\n .list();\n return result.size() == 0 ? null : (Account) result.get(0);\n }\n\n public void clearQuickAccount() {\n accountDao.queryBuilder()\n .where(AccountDao.Properties.Type.eq(AppConstants.TYPE_QUICK))\n .buildDelete()\n .executeDeleteWithoutDetachingEntities();\n }\n\n public ArrayList<Account> getAccountsByCategory(Long category) {\n return (ArrayList) accountDao.queryBuilder()\n .where(AccountDao.Properties.Category.eq(category),\n AccountDao.Properties.Type.notEq(AppConstants.TYPE_MASTER),\n AccountDao.Properties.Type.notEq(AppConstants.TYPE_QUICK))\n .orderDesc(AccountDao.Properties.Id)\n .list();\n }\n\n public ArrayList<Account> getRecentUsed(int limit) {\n return (ArrayList) accountDao.queryBuilder()\n .where(AccountDao.Properties.Type.notEq(AppConstants.TYPE_MASTER),\n AccountDao.Properties.Type.notEq(AppConstants.TYPE_QUICK))\n .orderDesc(AccountDao.Properties.Last_access)\n .limit(limit)\n .list();\n\n }\n}", "public class CategoryHelper {\n private static CategoryHelper ourInstance;\n private Context context;\n private DaoMaster daoMaster;\n private DaoSession daoSession;\n private CategoryDao categoryDao;\n\n public static CategoryHelper getInstance(Context context) {\n if (ourInstance == null){\n ourInstance = new CategoryHelper(context);\n }\n return ourInstance;\n }\n\n private CategoryHelper(Context context) {\n this.context = context;\n getDaoMaster();\n getDaoSession();\n categoryDao = daoSession.getCategoryDao();\n\n }\n\n public DaoMaster getDaoMaster(){\n if (daoMaster == null) {\n DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, AppConstants.DB_NAME, null);\n daoMaster = new DaoMaster(helper.getWritableDatabase());\n }\n return daoMaster;\n }\n\n public DaoSession getDaoSession(){\n if (daoSession == null) {\n if (daoMaster == null) {\n daoMaster = getDaoMaster();\n }\n daoSession = daoMaster.newSession();\n }\n return daoSession;\n }\n\n public ArrayList<Category> getAllCategory() {\n return (ArrayList<Category>) categoryDao.loadAll();\n }\n\n public Category getCategoryByName(String name){\n List<Category> result = categoryDao.queryBuilder()\n .where(CategoryDao.Properties.Name.eq(name))\n .list();\n return result == null ? null : result.get(0);\n }\n\n public Category getCategoryById(Long id) {\n List<Category> result = categoryDao.queryBuilder()\n .where(CategoryDao.Properties.Id.eq(id))\n .list();\n return result == null || result.size() == 0 ? null : result.get(0);\n }\n\n public long saveCategory(Category category) {\n if (category.getId() == null || getCategoryById(category.getId()) == null) {\n return categoryDao.insertOrReplace(category);\n }\n categoryDao.update(category);\n return category.getId();\n }\n\n public void deleteCategory(Category category) {\n categoryDao.delete(category);\n }\n}", "public class TypeHelper {\n private static TypeHelper ourInstance;\n private Context context;\n private DaoMaster daoMaster;\n private AcctTypeDao acctTypeDao;\n private DaoSession daoSession;\n\n public static TypeHelper getInstance(Context context) {\n if (ourInstance == null) {\n ourInstance = new TypeHelper(context);\n }\n return ourInstance;\n }\n\n private TypeHelper(Context context) {\n this.context = context;\n getDaoMaster();\n getDaoSession();\n acctTypeDao = daoSession.getAcctTypeDao();\n }\n\n public DaoMaster getDaoMaster(){\n if (daoMaster == null) {\n DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, AppConstants.DB_NAME, null);\n daoMaster = new DaoMaster(helper.getWritableDatabase());\n }\n return daoMaster;\n }\n\n public DaoSession getDaoSession(){\n if (daoSession == null) {\n if (daoMaster == null) {\n daoMaster = getDaoMaster();\n }\n daoSession = daoMaster.newSession();\n }\n return daoSession;\n }\n\n public ArrayList<AcctType> getAllTypes (){\n return (ArrayList<AcctType>) acctTypeDao.loadAll();\n }\n\n public AcctType getTypeById(Long id) {\n List<AcctType> result = acctTypeDao.queryBuilder()\n .where(AcctTypeDao.Properties.Id.eq(id))\n .list();\n return result == null || result.size() == 0 ? null : result.get(0);\n }\n\n public AcctType getTypeByName(String name) {\n List<AcctType> result = acctTypeDao.queryBuilder()\n .where(AcctTypeDao.Properties.Name.eq(name))\n .list();\n return result == null || result.size() == 0 ? null : result.get(0);\n }\n\n public long save(AcctType acctType) {\n if (acctType.getId() == null || getTypeById(acctType.getId()) == null)\n return acctTypeDao.insertOrReplace(acctType);\n acctTypeDao.update(acctType);\n return acctType.getId();\n }\n\n public void delete(AcctType acctType) {\n acctTypeDao.delete(acctType);\n }\n}", "public class CategoryUtil {\n private static CategoryUtil ourInstance;\n private Context context;\n\n public static CategoryUtil getInstance(Context context) {\n if (ourInstance == null) {\n ourInstance = new CategoryUtil(context);\n }\n return ourInstance;\n }\n\n private CategoryUtil(Context context) {\n this.context = context;\n }\n\n public void initBuiltInCategories(){\n CategoryHelper helper = CategoryHelper.getInstance(context);\n Category cat = new Category();\n\n cat.setName(\"Recent\");\n cat.setType(AppConstants.CAT_TYPE_BUILTIN);\n cat.setId(AppConstants.CAT_ID_RECENT);\n cat.setIcon(\"icon_category/cat_recent.png\");\n helper.saveCategory(cat);\n\n cat = new Category();\n cat.setName(\"Cards\");\n cat.setType(AppConstants.CAT_TYPE_BUILTIN);\n cat.setId(AppConstants.CAT_ID_CARDS);\n cat.setIcon(\"icon_category/cat_cards.png\");\n helper.saveCategory(cat);\n\n cat = new Category();\n cat.setName(\"Computers\");\n cat.setType(AppConstants.CAT_TYPE_BUILTIN);\n cat.setId(AppConstants.CAT_ID_COMPUTERS);\n cat.setIcon(\"icon_category/cat_computer.png\");\n helper.saveCategory(cat);\n\n cat = new Category();\n cat.setName(\"Device\");\n cat.setType(AppConstants.CAT_TYPE_BUILTIN);\n cat.setId(AppConstants.CAT_ID_DEVICE);\n cat.setIcon(\"icon_category/cat_device.png\");\n helper.saveCategory(cat);\n\n cat = new Category();\n cat.setName(\"Entry\");\n cat.setType(AppConstants.CAT_TYPE_BUILTIN);\n cat.setId(AppConstants.CAT_ID_ENTRY);\n cat.setIcon(\"icon_category/cat_entry.png\");\n helper.saveCategory(cat);\n\n cat = new Category();\n cat.setName(\"Mail\");\n cat.setType(AppConstants.CAT_TYPE_BUILTIN);\n cat.setId(AppConstants.CAT_ID_MAIL);\n cat.setIcon(\"icon_category/cat_mail.png\");\n helper.saveCategory(cat);\n\n cat = new Category();\n cat.setName(\"Social\");\n cat.setType(AppConstants.CAT_TYPE_BUILTIN);\n cat.setId(AppConstants.CAT_ID_SOCIAL);\n cat.setIcon(\"icon_category/cat_social.png\");\n helper.saveCategory(cat);\n\n cat = new Category();\n cat.setName(\"Website\");\n cat.setType(AppConstants.CAT_TYPE_BUILTIN);\n cat.setId(AppConstants.CAT_ID_WEBSITE);\n cat.setIcon(\"icon_category/cat_website.png\");\n helper.saveCategory(cat);\n }\n\n public void initBuiltInTypes (){\n TypeHelper helper = TypeHelper.getInstance(context.getApplicationContext());\n AcctType toAdd;\n try {\n for (String file : context.getAssets().list(\"cat_cards\")) {\n if (file.endsWith(\".png\")) {\n toAdd = new AcctType();\n toAdd.setName(file.replace(\".png\", \"\"));\n toAdd.setCategory(AppConstants.CAT_ID_CARDS);\n toAdd.setIcon(\"cat_cards/\" + file);\n helper.save(toAdd);\n }\n }\n\n for (String file : context.getAssets().list(\"cat_computers\")) {\n if (file.endsWith(\".png\")) {\n toAdd = new AcctType();\n toAdd.setName(file.replace(\".png\", \"\"));\n toAdd.setCategory(AppConstants.CAT_ID_COMPUTERS);\n toAdd.setIcon(\"cat_computers/\" + file);\n helper.save(toAdd);\n }\n }\n\n for (String file : context.getAssets().list(\"cat_device\")) {\n if (file.endsWith(\".png\")) {\n toAdd = new AcctType();\n toAdd.setName(file.replace(\".png\", \"\"));\n toAdd.setCategory(AppConstants.CAT_ID_DEVICE);\n toAdd.setIcon(\"cat_device/\" + file);\n helper.save(toAdd);\n }\n }\n\n for (String file : context.getAssets().list(\"cat_mail\")) {\n if (file.endsWith(\".png\")) {\n toAdd = new AcctType();\n toAdd.setName(file.replace(\".png\", \"\"));\n toAdd.setCategory(AppConstants.CAT_ID_MAIL);\n toAdd.setIcon(\"cat_mail/\" + file);\n helper.save(toAdd);\n }\n }\n\n for (String file : context.getAssets().list(\"cat_cards\")) {\n if (file.endsWith(\".png\")) {\n toAdd = new AcctType();\n toAdd.setName(file.replace(\".png\", \"\"));\n toAdd.setCategory(AppConstants.CAT_ID_MAIL);\n toAdd.setIcon(\"cat_cards/\" + file);\n helper.save(toAdd);\n }\n }\n\n for (String file : context.getAssets().list(\"cat_entry\")) {\n if (file.endsWith(\".png\")) {\n toAdd = new AcctType();\n toAdd.setName(file.replace(\".png\", \"\"));\n toAdd.setCategory(AppConstants.CAT_ID_ENTRY);\n toAdd.setIcon(\"cat_entry/\" + file);\n helper.save(toAdd);\n }\n }\n\n for (String file : context.getAssets().list(\"cat_social\")) {\n if (file.endsWith(\".png\")) {\n toAdd = new AcctType();\n toAdd.setName(file.replace(\".png\", \"\"));\n toAdd.setCategory(AppConstants.CAT_ID_SOCIAL);\n toAdd.setIcon(\"cat_social/\" + file);\n helper.save(toAdd);\n }\n }\n\n for (String file : context.getAssets().list(\"cat_website\")) {\n if (file.endsWith(\".png\")) {\n toAdd = new AcctType();\n toAdd.setName(file.replace(\".png\", \"\"));\n toAdd.setCategory(AppConstants.CAT_ID_WEBSITE);\n toAdd.setIcon(\"cat_website/\" + file);\n helper.save(toAdd);\n }\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n}", "public class EnvUtil {\n private static EnvUtil ourInstance;\n private Context context;\n private String sdcardFolder, imageCropCacheFolder, catIconFolder, acctIconFolder;\n\n public static EnvUtil getInstance(Context context) {\n if (ourInstance == null)\n ourInstance = new EnvUtil(context);\n return ourInstance;\n }\n\n private EnvUtil(Context context) {\n this.context = context;\n sdcardFolder = Environment.getExternalStorageDirectory().getPath();\n imageCropCacheFolder = sdcardFolder + \"/data/data/leela/cache/\";\n if (!new File(imageCropCacheFolder).exists()) {\n new File(imageCropCacheFolder).mkdirs();\n try {\n new File(imageCropCacheFolder + \".nomedia\").createNewFile();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n catIconFolder = sdcardFolder + \"/data/data/leela/catIcon/\";\n if (!new File(catIconFolder).exists()) {\n new File(catIconFolder).mkdirs();\n try {\n new File(catIconFolder + \".nomedia\").createNewFile();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n acctIconFolder = sdcardFolder + \"/data/data/leela/acctIcon/\";\n if (!new File(acctIconFolder).exists()) {\n new File(acctIconFolder).mkdirs();\n try {\n new File(acctIconFolder + \".nomedia\").createNewFile();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n\n public String getImageCropCacheFolder() {\n return imageCropCacheFolder;\n }\n\n public String getSdcardFolder() {\n return sdcardFolder;\n }\n\n public String getCatIconFolder() {\n return catIconFolder;\n }\n\n public String getAcctIconFolder() {\n return acctIconFolder;\n }\n}", "public class ResUtil {\n private static ResUtil ourInstance;\n private Context context;\n public static ResUtil getInstance(Context context) {\n if (ourInstance == null) {\n ourInstance = new ResUtil(context);\n }\n return ourInstance;\n }\n\n private ResUtil(Context context) {\n this.context = context;\n }\n\n public float getDP(){\n return context.getResources().getDisplayMetrics().density;\n }\n\n public int pointToDp(int point) {\n return (int) (point * getDP());\n }\n\n public Bitmap getBmpInAssets(String assetName) throws IOException {\n return BitmapFactory.decodeStream(context.getResources().getAssets().open(assetName));\n }\n\n public Bitmap getBmp(String fileName) throws IOException {\n if (fileName.startsWith(\"/\")) {\n //File System\n return BitmapFactory.decodeStream(new FileInputStream(fileName));\n } else {\n //Assets\n return BitmapFactory.decodeStream(context.getResources().getAssets().open(fileName));\n }\n }\n\n public Uri getBmpUri(String fileName) {\n if (fileName.startsWith(\"/\")) {\n return Uri.fromFile(new File(fileName));\n } else {\n return Uri.parse(\"file:///android_asset/\" + fileName);\n }\n\n }\n\n public Object getBmpPath(String fileName) {\n if (fileName.startsWith(\"/\")) {\n return fileName;\n } else {\n InputStream ret;\n try {\n ret = context.getResources().getAssets().open(fileName);\n } catch (IOException e) {\n e.printStackTrace();\n return \"\";\n }\n return ret;\n }\n }\n\n public AppCompatDialog showProgressbar(Activity activity, long timeout, boolean cancelable) {\n final AppCompatDialog dialog = new AppCompatDialog(activity);\n dialog.setContentView(R.layout.dialog_progress);\n dialog.setCancelable(cancelable);\n dialog.setTitle(\"Progressing...\");\n ProgressBar progressBar = (ProgressBar) dialog.findViewById(R.id.progress);\n if (timeout > 0) {\n Handler handler = new Handler(activity.getMainLooper());\n handler.postDelayed(new Runnable() {\n @Override\n public void run() {\n dialog.cancel();\n dialog.dismiss();\n }\n }, timeout);\n dialog.show();\n } else {\n dialog.show();\n }\n return dialog;\n }\n\n public AppCompatDialog showProgressbar(Activity activity, long timeout) {\n return showProgressbar(activity, timeout, true);\n }\n\n public AppCompatDialog showProgressbar(Activity activity) {\n return showProgressbar(activity, 0, false);\n }\n\n public static void hideSoftKeyboard(View view) {\n if (view != null) {\n InputMethodManager imm = (InputMethodManager)view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);\n imm.hideSoftInputFromWindow(view.getWindowToken(), 0);\n }\n }\n}", "public class UserDefault extends StorageInterface {\n private Context context;\n private static UserDefault ourInstance;\n private SharedPreferences sharedPreferences;\n\n public static UserDefault getInstance(Context context) {\n if (ourInstance == null)\n ourInstance = new UserDefault(context);\n return ourInstance;\n }\n\n private UserDefault(Context context) {\n this.context = context;\n this.sharedPreferences = context.getSharedPreferences(\"UserDefaultPrivate\", Context.MODE_PRIVATE);\n }\n\n public UserDefault writeInt(String key, int value) {\n sharedPreferences.edit().putInt(key, value).commit();\n return this;\n }\n\n public UserDefault writeString(String key, String value){\n sharedPreferences.edit().putString(key, value).commit();\n return this;\n }\n\n public UserDefault writeBoolean(String key, boolean value) {\n sharedPreferences.edit().putBoolean(key, value).commit();\n return this;\n }\n\n public boolean hasQuickPassword() {\n return sharedPreferences.getBoolean(kSettingsHasQuickPassword, false);\n }\n\n public void setHasQuickPassword() {\n sharedPreferences.edit().putBoolean(kSettingsHasQuickPassword, true).commit();\n }\n\n public void clearQuickPassword() {\n sharedPreferences.edit().putBoolean(kSettingsHasQuickPassword, false).commit();\n }\n\n public int getInt(String key) {\n return sharedPreferences.getInt(key, -1);\n }\n\n public boolean getBoolean(String key) {\n return sharedPreferences.getBoolean(key, true);\n }\n\n public String getString(String key) {\n return sharedPreferences.getString(key, \"\");\n }\n\n public int getAutoClearTimeInSeconds() {\n return 60;\n }\n\n @Override\n public void save(String s, Boolean aBoolean) {\n sharedPreferences.edit().putBoolean(s, aBoolean).commit();\n }\n\n @Override\n public boolean load(String s, Boolean aBoolean) {\n return sharedPreferences.getBoolean(s, false);\n }\n\n @Override\n public void save(String s, String s1) {\n sharedPreferences.edit().putString(s, s1).commit();\n }\n\n @Override\n public String load(String s, String s1) {\n return sharedPreferences.getString(s, s1);\n }\n\n @Override\n public void save(String s, Integer integer) {\n sharedPreferences.edit().putInt(s, integer).commit();\n }\n\n @Override\n public Integer load(String s, Integer integer) {\n return sharedPreferences.getInt(s, integer);\n }\n\n @Override\n public void save(String s, Float aFloat) {\n sharedPreferences.edit().putFloat(s, aFloat).commit();\n }\n\n @Override\n public Float load(String s, Float aFloat) {\n return sharedPreferences.getFloat(s, aFloat);\n }\n\n @Override\n public void save(String s, Long aLong) {\n sharedPreferences.edit().putLong(s, aLong).commit();\n }\n\n @Override\n public Long load(String s, Long aLong) {\n return sharedPreferences.getLong(s, aLong);\n }\n\n @Override\n public Map<String, ?> getAll() {\n return sharedPreferences.getAll();\n }\n\n public long getQuickPassByte() {\n return sharedPreferences.getLong(kSettingsQuickPassByte, v4x4);\n }\n\n public void setQuickPassByte(long b) {\n sharedPreferences.edit().putLong(kSettingsQuickPassByte, b).commit();\n }\n\n public void setNeedPasswordWhenLaunch(boolean need) {\n sharedPreferences.edit().putBoolean(kNeedPasswordWhenLaunch, need).commit();\n }\n\n public boolean needPasswordWhenLaunch() {\n return sharedPreferences.getBoolean(kNeedPasswordWhenLaunch, false);\n }\n\n public static final String kSettingsHasQuickPassword = \"kSettingsHasQuickPassword\";\n public static final String kSettingsQuickPassByte = \"kSettingsQuickPassByte\";\n public static final String kNeedPasswordWhenLaunch = \"kNeedPasswordWhenLaunch\";\n public static final long v3x3 = 0x1033;\n public static final long v4x4 = 0x1044;\n}" ]
import android.app.Application; import sun.bob.leela.db.AccountHelper; import sun.bob.leela.db.CategoryHelper; import sun.bob.leela.db.TypeHelper; import sun.bob.leela.utils.CategoryUtil; import sun.bob.leela.utils.EnvUtil; import sun.bob.leela.utils.ResUtil; import sun.bob.leela.utils.UserDefault;
package sun.bob.leela; /** * Created by bob.sun on 16/3/19. */ public class App extends Application { @Override public void onCreate(){ super.onCreate(); AccountHelper.getInstance(getApplicationContext()); CategoryHelper categoryHelper = CategoryHelper.getInstance(getApplicationContext());
TypeHelper typeHelper = TypeHelper.getInstance(getApplicationContext());
2
IYCI/MyClass
app/src/main/java/com/YC2010/MyClass/ui/fragments/SearchScheduleFragment.java
[ "public class CourseInfo {\n private String courseName;\n private String courseNum;\n private String courseSec;\n private String courseTime;\n private String courseLoc;\n private String courseProf;\n private String tutName;\n private String tutNum;\n private String tutTime;\n private String tutLoc;\n private String tutSec;\n private boolean isOnline;\n private String labName;\n private String labNum;\n private String labTime;\n private String labSec;\n private String labLoc;\n\n public CourseInfo(String name){\n courseName = name;\n }\n\n public void setNum(String number){\n courseNum = number;\n }\n\n public void setLoc(String loc){\n courseLoc = loc;\n }\n\n public void setTime(String time){\n courseTime = time;\n }\n\n public void setTimeAPM(String time){\n if (!isOnline && time != null) {\n int i = 0;\n for (; time.charAt(i) < 48 || time.charAt(i) > 57; i++);\n String days = time.substring(0,i);\n String realtime = time.substring(i);\n String starttime = realtime.substring(0,5);\n String endtime = realtime.substring(6);\n try{\n DateFormat f1 = new SimpleDateFormat(\"HH:mm\"); //HH for hour of the day (0 - 23)\n Date d = f1.parse(starttime);\n DateFormat f2 = new SimpleDateFormat(\"h:mma\");\n starttime = f2.format(d); // \"12:18am\"\n\n DateFormat f3 = new SimpleDateFormat(\"HH:mm\"); //HH for hour of the day (0 - 23)\n Date d2 = f3.parse(endtime);\n DateFormat f4 = new SimpleDateFormat(\"h:mma\");\n endtime = f4.format(d2); // \"12:18am\"\n\n\n } catch (ParseException e){\n e.printStackTrace();\n }\n courseTime = days + starttime + \"-\" + endtime;\n } else {\n courseTime = time;\n }\n }\n public void setSec(String sec){\n courseSec = sec;\n isOnline = sec.equals(\"081\");\n }\n\n public void setProf(String prof){\n courseProf = prof;\n }\n\n public void setTutname(){\n tutName = courseName;\n }\n\n public void setTutnum(String num){\n tutNum = num;\n }\n\n public void setTutTime(String time){\n tutTime = time;\n }\n\n public void setTutLoc(String loc) {\n tutLoc = loc;\n }\n\n public void setTutsec(String sec){\n tutSec = sec;\n }\n\n public void setlabName(){\n tutSec = courseName;\n }\n\n public void setlabNum(String num){ labNum = num;}\n\n public void setlabTime(String time){ labTime = time;}\n\n public void setlabLoc(String loc){ labLoc = loc;}\n\n public void setlabSec(String sec){ labSec = sec;}\n\n public void setIsOnline(boolean isOnline) {\n this.isOnline = isOnline;\n }\n\n public String getCourseName() {\n return courseName;\n }\n\n public String getCourseNum() {\n return courseNum;\n }\n\n public String getCourseSec() {\n return courseSec;\n }\n\n public String getCourseTime() {\n return courseTime;\n }\n\n public String getCourseLoc() {\n return courseLoc;\n }\n\n public String getCourseProf() {\n return courseProf;\n }\n\n public String getTutName() {\n return tutName;\n }\n\n public String getTutNum() {\n return tutNum;\n }\n\n public String getTutTime() {\n return tutTime;\n }\n\n public String getTutLoc() {\n return tutLoc;\n }\n\n public String getTutSec() {\n return tutSec;\n }\n\n public boolean isOnline() {\n return isOnline;\n }\n\n public String getLabName() {\n return labName;\n }\n\n public String getLabNum() {\n return labNum;\n }\n\n public String getLabTime() {\n return labTime;\n }\n\n public String getLabSec() {\n return labSec;\n }\n\n public String getLabLoc() {\n return labLoc;\n }\n}", "public class LectureSectionObject implements Parcelable {\n private String number;\n private String section;\n private String time;\n private String professor;\n private String location;\n private String capacity;\n private String total;\n private boolean isOnline;\n\n public LectureSectionObject(String number, String section, String time, String professor, String location, String capacity, String total, boolean isOnline) {\n this.number = number;\n this.section = section;\n this.time = time;\n this.professor = professor;\n this.location = location;\n this.capacity = capacity;\n this.total = total;\n this.isOnline = isOnline;\n }\n\n public LectureSectionObject() {}\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeString(number);\n dest.writeString(section);\n dest.writeString(time);\n dest.writeString(professor);\n dest.writeString(location);\n dest.writeString(capacity);\n dest.writeString(total);\n dest.writeByte((byte) (isOnline ? 1 : 0));\n }\n\n public LectureSectionObject(Parcel src) {\n this.number = src.readString();\n this.section = src.readString();\n this.time = src.readString();\n this.professor = src.readString();\n this.location = src.readString();\n this.capacity = src.readString();\n this.total = src.readString();\n this.isOnline = src.readByte() != 0;\n }\n\n public static final Creator CREATOR = new Creator() {\n @Override\n public LectureSectionObject createFromParcel(Parcel source) {\n return new LectureSectionObject(source);\n }\n\n @Override\n public LectureSectionObject[] newArray(int size) {\n return new LectureSectionObject[size];\n }\n };\n\n public void setNumber(String number) {\n this.number = number;\n }\n\n public void setCapacity(String capacity) {\n this.capacity = capacity;\n }\n\n public void setLocation(String location) {\n this.location = location;\n }\n\n public void setTime(String time) {\n this.time = time;\n }\n\n public void setSection(String section) {\n this.section = section;\n }\n\n public void setTotal(String total) {\n this.total = total;\n }\n\n public void setProfessor(String professor) {\n this.professor = professor;\n }\n\n public void setIsOnline(boolean isOnline) {\n this.isOnline = isOnline;\n }\n\n public String getNumber() {\n return number;\n }\n\n public String getSection() {\n return section;\n }\n\n public String getTime() {\n return time;\n }\n\n public String getProfessor() {\n return professor;\n }\n\n public String getLocation() {\n return location;\n }\n\n public String getCapacity() {\n return capacity;\n }\n\n public String getTotal() {\n return total;\n }\n\n public boolean isOnline() {\n return isOnline;\n }\n}", "public class CoursesDBHandler extends SQLiteOpenHelper {\n private Context mContext;\n\n // DB Version\n private static final int DATABASE_VERSION = 6;\n\n // DB Name\n private static final String DATABASE_NAME = \"CoursesManager\";\n\n // Table name\n private static final String TABLE_COURSES = \"Courses\";\n\n // TABLE_REMINDERS Columns names // columnIndex\n\n private static final String KEY_NUM = \"courseNum\"; // 0\n private static final String KEY_NAME = \"courseName\"; // 1\n private static final String KEY_SECTION = \"courseSec\"; // 2\n private static final String KEY_TIME = \"courseTime\"; // 3\n private static final String KEY_LOC = \"courseLoc\"; // 4\n private static final String KEY_PROF = \"courseProf\"; // 5\n private static final String KEY_NAME_TUT = \"tutName\"; // 6\n private static final String KEY_NUM_TUT = \"tutNum\"; // 7\n private static final String KEY_TIME_TUT = \"tutTime\"; // 8\n private static final String KEY_LOC_TUT = \"tutLoc\"; // 9\n private static final String KEY_SEC_TUT = \"tutSec\"; // 10\n private static final String KEY_ONLINE = \"isOnline\"; // 11\n private static final String KEY_TAKING_TERM = \"takingTerm\";// 12\n\n public CoursesDBHandler(Context context) {\n super(context, DATABASE_NAME, null, DATABASE_VERSION);\n mContext = context;\n }\n\n @Override\n public void onCreate(SQLiteDatabase db) {\n Log.d(\"CoursesDBHandler\", \"onCreate\");\n String CREATE_TABLE = \"CREATE TABLE \" + TABLE_COURSES + \"(\"\n + KEY_NUM + \" STRING PRIMARY KEY,\" + KEY_NAME + \" TEXT,\"\n + KEY_SECTION + \" TEXT,\"\n + KEY_TIME + \" TEXT,\" + KEY_LOC + \" TEXT,\"\n + KEY_PROF + \" TEXT,\" + KEY_NAME_TUT + \" TEXT,\"\n + KEY_NUM_TUT + \" TEXT,\" + KEY_TIME_TUT + \" TEXT,\"\n + KEY_LOC_TUT + \" TEXT,\" + KEY_SEC_TUT + \" TEXT,\"\n + KEY_ONLINE + \" INTEGER,\" + KEY_TAKING_TERM + \" INTEGER\" + \")\";\n db.execSQL(CREATE_TABLE);\n }\n\n // Upgrading database\n @Override\n public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n Log.d(\"CoursesDBHandler\", \"onUpgrade\");\n switch(oldVersion) {\n case 3:\n case 4:\n case 5:\n try {\n Log.d(\"CoursesDBHandler\", \"onUpgrade case 4\");\n db.execSQL(\"ALTER TABLE \" + TABLE_COURSES + \" ADD column \" + KEY_TAKING_TERM + \" INTEGER NOT NULL DEFAULT(\" +\n mContext.getSharedPreferences(\"TERMS\", mContext.MODE_PRIVATE).getInt(\"CURRENT_TERM\", Constants.defaultCurTermNum) + \")\");\n }\n catch (Exception e) {\n e.printStackTrace();\n }\n break;\n }\n }\n\n /**\n * All CRUD(Create, Read, Update, Delete) Operations\n */\n\n // Adding new course\n public void addCourse(CourseInfo mCourse) {\n SQLiteDatabase db = this.getWritableDatabase();\n\n ContentValues values = new ContentValues();\n values.put(KEY_NUM, mCourse.getCourseNum());\n values.put(KEY_NAME, mCourse.getCourseName());\n values.put(KEY_SECTION, mCourse.getCourseSec());\n values.put(KEY_TIME, mCourse.getCourseTime());\n values.put(KEY_LOC, mCourse.getCourseLoc());\n values.put(KEY_PROF, mCourse.getCourseProf());\n values.put(KEY_NAME_TUT, mCourse.getTutName());\n values.put(KEY_NUM_TUT, mCourse.getTutNum());\n values.put(KEY_SEC_TUT, mCourse.getTutSec());\n values.put(KEY_TIME_TUT, mCourse.getTutTime());\n values.put(KEY_LOC_TUT, mCourse.getTutLoc());\n values.put(KEY_ONLINE, mCourse.isOnline());\n values.put(KEY_TAKING_TERM, 0);\n\n // Inserting Row\n db.insert(TABLE_COURSES, null, values);\n db.close(); // Closing database connection\n }\n\n // add new course with taking term specify\n public void addCourse(CourseInfo mCourse, int term) {\n SQLiteDatabase db = this.getWritableDatabase();\n\n ContentValues values = new ContentValues();\n values.put(KEY_NUM, mCourse.getCourseNum());\n values.put(KEY_NAME, mCourse.getCourseName());\n values.put(KEY_SECTION, mCourse.getCourseSec());\n values.put(KEY_TIME, mCourse.getCourseTime());\n values.put(KEY_LOC, mCourse.getCourseLoc());\n values.put(KEY_PROF, mCourse.getCourseProf());\n values.put(KEY_NAME_TUT, mCourse.getTutName());\n values.put(KEY_NUM_TUT, mCourse.getTutNum());\n values.put(KEY_SEC_TUT, mCourse.getTutSec());\n values.put(KEY_TIME_TUT, mCourse.getTutTime());\n values.put(KEY_LOC_TUT, mCourse.getTutLoc());\n values.put(KEY_ONLINE, mCourse.isOnline());\n values.put(KEY_TAKING_TERM, term);\n\n // Inserting Row\n db.insert(TABLE_COURSES, null, values);\n db.close(); // Closing database connection\n }\n\n // remove a course\n public void removeCourse(String courseNum){\n SQLiteDatabase db = this.getWritableDatabase();\n\n // deleting Row\n int affected_rows = db.delete(TABLE_COURSES, KEY_NUM + \" = ?\", new String[]{courseNum});\n Log.d(\"removeReminder\", affected_rows + \" rows deleted\");\n db.close(); // Closing database connection\n }\n\n public void removeAll(){\n SQLiteDatabase db = this.getWritableDatabase();\n\n // deleting Row\n int affected_rows = db.delete(TABLE_COURSES, null,null);\n Log.d(\"removeReminder\", affected_rows + \" rows deleted\");\n db.close(); // Closing database connection\n }\n\n // get reminder count\n public int CountCourses(){\n SQLiteDatabase db = this.getReadableDatabase();\n String selectQuery = \"SELECT COUNT(*) FROM \" + TABLE_COURSES;\n SQLiteStatement s = db.compileStatement(selectQuery);\n long count = s.simpleQueryForLong();\n return (int)count;\n }\n\n // check if course exist\n public boolean IsInDB(String courseID) {\n SQLiteDatabase db = this.getReadableDatabase();\n String Query = \"Select * from \" + TABLE_COURSES + \" where \" + KEY_NUM + \" = \" + courseID;\n Cursor cursor = db.rawQuery(Query, null);\n if(cursor.getCount() <= 0){\n cursor.close();\n return false;\n }\n cursor.close();\n return true;\n }\n\n // Get All Courses\n public List<CourseInfo> getAllCourses() {\n List<CourseInfo> CoursesList = new ArrayList<>();\n\n // Select All Query\n String selectQuery = \"SELECT * FROM \" + TABLE_COURSES;\n\n SQLiteDatabase db = this.getWritableDatabase();\n Cursor cursor = db.rawQuery(selectQuery, null);\n\n // looping through all rows and adding to list\n if (cursor.moveToFirst()) {\n do {\n CourseInfo course = new CourseInfo(cursor.getString(1));\n course.setNum(cursor.getString(0));\n course.setSec(cursor.getString(2));\n course.setTime(cursor.getString(3));\n course.setLoc(cursor.getString(4));\n course.setProf(cursor.getString(5));\n course.setTutname();\n course.setTutnum(cursor.getString(7));\n course.setTutTime(cursor.getString(8));\n course.setTutLoc(cursor.getString(9));\n course.setTutsec(cursor.getString(10));\n course.setIsOnline(cursor.getInt(11) > 0);\n\n // Adding course to list\n CoursesList.add(course);\n } while (cursor.moveToNext());\n }\n\n // return contact list\n return CoursesList;\n }\n\n // Get All Courses by term\n public List<CourseInfo> getAllCourses(int term) {\n List<CourseInfo> CoursesList = new ArrayList<>();\n\n // Select All Query\n String selectQuery = \"SELECT * FROM \" + TABLE_COURSES + \" WHERE \" + KEY_TAKING_TERM + \" = \" + term;\n\n SQLiteDatabase db = this.getWritableDatabase();\n Cursor cursor = db.rawQuery(selectQuery, null);\n\n // looping through all rows and adding to list\n if (cursor.moveToFirst()) {\n do {\n CourseInfo course = new CourseInfo(cursor.getString(1));\n course.setNum(cursor.getString(0));\n course.setSec(cursor.getString(2));\n course.setTime(cursor.getString(3));\n course.setLoc(cursor.getString(4));\n course.setProf(cursor.getString(5));\n course.setTutname();\n course.setTutnum(cursor.getString(7));\n course.setTutTime(cursor.getString(8));\n course.setTutLoc(cursor.getString(9));\n course.setTutsec(cursor.getString(10));\n course.setIsOnline(cursor.getInt(11) > 0);\n\n // Adding course to list\n CoursesList.add(course);\n } while (cursor.moveToNext());\n }\n\n // return contact list\n return CoursesList;\n }\n}", "public class SectionListAdapter extends BaseAdapter {\n ArrayList<LectureSectionObject> mArrayList;\n Context mContext;\n LayoutInflater mLayoutInflater;\n\n public SectionListAdapter(Context context, int textViewResourceId, Bundle bundle) {\n mLayoutInflater = LayoutInflater.from(context);\n mArrayList = bundle.getParcelableArrayList(Constants.lectureSectionObjectListKey);\n mContext = context;\n Log.d(\"SectionListAdapter\", \"Course name is \" + bundle.getString(\"courseName\"));\n }\n\n @Override\n public LectureSectionObject getItem(int i) {\n return mArrayList.get(i);\n }\n\n @Override\n public int getCount() {\n return mArrayList != null ? mArrayList.size() : 0;\n }\n\n @Override\n public long getItemId(int arg0) {\n return 0;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n\n View v = mLayoutInflater.inflate(R.layout.section_item, null);\n\n TextView capacity = (TextView) v.findViewById(R.id.section_item_capacity);\n TextView lec = (TextView) v.findViewById(R.id.section_item_lec);\n TextView loc = (TextView) v.findViewById(R.id.section_item_loc);\n TextView time = (TextView) v.findViewById(R.id.section_item_time);\n TextView prof = (TextView) v.findViewById(R.id.section_item_prof);\n RelativeLayout section_item_prof_layout = (RelativeLayout) v.findViewById((R.id.section_item_prof_layout));\n\n LectureSectionObject sectionInfo = getItem(position);\n String professor = sectionInfo.getProfessor();\n\n if (professor != null && professor.length() > 0) {\n prof.setText(professor);\n prof.setVisibility(View.VISIBLE);\n section_item_prof_layout.setVisibility(View.VISIBLE);\n } else {\n prof.setVisibility(View.GONE);\n }\n\n lec.setText(sectionInfo.getSection());\n time.setText(sectionInfo.getTime());\n loc.setText(sectionInfo.getLocation());\n\n int enroll_total = Integer.parseInt(sectionInfo.getTotal());\n int enroll_cap = Integer.parseInt(sectionInfo.getCapacity());\n\n if (enroll_total/enroll_cap >= 1) {\n capacity.setTextColor(mContext.getResources().getColor(R.color.fab_color_1));\n } else {\n capacity.setTextColor(mContext.getResources().getColor(R.color.light_green));\n }\n\n Log.d(\"SectionListAdapter\", \"rate is \" + enroll_total/enroll_cap);\n\n capacity.setText(enroll_total + \"/\" + enroll_cap);\n\n return v;\n }\n\n}", "public class TstListAdapter extends BaseAdapter {\n ArrayList<TestObject> mArrayList;\n Context mContext;\n LayoutInflater mLayoutInflater;\n\n public TstListAdapter(Context context, int textViewResourceId, Bundle bundle) {\n mLayoutInflater = LayoutInflater.from(context);\n mArrayList = bundle.getParcelableArrayList(Constants.testObjectListKey);\n mContext = context;\n Log.d(\"SectionListAdapter\", \"Course name is \" + bundle.getString(\"courseName\"));\n }\n\n\n @Override\n public TestObject getItem(int i) {\n return mArrayList.get(i);\n }\n\n @Override\n public int getCount() {\n return mArrayList != null ? mArrayList.size() : 0;\n }\n\n @Override\n public long getItemId(int arg0) {\n return 0;\n }\n\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n //Log.d(\"SectionListAdapter\", \"enter getView\");\n View v = convertView;\n\n v = mLayoutInflater.inflate(R.layout.section_item, null);\n\n Log.d(\"SectionListAdapter\", \"position is \" + position);\n\n TextView capacity = (TextView) v.findViewById(R.id.section_item_capacity);\n TextView lec = (TextView) v.findViewById(R.id.section_item_lec);\n TextView loc = (TextView) v.findViewById(R.id.section_item_loc);\n TextView time = (TextView) v.findViewById(R.id.section_item_time);\n TextView prof = (TextView) v.findViewById(R.id.section_item_prof);\n\n loc.setVisibility(View.GONE);\n prof.setVisibility(View.GONE);\n\n TestObject testInfo = getItem(position);\n\n lec.setText(testInfo.getSection());\n time.setText(testInfo.getTime());\n //prof.setText(mBundle.getStringArrayList(\"LEC_PROF\").get(position));\n //loc.setText(mBundle.getStringArrayList(\"LEC_LOC\").get(position));\n\n capacity.setText(testInfo.getTotal() + \"/\" + testInfo.getCapacity());\n\n return v;\n }\n\n}", "public class TutListAdapter extends BaseAdapter {\n ArrayList<TutorialObject> mArrayList;\n Context mContext;\n LayoutInflater mLayoutInflater;\n\n public TutListAdapter(Context context, int textViewResourceId, Bundle bundle) {\n mLayoutInflater = LayoutInflater.from(context);\n mArrayList = bundle.getParcelableArrayList(Constants.tutorialObjectListKey);\n mContext = context;\n Log.d(\"SectionListAdapter\", \"Course name is \" + bundle.getString(\"courseName\"));\n }\n\n\n @Override\n public TutorialObject getItem(int i) {\n return mArrayList.get(i);\n }\n\n @Override\n public int getCount() {\n return mArrayList != null ? mArrayList.size() : 0;\n }\n\n @Override\n public long getItemId(int arg0) {\n return 0;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n //Log.d(\"SectionListAdapter\", \"enter getView\");\n View v = convertView;\n\n v = mLayoutInflater.inflate(R.layout.section_item, null);\n\n\n Log.d(\"SectionListAdapter\", \"position is \" + position);\n\n TextView capacity = (TextView) v.findViewById(R.id.section_item_capacity);\n TextView lec = (TextView) v.findViewById(R.id.section_item_lec);\n TextView loc = (TextView) v.findViewById(R.id.section_item_loc);\n TextView time = (TextView) v.findViewById(R.id.section_item_time);\n\n TutorialObject tutorialInfo = getItem(position);\n\n lec.setText(tutorialInfo.getSection());\n time.setText(tutorialInfo.getTime());\n loc.setText(tutorialInfo.getLocation());\n\n int enroll_total = Integer.parseInt(tutorialInfo.getTotal());\n int enroll_cap = Integer.parseInt(tutorialInfo.getCapacity());\n\n if(enroll_total/enroll_cap >= 1)\n capacity.setTextColor(mContext.getResources().getColor(R.color.fab_color_1));\n else\n capacity.setTextColor(mContext.getResources().getColor(R.color.light_green));\n capacity.setText(enroll_total + \"/\" + enroll_cap);\n\n return v;\n }\n\n}", "public class Constants {\n public static String UWAPIROOT = \"https://api.uwaterloo.ca/v2/\";\n public static List<Reminder_item> holiday_2015;\n public static List<Reminder_item> sample_reminder;\n\n public static String lectureSectionObjectListKey = \"LEC_OBJECTS\";\n public static String testObjectListKey = \"TST_OBJECTS\";\n public static String tutorialObjectListKey = \"TUT_OBJECTS\";\n public static String finalObjectListKey = \"FINAL_OBJECTS\";\n\n // default term value\n public static Integer defaultCurTermNum = 1161;\n public static String defaultCurTermName = \"Winter 2016 (Current)\";\n public static Integer defaultNextTermNum = 1165;\n public static String defaultNextTermName = \"Spring 2016 (Next)\";\n\n // temporarily hardcoded\n // Note: month off by one because of unix time standard\n public static GregorianCalendar nextTermStartDate = new GregorianCalendar(2016, 4, 2);\n\n\n\n public static List<Reminder_item> get_sample_reminder(){\n sample_reminder = new ArrayList<>();\n Reminder_item tmp = new Reminder_item(UUID.randomUUID().toString(),\n \"Final end\",\"\", 2015, 7, 15, \"d\");\n sample_reminder.add(tmp);\n tmp = new Reminder_item(UUID.randomUUID().toString(),\n \"Next term start\",\"\", 2015, 8, 14, \"d\");\n sample_reminder.add(tmp);\n tmp = new Reminder_item(UUID.randomUUID().toString(),\n \"First penalty end\",\"\", 2015, 9, 3, \"d\");\n sample_reminder.add(tmp);\n tmp = new Reminder_item(UUID.randomUUID().toString(),\n \"Late fee for fall\",\"\", 2015, 7, 28, \"d\");\n sample_reminder.add(tmp);\n\n return sample_reminder;\n }\n\n public static List<Reminder_item> get_holidays(){\n holiday_2015 = new ArrayList<>();\n Reminder_item tmp = new Reminder_item(UUID.randomUUID().toString(),\n \"Civic Holiday\",\"\", 2015, 7, 3, \"d\");\n holiday_2015.add(tmp);\n tmp = new Reminder_item(UUID.randomUUID().toString(),\n \"Labour Day\",\"\", 2015, 8, 7, \"d\");\n holiday_2015.add(tmp);\n tmp = new Reminder_item(UUID.randomUUID().toString(),\n \"Thanksgiving\",\"\", 2015, 9, 12, \"d\");\n holiday_2015.add(tmp);\n tmp = new Reminder_item(UUID.randomUUID().toString(),\n \"Christmas\",\"\", 2015, 11, 25, \"d\");\n holiday_2015.add(tmp);\n\n tmp = new Reminder_item(UUID.randomUUID().toString(),\n \"Boxing Day\",\"\", 2015, 11, 28, \"d\");\n holiday_2015.add(tmp);\n\n return holiday_2015;\n }\n}" ]
import android.app.Activity; import android.app.AlertDialog; import android.app.Fragment; import android.content.DialogInterface; import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v7.widget.AppCompatButton; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.YC2010.MyClass.model.CourseInfo; import com.YC2010.MyClass.model.LectureSectionObject; import com.YC2010.MyClass.R; import com.YC2010.MyClass.data.CoursesDBHandler; import com.YC2010.MyClass.ui.adapters.SectionListAdapter; import com.YC2010.MyClass.ui.adapters.TstListAdapter; import com.YC2010.MyClass.ui.adapters.TutListAdapter; import com.YC2010.MyClass.utils.Constants; import java.util.ArrayList;
package com.YC2010.MyClass.ui.fragments; /** * Created by Danny on 2015/12/26. */ public class SearchScheduleFragment extends Fragment { private Activity mActivity; private View mView; private Bundle mFetchedResult; private boolean mCourseTaken; private String mTakenCourseNumber; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.mActivity = getActivity(); this.mFetchedResult = this.getArguments(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.fragment_search_schedule, container, false); TextView courseName = (TextView) mView.findViewById(R.id.course_name); courseName.setText(mFetchedResult.getString("courseName")); setupLists(); setupAddButton(); return mView; } private void setupLists() { // get default divider int[] attrs = {android.R.attr.listDivider}; TypedArray ta = mActivity.obtainStyledAttributes(attrs); Drawable divider = ta.getDrawable(0); ta.recycle(); LinearLayout mLecLinearLayout = (LinearLayout) mView.findViewById(R.id.lec_list); SectionListAdapter LecAdapter = new SectionListAdapter(mActivity, R.layout.section_item, mFetchedResult); for (int i = 0; i < LecAdapter.getCount(); i++) { View view = LecAdapter.getView(i, null, mLecLinearLayout); mLecLinearLayout.addView(view); mLecLinearLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE | LinearLayout.SHOW_DIVIDER_BEGINNING); mLecLinearLayout.setDividerDrawable(divider); } TextView lec = (TextView) mView.findViewById(R.id.lec); if (lec != null) { lec.setVisibility(View.VISIBLE); } if (mFetchedResult.getBoolean("has_tst", false)) { TextView tst = (TextView) mView.findViewById(R.id.tst); if (tst != null) { tst.setVisibility(View.VISIBLE); } LinearLayout mTstLinearLayout = (LinearLayout) mView.findViewById(R.id.tst_list);
TstListAdapter TstAdapter = new TstListAdapter(mActivity, R.layout.section_item, mFetchedResult);
4
kakao/hbase-tools
hbase0.98/hbase-manager-0.98/src/main/java/com/kakao/hbase/manager/command/MC.java
[ "public abstract class Args {\n public static final String OPTION_REGION = \"region\";\n public static final String OPTION_OUTPUT = \"output\";\n public static final String OPTION_SKIP_EXPORT = \"skip-export\";\n public static final String OPTION_VERBOSE = \"verbose\";\n public static final String OPTION_DEBUG = \"debug\";\n public static final String OPTION_KERBEROS_CONFIG = \"krbconf\";\n public static final String OPTION_KEY_TAB = \"keytab\";\n public static final String OPTION_KEY_TAB_SHORT = \"k\";\n public static final String OPTION_REGION_SERVER = \"rs\";\n public static final String OPTION_PRINCIPAL = \"principal\";\n public static final String OPTION_PRINCIPAL_SHORT = \"p\";\n public static final String OPTION_REALM = \"realm\";\n public static final String OPTION_FORCE_PROCEED = \"force-proceed\";\n public static final String OPTION_KEEP = \"keep\";\n public static final String OPTION_DELETE_SNAPSHOT_FOR_NOT_EXISTING_TABLE = \"delete-snapshot-for-not-existing-table\";\n public static final String OPTION_SKIP_FLUSH = \"skip-flush\";\n public static final String OPTION_EXCLUDE = \"exclude\";\n public static final String OPTION_OVERRIDE = \"override\";\n public static final String OPTION_AFTER_FAILURE = \"after-failure\";\n public static final String OPTION_AFTER_SUCCESS = \"after-success\";\n public static final String OPTION_AFTER_FINISH = \"after-finish\";\n public static final String OPTION_CLEAR_WATCH_LEAK = \"clear-watch-leak\";\n public static final String OPTION_OPTIMIZE = \"optimize\";\n public static final String OPTION_TURN_BALANCER_OFF = \"turn-balancer-off\";\n public static final String OPTION_BALANCE_FACTOR = \"factor\";\n public static final String OPTION_TEST = \"test\"; // for test cases only\n public static final String OPTION_HTTP_PORT = \"port\";\n public static final String OPTION_INTERVAL = \"interval\";\n public static final String OPTION_MOVE_ASYNC = \"move-async\";\n public static final String OPTION_MAX_ITERATION = \"max-iteration\";\n public static final String OPTION_LOCALITY_THRESHOLD = \"locality\";\n public static final String OPTION_CF = \"cf\";\n public static final String OPTION_WAIT_UNTIL_FINISH = \"wait\";\n public static final String OPTION_INTERACTIVE = \"interactive\";\n public static final String OPTION_CONF = \"conf\";\n public static final String OPTION_CONF_SHORT = \"c\";\n public static final String OPTION_PHOENIX = \"phoenix-salting-table\";\n\n public static final String INVALID_ARGUMENTS = \"Invalid arguments\";\n public static final String ALL_TABLES = \"\";\n private static final int INTERVAL_DEFAULT_MS = 10 * 1000;\n protected final String zookeeperQuorum;\n protected final OptionSet optionSet;\n\n public Args(String[] args) throws IOException {\n OptionSet optionSetTemp = createOptionParser().parse(args);\n\n List<?> nonOptionArguments = optionSetTemp.nonOptionArguments();\n if (nonOptionArguments.size() < 1) throw new IllegalArgumentException(INVALID_ARGUMENTS);\n\n String arg = (String) nonOptionArguments.get(0);\n\n if (Util.isFile(arg)) {\n String[] newArgs = (String[]) ArrayUtils.addAll(parseArgsFile(arg), Arrays.copyOfRange(args, 1, args.length));\n this.optionSet = createOptionParser().parse(newArgs);\n this.zookeeperQuorum = (String) optionSet.nonOptionArguments().get(0);\n } else {\n this.optionSet = optionSetTemp;\n this.zookeeperQuorum = arg;\n }\n }\n\n public static String commonUsage() {\n return \" args file:\\n\"\n + \" Plain text file that contains args and options.\\n\"\n + \" common options:\\n\"\n + \" --\" + Args.OPTION_FORCE_PROCEED + \"\\n\"\n + \" Do not ask whether to proceed.\\n\"\n + \" --\" + Args.OPTION_DEBUG + \"\\n\"\n + \" Print debug log.\\n\"\n + \" --\" + Args.OPTION_VERBOSE + \"\\n\"\n + \" Print some more messages.\\n\"\n + \" -\" + Args.OPTION_CONF_SHORT + \"<key=value>, --\" + Args.OPTION_CONF + \"=<key=value>\\n\"\n + \" Set a configuration for HBase. Can be used many times for several configurations.\\n\"\n + \" --\" + Args.OPTION_AFTER_FAILURE + \"=<script>\\n\"\n + \" The script to run when this running is failed.\\n\"\n + \" The first argument of the script should be a message string.\\n\"\n + \" --\" + Args.OPTION_AFTER_SUCCESS + \"=<script>\\n\"\n + \" The script to run when this running is successfully finished.\\n\"\n + \" The first argument of the script should be a message string.\\n\"\n + \" --\" + Args.OPTION_AFTER_FINISH + \"=<script>\\n\"\n + \" The script to run when this running is successfully finished or failed.\\n\"\n + \" The first argument of the script should be a message string.\\n\"\n + \" -\" + Args.OPTION_KEY_TAB_SHORT + \"<keytab file>, --\" + Args.OPTION_KEY_TAB + \"=<keytab file>\\n\"\n + \" Kerberos keytab file. Use absolute path.\\n\"\n + \" -\" + Args.OPTION_PRINCIPAL_SHORT + \"<principal>, --\" + Args.OPTION_PRINCIPAL + \"=<principal>\\n\"\n + \" Kerberos principal.\\n\"\n + \" --\" + Args.OPTION_REALM + \"=<realm>\\n\"\n + \" Kerberos realm to use. Set this arg if it is not the default realm.\\n\"\n + \" --\" + Args.OPTION_KERBEROS_CONFIG + \"=<kerberos config file>\\n\"\n + \" Kerberos config file. Use absolute path.\\n\";\n }\n\n public static String[] parseArgsFile(String fileName) throws IOException {\n return parseArgsFile(fileName, false);\n }\n\n public static String[] parseArgsFile(String fileName, boolean fromResource) throws IOException {\n final String string;\n if (fromResource) {\n string = Util.readFromResource(fileName);\n } else {\n string = Util.readFromFile(fileName);\n }\n return string.split(\"[ \\n]\");\n }\n\n public static Set<String> tables(Args args, HBaseAdmin admin) throws IOException {\n return tables(args, admin, args.getTableName());\n }\n\n public static Set<String> tables(Args args, HBaseAdmin admin, String tableName) throws IOException {\n long startTimestamp = System.currentTimeMillis();\n Util.printVerboseMessage(args, Util.getMethodName() + \" - start\");\n if (tableName.equals(ALL_TABLES)) {\n Util.printVerboseMessage(args, Util.getMethodName() + \" - end\", startTimestamp);\n return null;\n } else {\n Set<String> tables = new TreeSet<>();\n HTableDescriptor[] hTableDescriptors = admin.listTables(tableName);\n if (hTableDescriptors == null) {\n return tables;\n } else {\n for (HTableDescriptor hTableDescriptor : hTableDescriptors) {\n // fixme\n // If hbase 1.0 client is connected to hbase 0.98,\n // admin.listTables(tableName) always returns all tables.\n // This is a workaround.\n String nameAsString = hTableDescriptor.getNameAsString();\n if (nameAsString.matches(tableName))\n tables.add(nameAsString);\n }\n }\n\n Util.printVerboseMessage(args, Util.getMethodName() + \" - end\", startTimestamp);\n return tables;\n }\n }\n\n @Override\n public String toString() {\n if (optionSet == null) return \"\";\n\n String nonOptionArgs = \"\";\n if (optionSet.nonOptionArguments() != null) {\n int i = 0;\n for (Object object : optionSet.nonOptionArguments()) {\n if (i > 0) nonOptionArgs += \" \";\n nonOptionArgs += \"\\\"\" + object.toString() + \"\\\"\";\n i++;\n }\n }\n\n String optionArgs = \"\";\n if (optionSet.asMap() != null) {\n int i = 0;\n for (Map.Entry<OptionSpec<?>, List<?>> entry : optionSet.asMap().entrySet()) {\n if (entry.getValue().size() > 0) {\n if (i > 0) optionArgs += \" \";\n optionArgs += \"--\" + entry.getKey().options().get(0) + \"=\\\"\" + entry.getValue().get(0) + \"\\\"\";\n i++;\n }\n }\n\n }\n\n return nonOptionArgs + \" \" + optionArgs;\n }\n\n public String getTableName() {\n if (optionSet.nonOptionArguments().size() > 1) {\n return (String) optionSet.nonOptionArguments().get(1);\n } else {\n return Args.ALL_TABLES;\n }\n }\n\n public String getZookeeperQuorum() {\n return zookeeperQuorum;\n }\n\n protected abstract OptionParser createOptionParser();\n\n protected OptionParser createCommonOptionParser() {\n OptionParser optionParser = new OptionParser();\n optionParser.accepts(OPTION_FORCE_PROCEED);\n optionParser.accepts(OPTION_TEST);\n optionParser.accepts(OPTION_DEBUG);\n optionParser.accepts(OPTION_VERBOSE);\n optionParser.accepts(OPTION_CONF).withRequiredArg().ofType(String.class);\n optionParser.accepts(OPTION_CONF_SHORT).withRequiredArg().ofType(String.class);\n optionParser.accepts(OPTION_KEY_TAB).withRequiredArg().ofType(String.class);\n optionParser.accepts(OPTION_KEY_TAB_SHORT).withRequiredArg().ofType(String.class);\n optionParser.accepts(OPTION_PRINCIPAL).withRequiredArg().ofType(String.class);\n optionParser.accepts(OPTION_PRINCIPAL_SHORT).withRequiredArg().ofType(String.class);\n optionParser.accepts(OPTION_REALM).withRequiredArg().ofType(String.class);\n optionParser.accepts(OPTION_KERBEROS_CONFIG).withRequiredArg().ofType(String.class);\n optionParser.accepts(OPTION_AFTER_FAILURE).withRequiredArg().ofType(String.class);\n optionParser.accepts(OPTION_AFTER_SUCCESS).withRequiredArg().ofType(String.class);\n optionParser.accepts(OPTION_AFTER_FINISH).withRequiredArg().ofType(String.class);\n return optionParser;\n }\n\n public Map<String, String> getConfigurations() {\n Map<String, String> result = new HashMap<>();\n if (optionSet.has(OPTION_CONF)) {\n result.putAll(parseConf(OPTION_CONF));\n }\n if (optionSet.has(OPTION_CONF_SHORT)) {\n result.putAll(parseConf(OPTION_CONF_SHORT));\n }\n return result;\n }\n\n private Map<String, String> parseConf(String option) {\n Map<String, String> result = new HashMap<>();\n List<?> objects = optionSet.valuesOf(option);\n for (Object confArg : objects) {\n String confStr = ((String) confArg);\n int splitPoint = confStr.indexOf(\"=\");\n String key = confStr.substring(0, splitPoint);\n String value = confStr.substring(splitPoint + 1);\n result.put(key, value);\n }\n return result;\n }\n\n public String getAfterFailureScript() {\n if (optionSet.has(OPTION_AFTER_FAILURE)) {\n return (String) optionSet.valueOf(OPTION_AFTER_FAILURE);\n } else {\n return null;\n }\n }\n\n public String getAfterSuccessScript() {\n if (optionSet.has(OPTION_AFTER_SUCCESS)) {\n return (String) optionSet.valueOf(OPTION_AFTER_SUCCESS);\n } else {\n return null;\n }\n }\n\n public String getAfterFinishScript() {\n if (optionSet.has(OPTION_AFTER_FINISH)) {\n return (String) optionSet.valueOf(OPTION_AFTER_FINISH);\n } else {\n return null;\n }\n }\n\n public int getIntervalMS() {\n if (optionSet.has(OPTION_INTERVAL))\n return (Integer) optionSet.valueOf(OPTION_INTERVAL) * 1000;\n else return INTERVAL_DEFAULT_MS;\n }\n\n public boolean has(String optionName) {\n return optionSet.has(optionName);\n }\n\n public boolean has(String optionLongName, String optionShortName) {\n return optionSet.has(optionLongName) || optionSet.has(optionShortName);\n }\n\n public Object valueOf(String optionName) {\n Object arg = optionSet.valueOf(optionName);\n if (arg != null && arg instanceof String) {\n String argString = ((String) arg).trim();\n return argString.length() == 0 ? null : argString;\n } else {\n return arg;\n }\n }\n\n public Object valueOf(String optionLongName, String optionShortName) {\n Object arg = optionSet.valueOf(optionName(optionLongName, optionShortName));\n if (arg != null && arg instanceof String) {\n String argString = ((String) arg).trim();\n return argString.length() == 0 ? null : argString;\n } else {\n return arg;\n }\n }\n\n private String optionName(String optionLongName, String optionShortName) {\n if (has(optionLongName)) return optionLongName;\n else return optionShortName;\n }\n\n public OptionSet getOptionSet() {\n return optionSet;\n }\n\n public boolean isForceProceed() {\n return optionSet.has(OPTION_FORCE_PROCEED);\n }\n\n public String hashStr() {\n return Integer.toHexString(optionSet.hashCode());\n }\n}", "public class Constant {\n public static final Charset CHARSET = StandardCharsets.UTF_8;\n public static final long WAIT_INTERVAL_MS = 1000;\n public static final long LARGE_WAIT_INTERVAL_MS = 60000;\n public static final long SMALL_WAIT_INTERVAL_MS = 3000;\n public static final int TRY_MAX = 20;\n public static final int TRY_MAX_SMALL = 3;\n public static final String TABLE_DELIMITER = \",\";\n public static final String MESSAGE_CANNOT_MOVE = \"Can not move region\";\n public static final String MESSAGE_DISABLED_OR_NOT_FOUND_TABLE = \"Disabled or not found table\";\n public static final String MESSAGE_NEED_REFRESH = \"need refresh\";\n public static final String UNIT_TEST_TABLE_PREFIX = \"UNIT_TEST_\";\n public static final String MESSAGE_INVALID_DATE_FORMAT = \"Invalid date format\";\n public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n public static final SimpleDateFormat DATE_FORMAT_ARGS = new SimpleDateFormat(\"yyyyMMddHHmmss\");\n\n private Constant() {\n }\n}", "public class Util {\n public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n\n static {\n Util.setLoggingThreshold(\"ERROR\");\n }\n\n private Util() {\n }\n\n public static void setLoggingThreshold(String loggingLevel) {\n Properties props = new Properties();\n props.setProperty(\"log4j.threshold\", loggingLevel);\n PropertyConfigurator.configure(props);\n }\n\n public static void validateTable(HBaseAdmin admin, String tableName) throws IOException, InterruptedException {\n if (tableName.equals(Args.ALL_TABLES)) return;\n\n boolean tableExists = false;\n try {\n if (tableName.contains(Constant.TABLE_DELIMITER)) {\n String[] tables = tableName.split(Constant.TABLE_DELIMITER);\n for (String table : tables) {\n tableExists = admin.tableExists(table);\n }\n } else {\n tableExists = admin.listTables(tableName).length > 0;\n }\n } catch (Exception e) {\n Thread.sleep(1000);\n System.out.println();\n System.out.println(admin.getConfiguration().get(\"hbase.zookeeper.quorum\") + \" is invalid zookeeper quorum\");\n System.exit(1);\n }\n if (tableExists) {\n try {\n if (!admin.isTableEnabled(tableName)) {\n throw new InvalidTableException(\"Table is not enabled.\");\n }\n } catch (Exception ignore) {\n }\n } else {\n throw new InvalidTableException(\"Table does not exist.\");\n }\n }\n\n public static boolean isMoved(HBaseAdmin admin, String tableName, String regionName, String serverNameTarget) {\n try (HTable table = new HTable(admin.getConfiguration(), tableName)) {\n NavigableMap<HRegionInfo, ServerName> regionLocations = table.getRegionLocations();\n for (Map.Entry<HRegionInfo, ServerName> regionLocation : regionLocations.entrySet()) {\n if (regionLocation.getKey().getEncodedName().equals(regionName)) {\n return regionLocation.getValue().getServerName().equals(serverNameTarget);\n }\n }\n\n if (!existsRegion(regionName, regionLocations.keySet()))\n return true; // skip moving\n } catch (IOException e) {\n return false;\n }\n return false;\n }\n\n public static boolean existsRegion(String regionName, Set<HRegionInfo> regionLocations) {\n boolean regionExists = false;\n for (HRegionInfo hRegionInfo : regionLocations) {\n if (hRegionInfo.getEncodedName().equals(regionName))\n regionExists = true;\n }\n return regionExists;\n }\n\n public static boolean askProceed() {\n System.out.print(\"Proceed (Y or N)? \");\n Scanner scanner = new Scanner(System.in);\n String s = scanner.nextLine();\n return s.toUpperCase().equals(\"Y\");\n }\n\n public static long printVerboseMessage(Args args, String message, long startTimestamp) {\n long currentTimestamp = System.currentTimeMillis();\n if (args != null && args.has(Args.OPTION_VERBOSE)) {\n System.out.println(now() + \" - \" + message + \" - Duration(ms) - \" + (currentTimestamp - startTimestamp));\n }\n return currentTimestamp;\n }\n\n public static void printVerboseMessage(Args args, String message) {\n if (args != null && args.has(Args.OPTION_VERBOSE))\n System.out.println(now() + \" - \" + message);\n }\n\n public static void printMessage(String message) {\n System.out.println(now() + \" - \" + message);\n }\n\n private static String now() {\n return DATE_FORMAT.format(System.currentTimeMillis());\n }\n\n public static String getResource(String rsc) throws IOException {\n StringBuilder sb = new StringBuilder();\n\n ClassLoader cLoader = Util.class.getClassLoader();\n try (InputStream i = cLoader.getResourceAsStream(rsc)) {\n BufferedReader r = new BufferedReader(new InputStreamReader(i));\n\n String l;\n while ((l = r.readLine()) != null) {\n sb.append(l).append(\"\\n\");\n }\n }\n return sb.toString();\n }\n\n private static String readString(Reader reader) throws IOException {\n StringBuilder sb = new StringBuilder();\n try (BufferedReader bufferedReader = new BufferedReader(reader)) {\n char[] buffer = new char[1000];\n int read;\n while ((read = bufferedReader.read(buffer)) != -1) {\n sb.append(buffer, 0, read);\n }\n }\n return sb.toString();\n }\n\n public static String readFromResource(String fileName) throws IOException {\n try (InputStream in = Util.class.getClassLoader().getResourceAsStream(fileName)) {\n return readString(new InputStreamReader(in));\n }\n }\n\n public static String readFromFile(String fileName) throws IOException {\n return readString(new FileReader(fileName));\n }\n\n public static boolean isFile(String path) {\n File file = new File(path);\n return file.exists() && !file.isDirectory();\n }\n\n public static Set<String> parseTableSet(HBaseAdmin admin, Args args) throws IOException {\n Set<String> tableSet = new HashSet<>();\n String tableArg = (String) args.getOptionSet().nonOptionArguments().get(1);\n if (tableArg.contains(Constant.TABLE_DELIMITER)) {\n String[] tableArgs = tableArg.split(Constant.TABLE_DELIMITER);\n for (String arg : tableArgs) {\n for (HTableDescriptor hTableDescriptor : admin.listTables(arg)) {\n tableSet.add(hTableDescriptor.getNameAsString());\n }\n }\n } else {\n for (HTableDescriptor hTableDescriptor : admin.listTables(tableArg)) {\n String tableName = hTableDescriptor.getNameAsString();\n if (args.has(Args.OPTION_TEST) && !tableName.startsWith(\"UNIT_TEST_\")) {\n continue;\n }\n tableSet.add(tableName);\n }\n }\n return tableSet;\n }\n\n @SuppressWarnings(\"deprecation\")\n public static String getRegionInfoString(HRegionInfo regionA) {\n return \"{TABLE => \" + Bytes.toString(regionA.getTableName())\n + \", ENCODED => \" + regionA.getEncodedName()\n + \", STARTKEY => '\" + Bytes.toStringBinary(regionA.getStartKey())\n + \"', ENDKEY => '\" + Bytes.toStringBinary(regionA.getEndKey()) + \"'\";\n }\n\n public static void sendAlertAfterFailed(Args args, Class clazz, String message) {\n if (args != null && args.getAfterFailureScript() != null)\n AlertSender.send(args.getAfterFailureScript(),\n \"FAIL - \" + clazz.getSimpleName()\n + \" - \" + message\n + \" - \" + args.toString());\n sendAlertAfterFinish(args, clazz, message, false);\n }\n\n public static void sendAlertAfterSuccess(Args args, Class clazz) {\n sendAlertAfterSuccess(args, clazz, null);\n }\n\n public static void sendAlertAfterSuccess(Args args, Class clazz, String message) {\n if (args != null && args.getAfterSuccessScript() != null)\n AlertSender.send(args.getAfterSuccessScript(),\n \"SUCCESS - \" + clazz.getSimpleName()\n + (message == null || message.equals(\"\") ? \"\" : \" - \" + message)\n + \" - \" + args.toString());\n sendAlertAfterFinish(args, clazz, message, true);\n }\n\n public static void sendAlertAfterFinish(Args args, Class clazz, String message, boolean success) {\n if (args != null && args.getAfterFinishScript() != null)\n AlertSender.send(args.getAfterFinishScript(),\n (success ? \"SUCCESS - \" : \"FAIL - \") + clazz.getSimpleName()\n + (message == null || message.equals(\"\") ? \"\" : \" - \" + message)\n + \" - \" + args.toString());\n }\n\n public static String getMethodName() {\n StackTraceElement current = Thread.currentThread().getStackTrace()[2];\n return current.getClassName() + \".\" + current.getMethodName();\n }\n\n public static long parseTimestamp(String timestampString) {\n try {\n Date date = Constant.DATE_FORMAT_ARGS.parse(timestampString);\n if (date.compareTo(new Date(System.currentTimeMillis())) > 0)\n throw new IllegalArgumentException(Constant.MESSAGE_INVALID_DATE_FORMAT);\n return date.getTime();\n } catch (ParseException e) {\n throw new IllegalArgumentException(Constant.MESSAGE_INVALID_DATE_FORMAT);\n }\n }\n\n public static boolean askProceedInteractively(Args args, boolean printNewLine) {\n if (args.has(Args.OPTION_INTERACTIVE)) {\n if (args.has(Args.OPTION_FORCE_PROCEED)) {\n if (printNewLine) System.out.println();\n } else {\n System.out.print(\" - \");\n if (!askProceed()) return false;\n }\n } else {\n if (printNewLine) System.out.println();\n }\n return true;\n }\n}", "public class CommandAdapter {\n\n public static List<RegionPlan> makePlan(HBaseAdmin admin, Map<ServerName, List<HRegionInfo>> clusterState, Configuration conf) throws IOException {\n StochasticLoadBalancer balancer = new StochasticLoadBalancer() {\n @Override\n protected boolean needsBalance(Cluster c) {\n return true;\n }\n };\n balancer.setConf(conf);\n balancer.setClusterStatus(admin.getClusterStatus());\n List<RegionPlan> regionPlanList = balancer.balanceCluster(clusterState);\n return regionPlanList == null ? new ArrayList<RegionPlan>() : regionPlanList;\n }\n\n public static List<RegionPlan> makePlan(HBaseAdmin admin, List<RegionPlan> newRegionPlan) throws IOException {\n // snapshot current region assignment\n Map<HRegionInfo, ServerName> regionAssignmentMap = createRegionAssignmentMap(admin);\n\n // update with new plan\n for (RegionPlan regionPlan : newRegionPlan) {\n regionAssignmentMap.put(regionPlan.getRegionInfo(), regionPlan.getDestination());\n }\n\n Map<ServerName, List<HRegionInfo>> clusterState = initializeRegionMap(admin);\n for (Map.Entry<HRegionInfo, ServerName> entry : regionAssignmentMap.entrySet())\n clusterState.get(entry.getValue()).add(entry.getKey());\n\n StochasticLoadBalancer balancer = new StochasticLoadBalancer();\n Configuration conf = admin.getConfiguration();\n conf.setFloat(\"hbase.regions.slop\", 0.2f);\n balancer.setConf(conf);\n return balancer.balanceCluster(clusterState);\n }\n\n // contains catalog tables\n private static Map<HRegionInfo, ServerName> createRegionAssignmentMap(HBaseAdmin admin) throws IOException {\n Map<HRegionInfo, ServerName> regionMap = new HashMap<>();\n for (ServerName serverName : admin.getClusterStatus().getServers()) {\n for (HRegionInfo hRegionInfo : admin.getOnlineRegions(serverName)) {\n regionMap.put(hRegionInfo, serverName);\n }\n }\n return regionMap;\n }\n\n public static List<HRegionInfo> getOnlineRegions(Args args, HBaseAdmin admin, ServerName serverName)\n throws IOException {\n long startTimestamp = System.currentTimeMillis();\n Util.printVerboseMessage(args, \"getOnlineRegions - start\");\n List<HRegionInfo> onlineRegions = admin.getOnlineRegions(serverName);\n Util.printVerboseMessage(args, \"getOnlineRegions - end\", startTimestamp);\n return onlineRegions;\n\n }\n\n public static boolean isMetaTable(String tableName) {\n return tableName.equals(TableName.META_TABLE_NAME.getNameAsString());\n }\n\n public static String metaTableName() {\n return TableName.META_TABLE_NAME.getNameAsString();\n }\n\n public static boolean isBalancerRunning(HBaseAdmin admin) throws IOException {\n boolean balancerRunning = admin.setBalancerRunning(false, false);\n if (balancerRunning) {\n admin.setBalancerRunning(true, false);\n }\n return balancerRunning;\n }\n\n public static Map<ServerName, List<HRegionInfo>> initializeRegionMap(HBaseAdmin admin) throws IOException {\n Map<ServerName, List<HRegionInfo>> regionMap = new TreeMap<>();\n for (ServerName serverName : admin.getClusterStatus().getServers())\n regionMap.put(serverName, new ArrayList<HRegionInfo>());\n return regionMap;\n }\n\n public static void fetch(String tableName, HConnection hConnection, Map<HRegionInfo, ServerName> regionServerMap, Object lock) {\n try (HTable table = (HTable) hConnection.getTable(tableName)) {\n NavigableMap<HRegionInfo, ServerName> regionLocations = table.getRegionLocations();\n //noinspection SynchronizationOnLocalVariableOrMethodParameter\n synchronized (lock) {\n for (Map.Entry<HRegionInfo, ServerName> entry : regionLocations.entrySet()) {\n regionServerMap.put(entry.getKey(), entry.getValue());\n }\n }\n } catch (IOException e) {\n System.out.println(e.getMessage());\n }\n }\n\n public static void loginUserFromSubject(Configuration conf, Subject subject) throws IOException {\n UserGroupInformation.setConfiguration(conf);\n UserGroupInformation.loginUserFromSubject(subject);\n }\n\n @SuppressWarnings(\"UnusedParameters\")\n public static NavigableMap<HRegionInfo, ServerName> regionServerMap(Args args, Configuration conf, HConnection connection, final boolean offlined) throws IOException {\n long timestamp = System.currentTimeMillis();\n\n final NavigableMap<HRegionInfo, ServerName> regionServerMap = new TreeMap<>();\n MetaScanner.DefaultMetaScannerVisitor visitor = new MetaScanner.DefaultMetaScannerVisitor() {\n @Override\n public boolean processRowInternal(Result rowResult) throws IOException {\n HRegionInfo info = HRegionInfo.getHRegionInfo(rowResult);\n ServerName serverName = HRegionInfo.getServerName(rowResult);\n\n if (info.getTable().getNameAsString().startsWith(\"hbase:\")) return true;\n if (info.isOffline() && !offlined) return true;\n regionServerMap.put(info, serverName);\n return true;\n }\n };\n MetaScanner.metaScan(connection, visitor);\n\n Util.printVerboseMessage(args, \"CommandAdapter.regionServerMap\", timestamp);\n return regionServerMap;\n }\n\n @SuppressWarnings(\"UnusedParameters\")\n public static NavigableMap<HRegionInfo, ServerName> regionServerMap(Args args, Configuration conf, HConnection connection, final Set<String> tableNames, final boolean offlined) throws IOException {\n long timestamp = System.currentTimeMillis();\n\n final NavigableMap<HRegionInfo, ServerName> regionServerMap = new TreeMap<>();\n\n if (tableNames.size() == 1) {\n return regionServerMap(args, conf, connection, tableNames.toArray(new String[1])[0], offlined);\n } else if (tableNames.size() > 1) {\n MetaScanner.DefaultMetaScannerVisitor visitor = new MetaScanner.DefaultMetaScannerVisitor() {\n @Override\n public boolean processRowInternal(Result rowResult) throws IOException {\n HRegionInfo info = HRegionInfo.getHRegionInfo(rowResult);\n ServerName serverName = HRegionInfo.getServerName(rowResult);\n\n String tableName = info.getTable().getNameAsString();\n if (tableName.startsWith(\"hbase:\")) return true;\n if (info.isOffline() && !offlined) return true;\n if (tableNames.contains(tableName))\n regionServerMap.put(info, serverName);\n return true;\n }\n };\n MetaScanner.metaScan(connection, visitor);\n }\n\n Util.printVerboseMessage(args, \"CommandAdapter.regionServerMap\", timestamp);\n return regionServerMap;\n }\n\n @SuppressWarnings(\"UnusedParameters\")\n private static NavigableMap<HRegionInfo, ServerName> regionServerMap(Args args, Configuration conf, HConnection connection, final String tableNameParam, final boolean offlined) throws IOException {\n long timestamp = System.currentTimeMillis();\n\n final NavigableMap<HRegionInfo, ServerName> regions = new TreeMap<>();\n TableName tableName = TableName.valueOf(tableNameParam);\n MetaScanner.MetaScannerVisitor visitor = new MetaScanner.TableMetaScannerVisitor(tableName) {\n @Override\n public boolean processRowInternal(Result rowResult) throws IOException {\n HRegionInfo info = HRegionInfo.getHRegionInfo(rowResult);\n ServerName serverName = HRegionInfo.getServerName(rowResult);\n\n if (info.isOffline() && !offlined) return true;\n regions.put(info, serverName);\n return true;\n }\n };\n MetaScanner.metaScan(connection, visitor, tableName);\n\n Util.printVerboseMessage(args, \"CommandAdapter.allTableRegions\", timestamp);\n return regions;\n }\n\n public static String getTableName(HRegionInfo hRegionInfo) {\n return hRegionInfo.getTable().getNameAsString();\n }\n\n public static boolean mergeRegions(Args args, HBaseAdmin admin, HRegionInfo regionA, HRegionInfo regionB) throws IOException {\n long timestamp = System.currentTimeMillis();\n\n if (HRegionInfo.areAdjacent(regionA, regionB)) {\n admin.mergeRegions(regionA.getEncodedNameAsBytes(), regionB.getEncodedNameAsBytes(), false);\n Util.printVerboseMessage(args, \"CommandAdapter.mergeRegions\", timestamp);\n return true;\n } else {\n Util.printVerboseMessage(args, \"CommandAdapter.mergeRegions\", timestamp);\n return false;\n }\n }\n\n public static List<HRegionInfo> adjacentEmptyRegions(List<HRegionInfo> emptyRegions) {\n List<HRegionInfo> adjacentEmptyRegions = new ArrayList<>();\n for (int i = 0; i < emptyRegions.size() - 1; i++) {\n HRegionInfo regionA = emptyRegions.get(i);\n HRegionInfo regionB = emptyRegions.get(i + 1);\n if (HRegionInfo.areAdjacent(regionA, regionB)) {\n adjacentEmptyRegions.add(regionA);\n adjacentEmptyRegions.add(regionB);\n i++;\n }\n }\n return adjacentEmptyRegions;\n }\n\n public static boolean isMajorCompacting(Args args, HBaseAdmin admin, String tableName)\n throws IOException, InterruptedException {\n CompactionState compactionState = admin.getCompactionState(tableName);\n return !(compactionState == CompactionState.NONE || compactionState == CompactionState.MINOR);\n }\n\n public static boolean isReallyEmptyRegion(HConnection connection,\n String tableName, HRegionInfo regionInfo) throws IOException {\n boolean emptyRegion = false;\n // verify really empty region by scanning records\n try (HTableInterface table = connection.getTable(tableName)) {\n Scan scan = new Scan(regionInfo.getStartKey(), regionInfo.getEndKey());\n FilterList filterList = new FilterList();\n filterList.addFilter(new KeyOnlyFilter());\n filterList.addFilter(new FirstKeyOnlyFilter());\n scan.setFilter(filterList);\n scan.setCacheBlocks(false);\n scan.setSmall(true);\n scan.setCaching(1);\n\n try (ResultScanner scanner = table.getScanner(scan)) {\n if (scanner.next() == null) emptyRegion = true;\n }\n }\n return emptyRegion;\n }\n\n public static Map<String, Map<String, String>> versionedRegionMap(HBaseAdmin admin, long timestamp)\n throws IOException {\n Map<String, Map<String, String>> regionLocationMap = new HashMap<>();\n try (HTable metaTable = new HTable(admin.getConfiguration(), metaTableName())) {\n Scan scan = new Scan();\n scan.setSmall(true);\n scan.setCaching(1000);\n scan.setMaxVersions();\n ResultScanner scanner = metaTable.getScanner(scan);\n for (Result result : scanner) {\n List<Cell> columnCells = result.getColumnCells(\"info\".getBytes(), \"server\".getBytes());\n for (Cell cell : columnCells) {\n if (cell.getTimestamp() <= timestamp) {\n String tableName = Bytes.toString(HRegionInfo.getTableName(cell.getRow()));\n String encodeRegionName = HRegionInfo.encodeRegionName(cell.getRow());\n String regionServer = Bytes.toString(cell.getValue()).replaceAll(\":\", \",\");\n\n Map<String, String> innerMap = regionLocationMap.get(tableName);\n if (innerMap == null) {\n innerMap = new HashMap<>();\n regionLocationMap.put(tableName, innerMap);\n }\n if (innerMap.get(encodeRegionName) == null)\n innerMap.put(encodeRegionName, regionServer);\n }\n }\n }\n }\n return regionLocationMap;\n }\n\n public static ServerName create(String serverNameStr) {\n return ServerName.valueOf(serverNameStr);\n }\n}", "public class RegionLoadAdapter {\n public static final LoadEntry[] loadEntries = RegionLoadDelegator.loadEntries();\n private final Map<HRegionInfo, RegionLoadDelegator> regionLoadMap = new HashMap<>();\n\n public RegionLoadAdapter(HBaseAdmin admin, Map<byte[], HRegionInfo> regionMap, Args args) throws IOException {\n long timestamp = System.currentTimeMillis();\n\n ClusterStatus clusterStatus = admin.getClusterStatus();\n Collection<ServerName> serverNames = clusterStatus.getServers();\n for (ServerName serverName : serverNames) {\n ServerLoad serverLoad = clusterStatus.getLoad(serverName);\n for (Map.Entry<byte[], RegionLoad> entry : serverLoad.getRegionsLoad().entrySet()) {\n if (regionMap.get(entry.getKey()) != null)\n regionLoadMap.put(regionMap.get(entry.getKey()), new RegionLoadDelegator(entry.getValue()));\n }\n }\n\n Util.printVerboseMessage(args, \"RegionLoadAdapter\", timestamp);\n }\n\n public static int loadEntryOrdinal(LoadEntry loadEntry) {\n return Arrays.asList(loadEntries).indexOf(loadEntry);\n }\n\n public RegionLoadDelegator get(HRegionInfo hRegionInfo) {\n return regionLoadMap.get(hRegionInfo);\n }\n}", "public class RegionLoadDelegator {\n private final org.apache.hadoop.hbase.RegionLoad regionLoad;\n\n public RegionLoadDelegator(org.apache.hadoop.hbase.RegionLoad regionLoad) {\n this.regionLoad = regionLoad;\n }\n\n public static LoadEntry[] loadEntries() {\n return LoadEntry.values();\n }\n\n public int getStorefiles() {\n return regionLoad.getStorefiles();\n }\n\n public int getStoreUncompressedSizeMB() {\n return regionLoad.getStoreUncompressedSizeMB();\n }\n\n public int getStorefileSizeMB() {\n return regionLoad.getStorefileSizeMB();\n }\n\n public long getReadRequestsCount() {\n return regionLoad.getReadRequestsCount();\n }\n\n public long getWriteRequestsCount() {\n return regionLoad.getWriteRequestsCount();\n }\n\n public int getMemStoreSizeMB() {\n return regionLoad.getMemStoreSizeMB();\n }\n\n public long getCurrentCompactedKVs() {\n return regionLoad.getCurrentCompactedKVs();\n }\n\n public int getRegions() {\n return 1;\n }\n\n public float getDataLocality() {\n return regionLoad.getDataLocality();\n }\n}" ]
import java.io.IOException; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import com.google.common.annotations.VisibleForTesting; import com.kakao.hbase.common.Args; import com.kakao.hbase.common.Constant; import com.kakao.hbase.common.util.Util; import com.kakao.hbase.specific.CommandAdapter; import com.kakao.hbase.specific.RegionLoadAdapter; import com.kakao.hbase.specific.RegionLoadDelegator; import org.apache.hadoop.hbase.HRegionInfo; import org.apache.hadoop.hbase.NotServingRegionException; import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.client.HBaseAdmin; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.util.StringUtils;
/* * Copyright 2015 Kakao Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.kakao.hbase.manager.command; public class MC implements Command { private final HBaseAdmin admin; private final Args args; private final AtomicInteger mcCounter = new AtomicInteger(); private final Map<byte[], String> regionTableMap = new TreeMap<>(Bytes.BYTES_COMPARATOR); private final Map<byte[], Integer> regionSizeMap = new TreeMap<>(Bytes.BYTES_COMPARATOR); private final Map<byte[], Float> regionLocalityMap = new TreeMap<>(Bytes.BYTES_COMPARATOR); private final Map<byte[], String> regionRSMap = new TreeMap<>(Bytes.BYTES_COMPARATOR); private Map<String, NavigableMap<HRegionInfo, ServerName>> regionLocations = new HashMap<>(); // regions or tables private Set<byte[]> targets = null; private boolean tableLevel = false; public MC(HBaseAdmin admin, Args args) { if (args.getOptionSet().nonOptionArguments().size() != 2) { throw new IllegalArgumentException(Args.INVALID_ARGUMENTS); } this.admin = admin; this.args = args; } @SuppressWarnings("unused") public static String usage() { return "Run major compaction on tables.\n" + "usage: " + MC.class.getSimpleName().toLowerCase() + " <zookeeper quorum> <table regex> [options]\n" + " options:\n" + " --" + Args.OPTION_WAIT_UNTIL_FINISH + ": Wait until all of MCs are finished.\n" + " --" + Args.OPTION_INTERACTIVE + ": Ask whether to proceed MC for each region or table.\n" + " --" + Args.OPTION_REGION_SERVER + "=<RS regex>: Compact the regions on these RSs.\n" + " --" + Args.OPTION_CF + "=<CF>: Compact the regions of this CF.\n" + " --" + Args.OPTION_LOCALITY_THRESHOLD + "=<threshold%>: Compact only if the data locality of the region is lower than this threshold.\n" + Args.commonUsage(); } @VisibleForTesting int getMcCounter() { return mcCounter.get(); } @VisibleForTesting Set<byte[]> getTargets() { return targets; } @VisibleForTesting boolean isTableLevel() { return tableLevel; } @Override public void run() throws Exception { targets = Collections.newSetFromMap(new TreeMap<byte[], Boolean>(Bytes.BYTES_COMPARATOR)); tableLevel = false; // or region level Set<String> tables = Args.tables(args, admin); assert tables != null; for (String table : tables) { if (args.has(Args.OPTION_REGION_SERVER) || args.has(Args.OPTION_LOCALITY_THRESHOLD)) { // MC at region level tableLevel = false; if (args.has(Args.OPTION_REGION_SERVER)) { filterWithRsAndLocality(targets, table); } else { if (args.has(Args.OPTION_LOCALITY_THRESHOLD)) { filterWithLocalityOnly(targets, table); } } } else { // MC at table level tableLevel = true; targets.add(table.getBytes()); } } // todo check compaction queue before running if (tableLevel) { System.out.println(targets.size() + " tables will be compacted."); } else { System.out.println(targets.size() + " regions will be compacted."); } if (targets.size() == 0) return;
if (!args.isForceProceed() && !Util.askProceed()) return;
2
Martin20150405/Pano360
vrlib/src/main/java/com/martin/ads/vrlib/filters/base/OrthoFilter.java
[ "public enum PanoMode\n{\n MOTION,TOUCH,SINGLE_SCREEN,DUAL_SCREEN\n}", "public class Plane {\n private FloatBuffer mVerticesBuffer;\n private FloatBuffer mTexCoordinateBuffer;\n private final float TRIANGLES_DATA_CW[] = {\n -1.0f, -1.0f, 0f, //LD\n -1.0f, 1.0f, 0f, //LU\n 1.0f, -1.0f, 0f, //RD\n 1.0f, 1.0f, 0f //RU\n };\n\n public Plane(boolean isInGroup) {\n mVerticesBuffer = BufferUtils.getFloatBuffer(TRIANGLES_DATA_CW,0);\n if (isInGroup)\n mTexCoordinateBuffer = BufferUtils.getFloatBuffer(PlaneTextureRotationUtils.getRotation(Rotation.NORMAL, false, true), 0);\n else mTexCoordinateBuffer = BufferUtils.getFloatBuffer(PlaneTextureRotationUtils.TEXTURE_NO_ROTATION,0);\n }\n\n public void uploadVerticesBuffer(int positionHandle){\n FloatBuffer vertexBuffer = getVerticesBuffer();\n if (vertexBuffer == null) return;\n vertexBuffer.position(0);\n\n GLES20.glVertexAttribPointer(positionHandle, 3, GLES20.GL_FLOAT, false, 0, vertexBuffer);\n ShaderUtils.checkGlError(\"glVertexAttribPointer maPosition\");\n GLES20.glEnableVertexAttribArray(positionHandle);\n ShaderUtils.checkGlError(\"glEnableVertexAttribArray maPositionHandle\");\n }\n\n public void uploadTexCoordinateBuffer(int textureCoordinateHandle){\n FloatBuffer textureBuffer = getTexCoordinateBuffer();\n if (textureBuffer == null) return;\n textureBuffer.position(0);\n\n GLES20.glVertexAttribPointer(textureCoordinateHandle, 2, GLES20.GL_FLOAT, false, 0, textureBuffer);\n ShaderUtils.checkGlError(\"glVertexAttribPointer maTextureHandle\");\n GLES20.glEnableVertexAttribArray(textureCoordinateHandle);\n ShaderUtils.checkGlError(\"glEnableVertexAttribArray maTextureHandle\");\n }\n\n\n public FloatBuffer getVerticesBuffer() {\n return mVerticesBuffer;\n }\n\n public FloatBuffer getTexCoordinateBuffer() {\n return mTexCoordinateBuffer;\n }\n\n //only used to flip texture\n public void setTexCoordinateBuffer(FloatBuffer mTexCoordinateBuffer) {\n this.mTexCoordinateBuffer = mTexCoordinateBuffer;\n }\n\n public void setVerticesBuffer(FloatBuffer mVerticesBuffer) {\n this.mVerticesBuffer = mVerticesBuffer;\n }\n\n public void draw() {\n GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);\n }\n\n public Plane scale(float scalingFactor){\n float[] temp=new float[TRIANGLES_DATA_CW.length];\n System.arraycopy(TRIANGLES_DATA_CW,0,temp,0,TRIANGLES_DATA_CW.length);\n for(int i=0;i<temp.length;i++){\n temp[i]*=scalingFactor;\n }\n mVerticesBuffer = BufferUtils.getFloatBuffer(temp,0);\n return this;\n }\n\n public Plane resetTrianglesDataWithRect(RectF rectF){\n TRIANGLES_DATA_CW[0]=rectF.left; TRIANGLES_DATA_CW[1]=rectF.bottom;\n TRIANGLES_DATA_CW[3]=rectF.left; TRIANGLES_DATA_CW[4]=rectF.top;\n TRIANGLES_DATA_CW[6]=rectF.right; TRIANGLES_DATA_CW[7]=rectF.bottom;\n TRIANGLES_DATA_CW[9]=rectF.right; TRIANGLES_DATA_CW[10]=rectF.top;\n mVerticesBuffer = BufferUtils.getFloatBuffer(TRIANGLES_DATA_CW,0);\n return this;\n }\n\n}", "public class GLPassThroughProgram extends GLAbsProgram {\n\n private int uMVPMatrixHandle;\n private int uTextureSamplerHandle;\n\n public GLPassThroughProgram(Context context) {\n super(context, \"filter/vsh/pass_through.glsl\",\"filter/fsh/pass_through.glsl\");\n }\n\n @Override\n public void create() {\n super.create();\n uTextureSamplerHandle= GLES20.glGetUniformLocation(getProgramId(),\"sTexture\");\n ShaderUtils.checkGlError(\"glGetUniformLocation uniform sTexture\");\n uMVPMatrixHandle=GLES20.glGetUniformLocation(getProgramId(),\"uMVPMatrix\");\n ShaderUtils.checkGlError(\"glGetUniformLocation uMVPMatrix\");\n }\n\n\n public int getTextureSamplerHandle() {\n return uTextureSamplerHandle;\n }\n\n public int getMVPMatrixHandle() {\n return uMVPMatrixHandle;\n }\n}", "public class MatrixUtils {\n public static float IDENTITY_MATRIX[]=new float[16];\n static {\n Matrix.setIdentityM(IDENTITY_MATRIX,0);\n }\n\n public static void updateProjection(int imageWidth, int imageHeight,int surfaceWidth,int surfaceHeight,int adjustingMode,float[] projectionMatrix){\n switch (adjustingMode){\n case AdjustingMode.ADJUSTING_MODE_STRETCH:\n MatrixUtils.updateProjectionFill(projectionMatrix);\n break;\n case AdjustingMode.ADJUSTING_MODE_FIT_TO_SCREEN:\n MatrixUtils.updateProjectionFit(imageWidth,imageHeight,\n surfaceWidth,surfaceHeight,projectionMatrix);\n break;\n case AdjustingMode.ADJUSTING_MODE_CROP:\n MatrixUtils.updateProjectionCrop(imageWidth,imageHeight,\n surfaceWidth,surfaceHeight,projectionMatrix);\n break;\n default:\n throw new RuntimeException(\"Adjusting Mode not found!\");\n }\n }\n\n public static void updateProjectionFill(float[] projectionMatrix) {\n Matrix.setIdentityM(projectionMatrix,0);\n }\n\n public static void updateProjectionFit(int imageWidth, int imageHeight,int surfaceWidth,int surfaceHeight,float[] projectionMatrix) {\n float screenRatio=(float)surfaceWidth/surfaceHeight;\n float videoRatio=(float) imageWidth / imageHeight;\n if (videoRatio>screenRatio){\n Matrix.orthoM(projectionMatrix,0,-1f,1f,-videoRatio/screenRatio,videoRatio/screenRatio,-1f,1f);\n }else Matrix.orthoM(projectionMatrix,0,-screenRatio/videoRatio,screenRatio/videoRatio,-1f,1f,-1f,1f);\n }\n\n public static void updateProjectionCrop(int imageWidth, int imageHeight,int surfaceWidth,int surfaceHeight,float[] projectionMatrix) {\n float screenRatio=(float)surfaceWidth/surfaceHeight;\n float videoRatio=(float) imageWidth / imageHeight;\n //crop is just making the screen fit the image.\n //only one difference\n if (videoRatio<screenRatio){\n Matrix.orthoM(projectionMatrix,0,-1f,1f,-videoRatio/screenRatio,videoRatio/screenRatio,-1f,1f);\n }else Matrix.orthoM(projectionMatrix,0,-screenRatio/videoRatio,screenRatio/videoRatio,-1f,1f,-1f,1f);\n }\n}", "public class StatusHelper {\n private PanoStatus panoStatus;\n private PanoMode panoDisPlayMode;\n private PanoMode panoInteractiveMode;\n private Context context;\n public StatusHelper(Context context) {\n this.context = context;\n }\n\n public Context getContext() {\n return context;\n }\n\n public PanoStatus getPanoStatus() {\n return panoStatus;\n }\n\n public void setPanoStatus(PanoStatus panoStatus) {\n this.panoStatus = panoStatus;\n }\n\n public PanoMode getPanoDisPlayMode() {\n return panoDisPlayMode;\n }\n\n public void setPanoDisPlayMode(PanoMode panoDisPlayMode) {\n this.panoDisPlayMode = panoDisPlayMode;\n }\n\n public PanoMode getPanoInteractiveMode() {\n return panoInteractiveMode;\n }\n\n public void setPanoInteractiveMode(PanoMode panoInteractiveMode) {\n this.panoInteractiveMode = panoInteractiveMode;\n }\n}", "public class TextureUtils {\n private static final String TAG = \"TextureUtils\";\n\n public static void bindTexture2D(int textureId,int activeTextureID,int handle,int idx){\n if (textureId != GLEtc.NO_TEXTURE) {\n GLES20.glActiveTexture(activeTextureID);\n GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId);\n GLES20.glUniform1i(handle, idx);\n }\n }\n\n public static void bindTextureOES(int textureId,int activeTextureID,int handle,int idx){\n if (textureId != GLEtc.NO_TEXTURE) {\n GLES20.glActiveTexture(activeTextureID);\n GLES20.glBindTexture(GLEtc.GL_TEXTURE_EXTERNAL_OES, textureId);\n GLES20.glUniform1i(handle, idx);\n }\n }\n\n public static int loadTextureFromResources(Context context, int resourceId,int imageSize[]){\n return getTextureFromBitmap(\n BitmapUtils.loadBitmapFromRaw(context,resourceId),\n imageSize);\n }\n\n public static int loadTextureFromAssets(Context context, String filePath,int imageSize[]){\n return getTextureFromBitmap(\n BitmapUtils.loadBitmapFromAssets(context,filePath),\n imageSize);\n }\n\n //bitmap will be recycled after calling this method\n public static int getTextureFromBitmap(Bitmap bitmap,int imageSize[]){\n final int[] textureObjectIds=new int[1];\n GLES20.glGenTextures(1,textureObjectIds,0);\n if (textureObjectIds[0]==0){\n Log.d(TAG,\"Failed at glGenTextures\");\n return 0;\n }\n\n if (bitmap==null){\n Log.d(TAG,\"Failed at decoding bitmap\");\n GLES20.glDeleteTextures(1,textureObjectIds,0);\n return 0;\n }\n\n if(imageSize!=null && imageSize.length>=2){\n imageSize[0]=bitmap.getWidth();\n imageSize[1]=bitmap.getHeight();\n }\n\n GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,textureObjectIds[0]);\n\n GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,\n GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);\n GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,\n GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);\n GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,\n GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);\n GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,\n GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);\n GLUtils.texImage2D(GLES20.GL_TEXTURE_2D,0,bitmap,0);\n bitmap.recycle();\n\n GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,0);\n return textureObjectIds[0];\n }\n}" ]
import android.opengl.GLES20; import android.opengl.Matrix; import com.martin.ads.vrlib.constant.PanoMode; import com.martin.ads.vrlib.object.Plane; import com.martin.ads.vrlib.programs.GLPassThroughProgram; import com.martin.ads.vrlib.utils.MatrixUtils; import com.martin.ads.vrlib.utils.StatusHelper; import com.martin.ads.vrlib.utils.TextureUtils;
package com.martin.ads.vrlib.filters.base; /** * Created by Ads on 2016/11/19. * let the image pass through * and simply fit the image to the screen */ public class OrthoFilter extends AbsFilter { private int adjustingMode; private GLPassThroughProgram glPassThroughProgram; private Plane plane; private float[] projectionMatrix = new float[16]; private int videoWidth,videoHeight;
private StatusHelper statusHelper;
4
KMax/cqels
src/main/java/org/deri/cqels/engine/IndexedOnWindowBuff.java
[ "public class EnQuad {\n\tlong gID,sID,pID,oID;\n\tlong time;\n\tpublic EnQuad(long gID,long sID, long pID, long oID){\n\t\tthis.gID=gID;\n\t\tthis.sID=sID;\n\t\tthis.pID=pID;\n\t\tthis.oID=oID;\n\t\ttime=System.nanoTime();\n\t}\n\t\n\tpublic long getGID(){\n\t\treturn gID;\n\t}\n\t\n\tpublic long getSID(){\n\t\treturn sID;\n\t}\n\t\n\tpublic long getPID(){\n\t\treturn pID;\n\t}\n\t\n\tpublic long getOID(){\n\t\treturn oID;\n\t}\n\t\n\tpublic long time(){ return time;};\n}", "public interface Mapping extends Map<Var, Long>{\n\t\n\n\tpublic long get(Var var); \n\t\n\tpublic void from(OpRouter router);\n\t\n\tpublic OpRouter from();\n\t\n\tpublic ExecContext getCtx();\n\t\n\tpublic Iterator<Var> vars();\n\t\n\tpublic void addParent(Mapping parent);\n\t\n\tpublic boolean hasParent();\n\t\n\tpublic boolean isCompatible(Mapping mapping);\n}", "public class MappingIterCursorAll extends MappingIterCursor {\n\tArrayList<Var> vars;\n\tpublic MappingIterCursorAll(ExecContext context, Database database, ArrayList<Var> vars) {\n\t\tsuper(context, database);\n\t\tthis.vars = vars;\n\t\t//_readNext();\n\t}\n\t\n\t@Override\n\tpublic void _readNext() {\n\t\tDatabaseEntry key = new DatabaseEntry(); \n\t\tcurEnt = new DatabaseEntry();\n\t\tif(cursor == null) {\n\t\t\tcursor = db.openCursor(null, CursorConfig.READ_COMMITTED);\n\t\t}\n\t\tif(!(cursor.getNext(key, curEnt, LockMode.DEFAULT) == OperationStatus.SUCCESS)) {\n\t\t\tcurEnt = null;\n\t\t}\n\t\t//System.out.println(\"read Next not null\");\n\t}\n\n\t@Override\n\tprotected Mapping moveToNextMapping() {\n\t\tMapping mapping = null;\n\t\tif(curEnt != null) {\n\t\t\tmapping = org.deri.cqels.util.Utils.data2Mapping(context, curEnt, vars);\n\t\t\t_readNext();\n\t\t}\n\t\treturn mapping;\n\t}\n\t\n\t\n\n}", "public class MappingIterCursorByKey extends MappingIterCursor {\n\tDatabaseEntry key;\n\tMapping mapping;\n\tArrayList<Var> vars;\n\tpublic MappingIterCursorByKey(ExecContext context,Database db,DatabaseEntry key,Mapping mapping,ArrayList<Var> vars) {\n\t\tsuper(context, db);\n\t\tcurEnt = new DatabaseEntry();\n\t\tthis.key = key;\n\t\tthis.mapping = mapping;\n\t\tthis.vars = vars;\n\t}\n\t\n\t@Override\n\tpublic void _readNext() {\n\t\t// TODO Auto-generated method stub\n\t\tDatabaseEntry _key = new DatabaseEntry(); \n\t\tcurEnt = new DatabaseEntry();\n\t\tif(cursor == null) {\n\t\t\tcursor = db.openCursor(null, CursorConfig.READ_COMMITTED);\n\t\t\tif(!(cursor.getSearchKey(key, curEnt, LockMode.DEFAULT) == OperationStatus.SUCCESS))\n\t\t\t\t\tcurEnt = null;\n\t\t}\n\t\telse{\n\t\t\tif(!(cursor.getNextDup(_key, curEnt, LockMode.DEFAULT) == OperationStatus.SUCCESS))\n\t\t\t\tcurEnt = null;\n\t\t}\n\t}\n\t\n\t@Override\n\tprotected Mapping moveToNextMapping() {\n\t\t Mapping _mapping = null;\n\t\tif(curEnt != null) {\n\t\t _mapping = org.deri.cqels.util.Utils.data2Mapping(context, curEnt, mapping, vars);\n\t\t _readNext();\n\t\t}\n\t\treturn _mapping;\n\t}\n}", "public class MappingIterCursorByRangeKey extends MappingIterCursor {\n\tDatabaseEntry key;\n\tMapping mapping,_nextMapping;\n\tArrayList<Var> vars;\n\tint idxLen;\n\tpublic MappingIterCursorByRangeKey(ExecContext context, Database db, DatabaseEntry key, \n\t\t\tMapping mapping, ArrayList<Var> vars, int idxLen) {\n\t\tsuper(context, db);\t\t\n\t\tthis.key = key;\n\t\tthis.mapping = mapping;\n\t\tthis.vars = vars;\n\t\tthis.idxLen = idxLen;\n\t}\n\t\n\t@Override\n\tpublic void _readNext() {\n\t\tDatabaseEntry _key = new DatabaseEntry(key.getData());\n\t\tcurEnt = new DatabaseEntry();\n\t\tif(cursor == null) {\n\t\t\tcursor = db.openCursor(null, CursorConfig.READ_COMMITTED);\n\t\t\tif((!(cursor.getSearchKeyRange(_key, curEnt, LockMode.DEFAULT) == OperationStatus.SUCCESS))\n\t\t\t\t\t|| Utils.outRange(curEnt, key, idxLen))\t\t\t\n\t\t\t\tcurEnt = null;\n\t\t}\n\t\telse {\n\t\t\tif((!(cursor.getNext(_key, curEnt, LockMode.DEFAULT) == OperationStatus.SUCCESS))\n\t\t\t\t\t|| Utils.outRange(curEnt, key, idxLen))\t\t\t\n\t\t\t\tcurEnt = null;\n\t\t}\n\t}\n\t\n\t@Override\n\tprotected Mapping moveToNextMapping() {\n\t\tMapping _mapping = null;\n\t\tif(curEnt != null){\n\t\t\t_mapping = Utils.data2Mapping(context, curEnt, mapping, vars);\n\t\t\t_readNext();\n\t\t}\n\t\treturn _mapping;\n\t}\t\n\n}", "public interface MappingIterator extends Closeable, Iterator<Mapping> {\n\n /**\n * Get next binding\n */\n public Mapping nextMapping();\n\n /**\n * Cancels the query as soon as is possible for the given iterator\n */\n public void cancel();\n}", "public class NullMappingIter extends MappingIter {\n\tprivate static NullMappingIter instance;\n\tpublic NullMappingIter() {\n\t\tsuper(null);\n\t}\n\t\n\tpublic static NullMappingIter instance() {\n\t\tif(instance==null) instance=new NullMappingIter(); \n\t\treturn instance;\n\t}\n\t\n\t@Override\n\tprotected void closeIterator() {\n\t\t// TODO Auto-generated method stub\n\n\t}\n\n\t@Override\n\tprotected boolean hasNextMapping() {\n\t\t// TODO Auto-generated method stub\n\t\treturn false;\n\t}\n\n\t@Override\n\tprotected Mapping moveToNextMapping() {\n\t\t// TODO Auto-generated method stub\n\t\treturn null;\n\t}\n\n\t@Override\n\tprotected void requestCancel() {\n\t\t// TODO Auto-generated method stub\n\n\t}\n\n}", "public class Utils {\n\n\tpublic static void _addBinding(Node node, HashMap<Var, Long> hMap,Mapping mapping, TupleInput input){\n\t\tif(node.isVariable()&&(!mapping.containsKey((Var)node)))\n\t\t\thMap.put((Var)node,input.readLong());\n\t}\n\t\n\t\n\tpublic static ArrayList<Var> quad2Vars(Quad quad){\n\t\tArrayList<Var> vars=new ArrayList<Var>();\n\t\tif(quad.getGraph().isVariable()) vars.add((Var)quad.getGraph());\n\t\tif(quad.getSubject().isVariable()) vars.add((Var)quad.getSubject());\n\t\tif(quad.getPredicate().isVariable()) vars.add((Var)quad.getPredicate());\n\t\tif(quad.getObject().isVariable()) vars.add((Var)quad.getObject());\n\t\treturn vars;\n\t}\n\t \n\tpublic static Mapping data2Mapping(ExecContext context,DatabaseEntry data,Mapping mapping,ArrayList<Var> vars){\n\t\treturn new MappingWrapped(context, data2MappingFilter(context, data, mapping, vars),mapping );\n\t}\n\t\n\tpublic static Mapping data2MappingFilter(ExecContext context,DatabaseEntry data,Mapping mapping, ArrayList<Var> vars){\n\t\tHashMap<Var, Long> hMap=new HashMap<Var, Long>(); \n\t\tTupleInput input= new TupleInput(data.getData());\t\n\t\tfor(int i=0;i<vars.size();i++){\n\t\t\tlong tmp=input.readLong();\n\t\t\tif(!mapping.containsKey(vars.get(i))) hMap.put(vars.get(i), tmp);\n\t\t}\n\t\treturn new HashMapping(context, hMap);\n\t}\n\t\n\tpublic static Mapping data2Mapping(ExecContext context,DatabaseEntry data, ArrayList<Var> vars){\n\t\tHashMap<Var, Long> hMap=new HashMap<Var, Long>(); \n\t\tTupleInput input= new TupleInput(data.getData());\t\n\t\tfor(int i=0;i<vars.size();i++)\n\t\t\thMap.put(vars.get(i), input.readLong());\n\t\t\n\t\treturn new HashMapping(context, hMap);\n\t}\n\n\tpublic static boolean outRange(DatabaseEntry data, DatabaseEntry range,int idxLen){\n\t\tTupleInput in1=new TupleInput(data.getData());\n\t\tTupleInput in2=new TupleInput(range.getData());\n\t\tfor(int i=0;i<idxLen;i++)\n\t\t\tif(in1.readLong()!=in2.readLong()) return true;\n\t\treturn false;\n\t}\n\n}" ]
import java.util.ArrayList; import java.util.concurrent.TimeUnit; import org.deri.cqels.data.EnQuad; import org.deri.cqels.data.Mapping; import org.deri.cqels.engine.iterator.MappingIterCursorAll; import org.deri.cqels.engine.iterator.MappingIterCursorByKey; import org.deri.cqels.engine.iterator.MappingIterCursorByRangeKey; import org.deri.cqels.engine.iterator.MappingIterator; import org.deri.cqels.engine.iterator.NullMappingIter; import org.deri.cqels.util.Utils; import com.hp.hpl.jena.sparql.algebra.Op; import com.hp.hpl.jena.sparql.core.Quad; import com.hp.hpl.jena.sparql.core.Var; import com.sleepycat.bind.tuple.LongBinding; import com.sleepycat.bind.tuple.TupleInput; import com.sleepycat.bind.tuple.TupleOutput; import com.sleepycat.je.Database; import com.sleepycat.je.DatabaseConfig; import com.sleepycat.je.DatabaseEntry; import com.sleepycat.je.SecondaryConfig; import com.sleepycat.je.SecondaryDatabase; import com.sleepycat.je.SecondaryKeyCreator;
package org.deri.cqels.engine; /** * @author Danh Le Phuoc * @organization DERI Galway, NUIG, Ireland www.deri.ie * @email danh.lephuoc@deri.org */ public class IndexedOnWindowBuff { ExecContext context; Quad quad; Database buff; Op op; OpRouter router; ArrayList<Var> vars; ArrayList<ArrayList<Integer>> indexes; SecondaryDatabase[] idxDbs; Window w; public IndexedOnWindowBuff(ExecContext context,Quad quad, OpRouter router, Window w){ this.context = context; this.quad = quad; this.router = router; this.op = router.getOp(); init(); this.w = w; //if(w==null) System.out.println("null "+quad); w.setBuff(buff); } public void init() { DatabaseConfig dbConfig = new DatabaseConfig(); dbConfig.setAllowCreate(true); dbConfig.setTemporary(true); //dbConfig.setTransactional(true); buff = context.env().openDatabase(null, "pri_synopsis_" + router.getId(), dbConfig); //System.out.println("ttrans "+dbConfig.getTransactional()); initIndexes(); } public void initIndexes() {
vars = Utils.quad2Vars(quad);
7
yunnet/kafkaEagle
src/main/java/org/smartloli/kafka/eagle/web/service/impl/AlarmServiceImpl.java
[ "public class AlarmDomain {\n\n\tprivate String group = \"\";\n\tprivate String topics = \"\";\n\tprivate long lag = 0L;\n\tprivate String owners = \"\";\n\tprivate String modifyDate = \"\";\n\n\tpublic String getGroup() {\n\t\treturn group;\n\t}\n\n\tpublic void setGroup(String group) {\n\t\tthis.group = group;\n\t}\n\n\tpublic String getTopics() {\n\t\treturn topics;\n\t}\n\n\tpublic void setTopics(String topics) {\n\t\tthis.topics = topics;\n\t}\n\n\tpublic String getOwners() {\n\t\treturn owners;\n\t}\n\n\tpublic void setOwners(String owners) {\n\t\tthis.owners = owners;\n\t}\n\n\tpublic long getLag() {\n\t\treturn lag;\n\t}\n\n\tpublic void setLag(long lag) {\n\t\tthis.lag = lag;\n\t}\n\n\tpublic String getModifyDate() {\n\t\treturn modifyDate;\n\t}\n\n\tpublic void setModifyDate(String modifyDate) {\n\t\tthis.modifyDate = modifyDate;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn new Gson().toJson(this);\n\t}\n\n}", "public class KafkaFactory implements KafkaProvider {\n\n\tpublic KafkaService create() {\n\t\treturn new KafkaServiceImpl();\n\t}\n}", "public interface KafkaService {\n\n\t/** Find topic and group exist in zookeeper. */\n\tpublic boolean findTopicAndGroupExist(String clusterAlias, String topic, String group);\n\n\t/** Obtaining metadata in zookeeper by topic. */\n\tpublic List<String> findTopicPartition(String clusterAlias, String topic);\n\n\t/** Get kafka active consumer topic. */\n\tpublic Map<String, List<String>> getActiveTopic(String clusterAlias);\n\n\t/** Get all broker list from zookeeper. */\n\tpublic String getAllBrokersInfo(String clusterAlias);\n\n\t/** Get all topic info from zookeeper. */\n\tpublic String getAllPartitions(String clusterAlias);\n\n\t/** Obtaining kafka consumer information from zookeeper. */\n\tpublic Map<String, List<String>> getConsumers(String clusterAlias);\n\n\t/** Obtaining kafka consumer page information from zookeeper. */\n\tpublic Map<String, List<String>> getConsumers(String clusterAlias, PageParamDomain page);\n\n\t/** Use Kafka low consumer API & get logsize size from zookeeper. */\n\tpublic long getLogSize(List<String> hosts, String topic, int partition);\n\n\t/** According to group, topic and partition to get offset from zookeeper. */\n\tpublic OffsetZkDomain getOffset(String clusterAlias, String topic, String group, int partition);\n\n\t/** According to topic and partition to obtain Replicas & Isr. */\n\tpublic String geyReplicasIsr(String clusterAlias, String topic, int partitionid);\n\n\t/** Use kafka console comand to create topic. */\n\tpublic Map<String, Object> create(String clusterAlias, String topicName, String partitions, String replic);\n\n\t/** Use kafka console command to delete topic. */\n\tpublic Map<String, Object> delete(String clusterAlias, String topicName);\n\n\t/** Find leader through topic. */\n\tpublic List<MetadataDomain> findLeader(String clusterAlias, String topic);\n\n\t/** Convert query kafka to topic in the sql message for standard sql. */\n\tpublic KafkaSqlDomain parseSql(String clusterAlias, String sql);\n\n\t/** Get kafka 0.10.x active consumer group & topics. */\n\tpublic Set<String> getKafkaActiverTopics(String clusterAlias, String group);\n\n\t/** Get kafka 0.10.x consumer group & topic information. */\n\tpublic String getKafkaConsumer(String clusterAlias);\n\n\t/** Get kafka consumer information pages. */\n\tpublic String getKafkaActiverSize(String clusterAlias, String group);\n\n\t/** Get kafka consumer groups. */\n\tpublic int getKafkaConsumerGroups(String clusterAlias);\n\n\t/** Get kafka consumer topics. */\n\tpublic Set<String> getKafkaConsumerTopic(String clusterAlias, String group);\n\n\t/** Get kafka consumer group & topic. */\n\tpublic String getKafkaConsumerGroupTopic(String clusterAlias, String group);\n\n}", "public class ZkFactory implements ZkProvider {\n\n\t@Override\n\tpublic ZkService create() {\n\t\treturn new ZkServiceImpl();\n\t}\n\n}", "public interface ZkService {\n\n\t/** Zookeeper delete command. */\n\tpublic String delete(String clusterAlias,String cmd);\n\n\t/** Zookeeper get command. */\n\tpublic String get(String clusterAlias,String cmd);\n\n\t/** Get alarmer information. */\n\tpublic String getAlarm(String clusterAlias);\n\n\t/** Get consumer data that has group and topic as the only sign. */\n\tpublic String getOffsets(String clusterAlias,String group, String topic);\n\n\t/** Insert new datasets. */\n\tpublic void insert(String clusterAlias,List<OffsetsLiteDomain> list);\n\n\t/** Insert new alarmer configure information. */\n\tpublic int insertAlarmConfigure(String clusterAlias,AlarmDomain alarm);\n\n\t/** Zookeeper ls command. */\n\tpublic String ls(String clusterAlias,String cmd);\n\n\t/**\n\t * Remove the metadata information in the Ke root directory in\n\t * zookeeper,with group and topic as the only sign.\n\t */\n\tpublic void remove(String clusterAlias,String group, String topic, String theme);\n\n\t/** Get zookeeper health status. */\n\tpublic String status(String host, String port);\n\n\t/** Get zookeeper cluster information. */\n\tpublic String zkCluster(String clusterAlias);\n\n\t/** Judge whether the zkcli is active. */\n\tpublic JSONObject zkCliStatus(String clusterAlias);\n\n}", "public interface AlarmService {\n\n\t/** Add alarmer interface. */\n\tpublic Map<String, Object> add(String clusterAlias,AlarmDomain alarm);\n\n\t/** Delete alarmer interface. */\n\tpublic void delete(String clusterAlias,String group, String topic);\n\n\t/** Get alarmer interface. */\n\tpublic String get(String clusterAlias,String formatter);\n\n\t/** List alarmer information. */\n\tpublic String list(String clusterAlias);\n\n}" ]
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.smartloli.kafka.eagle.common.domain.AlarmDomain; import org.smartloli.kafka.eagle.core.factory.KafkaFactory; import org.smartloli.kafka.eagle.core.factory.KafkaService; import org.smartloli.kafka.eagle.core.factory.ZkFactory; import org.smartloli.kafka.eagle.core.factory.ZkService; import org.smartloli.kafka.eagle.web.service.AlarmService; import org.springframework.stereotype.Service;
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.smartloli.kafka.eagle.web.service.impl; /** * Alarm implements service to get configure info. * * @Author smartloli. * * Created by Sep 6, 2016. * * Update by hexiang 20170216 */ @Service public class AlarmServiceImpl implements AlarmService { /** Kafka service interface. */
private KafkaService kafkaService = new KafkaFactory().create();
2
cjdaly/fold
net.locosoft.fold.channel.fold/src/net/locosoft/fold/channel/fold/internal/FoldChannel.java
[ "public abstract class AbstractChannel implements IChannel, IChannelInternal {\n\n\t//\n\t// IChannel\n\t//\n\n\tprivate String _id;\n\n\tpublic String getChannelId() {\n\t\treturn _id;\n\t}\n\n\tprivate String _description;\n\n\tpublic String getChannelData(String key, String... params) {\n\t\tswitch (key) {\n\t\tcase \"channel.description\":\n\t\t\treturn _description;\n\t\tdefault:\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic IChannelItemDetails getChannelItemDetails(String itemLabel,\n\t\t\tlong itemOrdinal) {\n\t\treturn null;\n\t}\n\n\t//\n\t// IChannelInternal\n\t//\n\n\tprivate IChannelService _channelService;\n\n\tpublic IChannelService getChannelService() {\n\t\treturn _channelService;\n\t}\n\n\tpublic final void init(String channelId, IChannelService channelService,\n\t\t\tString channelDescription) {\n\t\t_id = channelId;\n\t\t_description = channelDescription;\n\t\t_channelService = channelService;\n\t}\n\n\tpublic void init() {\n\t}\n\n\tpublic void fini() {\n\t}\n\n\tpublic boolean channelSecurity(HttpServletRequest request,\n\t\t\tHttpServletResponse response) throws IOException {\n\t\treturn true;\n\t}\n\n\tpublic void channelHttp(HttpServletRequest request,\n\t\t\tHttpServletResponse response) throws ServletException, IOException {\n\n\t\tswitch (request.getMethod()) {\n\t\tcase \"GET\":\n\t\t\tchannelHttpGet(request, response);\n\t\t\tbreak;\n\t\tcase \"POST\":\n\t\t\tchannelHttpPost(request, response);\n\t\t\tbreak;\n\t\tcase \"PUT\":\n\t\t\tchannelHttpPut(request, response);\n\t\t\tbreak;\n\t\tcase \"DELETE\":\n\t\t\tchannelHttpDelete(request, response);\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tprotected void channelHttpGet(HttpServletRequest request,\n\t\t\tHttpServletResponse response) throws ServletException, IOException {\n\t\tchannelHttpNotImplemented(request, response);\n\t}\n\n\tprotected void channelHttpPost(HttpServletRequest request,\n\t\t\tHttpServletResponse response) throws ServletException, IOException {\n\t\tchannelHttpNotImplemented(request, response);\n\t}\n\n\tprotected void channelHttpPut(HttpServletRequest request,\n\t\t\tHttpServletResponse response) throws ServletException, IOException {\n\t\tchannelHttpNotImplemented(request, response);\n\t}\n\n\tprotected void channelHttpDelete(HttpServletRequest request,\n\t\t\tHttpServletResponse response) throws ServletException, IOException {\n\t\tchannelHttpNotImplemented(request, response);\n\t}\n\n\tprivate void channelHttpNotImplemented(HttpServletRequest request,\n\t\t\tHttpServletResponse response) throws ServletException, IOException {\n\t\tresponse.setContentType(\"text/html\");\n\n\t\tPrintWriter writer = response.getWriter();\n\n\t\tString channelId = getChannelId();\n\t\tString thingName = getChannelData(\"thing\", \"name\");\n\t\twriter.append(\"<html>\\n<head>\\n<title>\");\n\t\twriter.append(\"fold: \" + thingName + \" / \" + channelId);\n\t\twriter.append(\"</title>\\n</head>\\n<body>\\n\");\n\n\t\twriter.append(\"<p>\");\n\t\twriter.append(\"Method \" + request.getMethod() + \" not implemented!\");\n\t\twriter.append(\"</p>\\n\");\n\n\t\twriter.append(\"\\n</body>\\n</html>\\n\");\n\t}\n\n\tpublic final Properties getChannelConfigProperties(\n\t\t\tString propertiesFilePrefix) {\n\t\tString channelConfigFilePath = FoldUtil.getFoldConfigDir()\n\t\t\t\t+ \"/channel/\" + getChannelId() + \"/\" + propertiesFilePrefix\n\t\t\t\t+ \".properties\";\n\t\treturn FoldUtil.loadPropertiesFile(channelConfigFilePath);\n\t}\n\n\tpublic final IProject getChannelProject() {\n\t\ttry {\n\t\t\tIWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace()\n\t\t\t\t\t.getRoot();\n\t\t\tIProject project = workspaceRoot.getProject(getChannelId());\n\t\t\tboolean workspaceStateChange = false;\n\n\t\t\tif (!project.exists()) {\n\t\t\t\tworkspaceStateChange = true;\n\t\t\t\tproject.create(null);\n\t\t\t}\n\n\t\t\tif (!project.isOpen()) {\n\t\t\t\tworkspaceStateChange = true;\n\t\t\t\tproject.open(null);\n\t\t\t}\n\n\t\t\tif (workspaceStateChange) {\n\t\t\t\tworkspaceRoot.getWorkspace().save(true, null);\n\t\t\t}\n\n\t\t\treturn project;\n\t\t} catch (CoreException ex) {\n\t\t\tex.printStackTrace();\n\t\t}\n\t\treturn null;\n\t}\n\n\tprivate long _channelNodeId = -1;\n\n\tpublic final long getChannelNodeId() {\n\t\tif (_channelNodeId == -1) {\n\t\t\tINeo4jService neo4jService = Neo4jUtil.getNeo4jService();\n\n\t\t\tICypher cypher = neo4jService\n\t\t\t\t\t.constructCypher(\"MERGE (channel:fold_Channel {fold_channelId : {channelId}}) RETURN ID(channel)\");\n\t\t\tcypher.addParameter(\"channelId\", getChannelId());\n\t\t\tneo4jService.invokeCypher(cypher);\n\n\t\t\tJsonValue jsonValue = cypher.getResultDataRow(0);\n\t\t\t_channelNodeId = jsonValue.asLong();\n\t\t}\n\t\treturn _channelNodeId;\n\t}\n\n}", "public class ChannelUtil {\n\n\tpublic static IChannelService getChannelService() {\n\t\treturn FoldUtil.getService(IChannelService.class);\n\t}\n}", "public interface IChannel {\n\n\tString getChannelId();\n\n\tString getChannelData(String key, String... params);\n\n\tIChannelItemDetails getChannelItemDetails(String itemLabel, long itemOrdinal);\n\n\tClass<? extends IChannel> getChannelInterface();\n\n}", "public interface IFoldChannel extends IChannel {\n\n\tlong getStartCount();\n\n}", "public abstract class ChannelHeaderFooterHtml extends AbstractChannelHtmlSketch {\n\n\tpublic ChannelHeaderFooterHtml(IChannelInternal channel) {\n\t\tsuper(channel);\n\t}\n\n\tpublic void composeHtmlResponse(HttpServletRequest request,\n\t\t\tHttpServletResponse response) throws ServletException, IOException {\n\t\tresponse.setContentType(\"text/html\");\n\t\tString thingName = getChannel().getChannelService().getChannelData(\n\t\t\t\t\"thing\", \"name\");\n\n\t\tHtmlComposer html = new HtmlComposer(response.getWriter());\n\t\thtml.html_head(\"fold: \" + thingName + \" / \"\n\t\t\t\t+ getChannel().getChannelId());\n\n\t\tcomposeHtmlResponseBody(request, response, html);\n\n\t\thtml.html_body(false);\n\t}\n\n\tprotected abstract void composeHtmlResponseBody(HttpServletRequest request,\n\t\t\tHttpServletResponse response, HtmlComposer html)\n\t\t\tthrows ServletException, IOException;\n}", "public class CounterPropertyNode extends AbstractNodeSketch {\n\n\tpublic CounterPropertyNode(long nodeId) {\n\t\t_nodeId = nodeId;\n\t}\n\n\tprivate long crementCounter(String counterPropertyName, boolean isIncrement) {\n\t\tINeo4jService neo4jService = getNeo4jService();\n\n\t\tchar crementOp = isIncrement ? '+' : '-';\n\t\tString cypherText = \"MATCH node WHERE id(node)={nodeId}\"\n\t\t\t\t+ \" SET node.`\" + counterPropertyName + \"`=COALESCE(node.`\"\n\t\t\t\t+ counterPropertyName + \"`, 0) \" + crementOp + \" 1\"\n\t\t\t\t+ \" RETURN node.`\" + counterPropertyName + \"`\";\n\t\tICypher cypher = neo4jService.constructCypher(cypherText);\n\t\tcypher.addParameter(\"nodeId\", getNodeId());\n\n\t\tneo4jService.invokeCypher(cypher);\n\n\t\tJsonValue jsonValue = cypher.getResultDataRow(0);\n\t\treturn jsonValue.asLong();\n\t}\n\n\tpublic long incrementCounter(String counterPropertyName) {\n\t\treturn crementCounter(counterPropertyName, true);\n\t}\n\n\tpublic long decrementCounter(String counterPropertyName) {\n\t\treturn crementCounter(counterPropertyName, false);\n\t}\n\n\tpublic long getCounter(String counterPropertyName) {\n\t\tPropertyAccessNode sketch = new PropertyAccessNode(getNodeId());\n\t\tJsonValue jsonValue = sketch.getValue(counterPropertyName);\n\t\tif ((jsonValue == null) || !jsonValue.isNumber())\n\t\t\treturn 0;\n\t\telse\n\t\t\treturn jsonValue.asLong();\n\t}\n\n}", "public class HierarchyNode extends AbstractNodeSketch {\n\n\tpublic HierarchyNode(long nodeId) {\n\t\t_nodeId = nodeId;\n\t}\n\n\tpublic void setNodeId(long nodeId) {\n\t\t_nodeId = nodeId;\n\t}\n\n\tpublic long getSupId() {\n\t\tINeo4jService neo4jService = getNeo4jService();\n\t\tString cypherText = \"MATCH (sup)-[:fold_Hierarchy]->(sub)\"\n\t\t\t\t+ \" WHERE ID(sub)={subId}\" //\n\t\t\t\t+ \" RETURN ID(sup)\";\n\t\tICypher cypher = neo4jService.constructCypher(cypherText);\n\t\tcypher.addParameter(\"subId\", getNodeId());\n\t\tneo4jService.invokeCypher(cypher);\n\t\tJsonValue jsonValue = cypher.getResultDataRow(0);\n\t\tif (jsonValue != null)\n\t\t\treturn jsonValue.asLong();\n\t\telse\n\t\t\treturn -1;\n\t}\n\n\tpublic JsonObject getSubNode(String segment) {\n\t\tINeo4jService neo4jService = getNeo4jService();\n\t\tString cypherText = \"MATCH (sup)-[:fold_Hierarchy]->(sub)\"\n\t\t\t\t+ \" WHERE ID(sup)={supId} AND sub.fold_Hierarchy_segment={segment}\" //\n\t\t\t\t+ \" RETURN sub\";\n\t\tICypher cypher = neo4jService.constructCypher(cypherText);\n\t\tcypher.addParameter(\"supId\", getNodeId());\n\t\tcypher.addParameter(\"segment\", segment);\n\t\tneo4jService.invokeCypher(cypher);\n\t\tJsonValue jsonValue = cypher.getResultDataRow(0);\n\t\tif ((jsonValue == null) || (!jsonValue.isObject()))\n\t\t\treturn null;\n\t\telse\n\t\t\treturn jsonValue.asObject();\n\t}\n\n\tpublic long getSubId(String segment, boolean createIfAbsent) {\n\t\tINeo4jService neo4jService = getNeo4jService();\n\t\tString cypherText;\n\t\tif (createIfAbsent) {\n\t\t\tcypherText = \"MATCH sup\" //\n\t\t\t\t\t+ \" WHERE id(sup)={supId}\" //\n\t\t\t\t\t+ \" CREATE UNIQUE (sup)-[:fold_Hierarchy]->\"\n\t\t\t\t\t+ \"(sub{ fold_Hierarchy_segment:{segment} }) \"\n\t\t\t\t\t+ \" RETURN ID(sub)\";\n\t\t} else {\n\t\t\tcypherText = \"MATCH (sup)-[:fold_Hierarchy]->(sub)\"\n\t\t\t\t\t+ \" WHERE ID(sup)={supId} AND sub.fold_Hierarchy_segment={segment}\" //\n\t\t\t\t\t+ \" RETURN ID(sub)\";\n\t\t}\n\t\tICypher cypher = neo4jService.constructCypher(cypherText);\n\t\tcypher.addParameter(\"supId\", getNodeId());\n\t\tcypher.addParameter(\"segment\", segment);\n\t\tneo4jService.invokeCypher(cypher);\n\t\tJsonValue jsonValue = cypher.getResultDataRow(0);\n\t\tif (jsonValue != null)\n\t\t\treturn jsonValue.asLong();\n\t\telse\n\t\t\treturn -1;\n\t}\n\n\tpublic long[] getSubIds() {\n\t\tINeo4jService neo4jService = getNeo4jService();\n\t\tString cypherText = \"MATCH (sup)-[:fold_Hierarchy]->(sub)\"\n\t\t\t\t+ \" WHERE ID(sup)={supId}\" //\n\t\t\t\t+ \" RETURN ID(sub)\";\n\t\tICypher cypher = neo4jService.constructCypher(cypherText);\n\t\tcypher.addParameter(\"supId\", getNodeId());\n\t\tneo4jService.invokeCypher(cypher);\n\n\t\tlong[] subIds = new long[cypher.getResultDataRowCount()];\n\t\tfor (int i = 0; i < cypher.getResultDataRowCount(); i++) {\n\t\t\tJsonValue jsonValue = cypher.getResultDataRow(i);\n\t\t\tsubIds[i] = jsonValue.asLong();\n\t\t}\n\t\treturn subIds;\n\t}\n\n\tpublic String[] getSubSegments() {\n\t\tINeo4jService neo4jService = getNeo4jService();\n\t\tString cypherText = \"MATCH (sup)-[:fold_Hierarchy]->(sub)\"\n\t\t\t\t+ \" WHERE ID(sup)={supId}\"\n\t\t\t\t+ \" RETURN sub.fold_Hierarchy_segment\";\n\t\tICypher cypher = neo4jService.constructCypher(cypherText);\n\t\tcypher.addParameter(\"supId\", getNodeId());\n\t\tneo4jService.invokeCypher(cypher);\n\n\t\tString[] subSegments = new String[cypher.getResultDataRowCount()];\n\t\tfor (int i = 0; i < cypher.getResultDataRowCount(); i++) {\n\t\t\tJsonValue jsonValue = cypher.getResultDataRow(i);\n\t\t\tsubSegments[i] = jsonValue.asString();\n\t\t}\n\t\treturn subSegments;\n\t}\n\n\t// TODO:\n\t// public long[] getPathNodeIds(Path path) {\n\t//\n\t// }\n\t//\n\t// TODO:\n\t// public long getPathEndNodeId(Path path) {\n\t// return -1;\n\t// }\n\n}", "public class HtmlComposer {\n\n\tprivate StringBuilder _builder;\n\tprivate PrintWriter _writer;\n\n\tpublic HtmlComposer(PrintWriter writer) {\n\t\t_writer = writer;\n\t\t_builder = new StringBuilder();\n\t}\n\n\tpublic String A(String href, String linkText) {\n\t\t_builder.setLength(0);\n\t\t_builder.append(\"<a href='\");\n\t\t_builder.append(href);\n\t\t_builder.append(\"'>\");\n\t\t_builder.append(linkText);\n\t\t_builder.append(\"</a>\");\n\t\treturn _builder.toString();\n\t}\n\n\tpublic void a(String href, String linkText) {\n\t\t_writer.print(\"<a href='\");\n\t\t_writer.print(href);\n\t\t_writer.print(\"'>\");\n\t\t_writer.print(linkText);\n\t\t_writer.println(\"</a>\");\n\t}\n\n\tpublic void b(String text) {\n\t\tsimpleTag(\"b\", text);\n\t}\n\n\tpublic void br() {\n\t\t_writer.println(\"<br>\");\n\t}\n\n\tpublic void button(String type, String text) {\n\t\t_writer.print(\"<button type='\");\n\t\t_writer.print(type);\n\t\t_writer.print(\"'>\");\n\t\t_writer.print(text);\n\t\t_writer.print(\"</button>\");\n\t}\n\n\tpublic void code(String text) {\n\t\tsimpleTag(\"code\", text);\n\t}\n\n\tpublic void dd(String text) {\n\t\tsimpleTag(\"dd\", text);\n\t}\n\n\tpublic void div() {\n\t\tdiv(true);\n\t}\n\n\tpublic void div(boolean startTag) {\n\t\tsimpleTag(\"div\", startTag);\n\t}\n\n\tpublic void dl() {\n\t\tdl(true);\n\t}\n\n\tpublic void dl(boolean startTag) {\n\t\tsimpleTag(\"dl\", startTag);\n\t}\n\n\tpublic void dt(String text) {\n\t\tsimpleTag(\"dt\", text);\n\t}\n\n\tpublic void em(String text) {\n\t\tsimpleTag(\"em\", text);\n\t}\n\n\tpublic void form() {\n\t\tform(false);\n\t}\n\n\tpublic void form(boolean startTag) {\n\t\tsimpleTag(\"form\", startTag);\n\t}\n\n\tpublic void h(int level, String text) {\n\t\tif (level < 1)\n\t\t\tlevel = 1;\n\t\telse if (level > 6)\n\t\t\tlevel = 6;\n\t\t_writer.print(\"<h\");\n\t\t_writer.print(level);\n\t\t_writer.print(\">\");\n\t\t_writer.print(text);\n\t\t_writer.print(\"</h\");\n\t\t_writer.print(level);\n\t\t_writer.println(\">\");\n\t}\n\n\tpublic void html_head(String title) {\n\t\t_writer.println(\"<html>\");\n\t\t_writer.println(\"<head>\");\n\t\t_writer.print(\"<title>\");\n\t\t_writer.print(title);\n\t\t_writer.println(\"</title>\");\n\t\t_writer.println(\"</head>\");\n\t\t_writer.println(\"<body>\");\n\t}\n\n\tpublic void html_body(boolean startTag) {\n\t\tif (!startTag) {\n\t\t\t_writer.println(\"</body>\");\n\t\t\t_writer.println(\"</html>\");\n\t\t}\n\t}\n\n\tpublic void i(String text) {\n\t\tsimpleTag(\"i\", text);\n\t}\n\n\tpublic void img(String src, String alt) {\n\t\t_writer.print(\"<img src='\");\n\t\t_writer.print(src);\n\t\t_writer.print(\"' alt='\");\n\t\t_writer.print(alt);\n\t\t_writer.print(\"'>\");\n\t}\n\n\tpublic void input(String type, String name) {\n\t\t_writer.print(\"<input type='\");\n\t\t_writer.print(type);\n\t\t_writer.print(\"' name='\");\n\t\t_writer.print(name);\n\t\t_writer.println(\"'>\");\n\t}\n\n\tpublic void li(String text) {\n\t\tsimpleTag(\"li\", text);\n\t}\n\n\tpublic void object(String data, String type) {\n\t\t_writer.print(\"<object data='\");\n\t\t_writer.print(data);\n\t\t_writer.print(\"' type='\");\n\t\t_writer.print(type);\n\t\t_writer.print(\"'></object>\");\n\t}\n\n\tpublic void ol() {\n\t\tol(true);\n\t}\n\n\tpublic void ol(boolean startTag) {\n\t\tsimpleTag(\"ol\", startTag);\n\t}\n\n\tpublic void p() {\n\t\tp(true);\n\t}\n\n\tpublic void p(boolean startTag) {\n\t\tsimpleTag(\"p\", startTag);\n\t}\n\n\tpublic void p(String text) {\n\t\tsimpleTag(\"p\", text);\n\t}\n\n\tpublic void pre(String text) {\n\t\tsimpleTag(\"pre\", text);\n\t}\n\n\tpublic void span(String text) {\n\t\tsimpleTag(\"span\", text);\n\t}\n\n\tpublic void strong(String text) {\n\t\tsimpleTag(\"strong\", text);\n\t}\n\n\tpublic void table() {\n\t\ttable(true);\n\t}\n\n\tpublic void table(boolean startTag) {\n\t\tsimpleTag(\"table\", startTag);\n\t}\n\n\tpublic void text(String text) {\n\t\t_writer.print(text);\n\t}\n\n\tpublic void td(String text) {\n\t\tsimpleTag(\"td\", text);\n\t}\n\n\tpublic void th(String text) {\n\t\tsimpleTag(\"th\", text);\n\t}\n\n\tpublic void tr(boolean startTag) {\n\t\tsimpleTag(\"tr\", startTag);\n\t}\n\n\tpublic void tr(String... tableCells) {\n\t\ttr(false, tableCells);\n\t}\n\n\tpublic void tr(boolean isHeader, String... tableCells) {\n\t\t_writer.print(\"<tr>\");\n\t\tfor (String tableCell : tableCells) {\n\t\t\tif (isHeader)\n\t\t\t\t_writer.print(\"<th>\");\n\t\t\telse\n\t\t\t\t_writer.print(\"<td>\");\n\t\t\t_writer.print(tableCell);\n\t\t\tif (isHeader)\n\t\t\t\t_writer.print(\"</th>\");\n\t\t\telse\n\t\t\t\t_writer.print(\"</td>\");\n\t\t}\n\t\t_writer.println(\"</tr>\");\n\t}\n\n\tpublic void ul() {\n\t\tul(true);\n\t}\n\n\tpublic void ul(boolean startTag) {\n\t\tsimpleTag(\"ul\", startTag);\n\t}\n\n\t//\n\t//\n\n\tprivate void simpleTag(String tag, String text) {\n\t\t_writer.print(\"<\");\n\t\t_writer.print(tag);\n\t\t_writer.print(\">\");\n\t\t_writer.print(text);\n\t\t_writer.print(\"</\");\n\t\t_writer.print(tag);\n\t\t_writer.println(\">\");\n\t}\n\n\tprivate void simpleTag(String tag, boolean startTag) {\n\t\tif (startTag) {\n\t\t\t_writer.print(\"<\");\n\t\t\t_writer.print(tag);\n\t\t\t_writer.println(\">\");\n\t\t} else {\n\t\t\t_writer.print(\"</\");\n\t\t\t_writer.print(tag);\n\t\t\t_writer.println(\">\");\n\t\t}\n\t}\n\n}" ]
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.locosoft.fold.channel.AbstractChannel; import net.locosoft.fold.channel.ChannelUtil; import net.locosoft.fold.channel.IChannel; import net.locosoft.fold.channel.fold.IFoldChannel; import net.locosoft.fold.sketch.pad.html.ChannelHeaderFooterHtml; import net.locosoft.fold.sketch.pad.neo4j.CounterPropertyNode; import net.locosoft.fold.sketch.pad.neo4j.HierarchyNode; import net.locosoft.fold.util.HtmlComposer; import org.eclipse.core.runtime.Path; import com.eclipsesource.json.JsonObject;
/***************************************************************************** * Copyright (c) 2015 Chris J Daly (github user cjdaly) * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * cjdaly - initial API and implementation ****************************************************************************/ package net.locosoft.fold.channel.fold.internal; public class FoldChannel extends AbstractChannel implements IFoldChannel { private FoldFinder _foldFinder = new FoldFinder(this); private long _startCount = -1; public long getStartCount() { return _startCount; } public Class<? extends IChannel> getChannelInterface() { return IFoldChannel.class; } public void init() { CounterPropertyNode foldStartCount = new CounterPropertyNode( getChannelNodeId()); _startCount = foldStartCount.incrementCounter("fold_startCount"); _foldFinder.start(); } public void fini() { _foldFinder.stop(); } public void channelHttpGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pathInfo = request.getPathInfo(); if ((pathInfo == null) || ("".equals(pathInfo)) || ("/".equals(pathInfo))) { // empty channel segment (/fold) new ChannelHttpGetDashboard() .composeHtmlResponse(request, response); } else { Path path = new Path(pathInfo); String channelSegment = path.segment(0); if ("fold".equals(channelSegment)) { // fold channel segment (/fold/fold) new ChannelHttpGetFold().composeHtmlResponse(request, response); } else { // everything else new ChannelHttpGetUndefined().composeHtmlResponse(request, response); } } } private class ChannelHttpGetDashboard extends ChannelHeaderFooterHtml { ChannelHttpGetDashboard() { super(FoldChannel.this); } protected void composeHtmlResponseBody(HttpServletRequest request, HttpServletResponse response, HtmlComposer html) throws ServletException, IOException { html.h(2, "fold"); html.p(); html.text("Thing: "); String thingName = getChannelService().getChannelData("thing", "name"); html.b(thingName); html.br(); html.text("start count: "); html.b(Long.toString(getStartCount())); html.p(false); html.h(3, "channels"); html.table(); IChannel[] channels = ChannelUtil.getChannelService() .getAllChannels(); for (IChannel channel : channels) { String channelLink = html.A("/fold/" + channel.getChannelId(), channel.getChannelId()); html.tr(channelLink, channel.getChannelData("channel.description")); } html.table(false); } } private class ChannelHttpGetFold extends ChannelHeaderFooterHtml { public ChannelHttpGetFold() { super(FoldChannel.this); } protected void composeHtmlResponseBody(HttpServletRequest request, HttpServletResponse response, HtmlComposer html) throws ServletException, IOException { html.h(2, "fold finder");
HierarchyNode foldChannelNode = new HierarchyNode(
6
khasang/SmartForecast
Forecast/app/src/main/java/com/khasang/forecast/stations/OpenWeatherMap.java
[ "public class MyApplication extends Application {\n\n private static Context context;\n\n public static Context getAppContext() {\n return MyApplication.context;\n }\n\n @Override\n public void onCreate() {\n super.onCreate();\n\n /** Проверяет, если Debug mode, то не отправляет отчеты об ошибках */\n CrashlyticsCore core = new CrashlyticsCore.Builder().disabled(BuildConfig.DEBUG).build();\n Fabric.with(this, new Crashlytics.Builder().core(core).build());\n\n DrawUtils.getInstance().init(this);\n MyApplication.context = getApplicationContext();\n Stetho.initializeWithDefaults(this);\n\n //FirebaseCrash.report(new Exception(\"My first Android non-fatal error\"));\n\n SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);\n String languageCode = sharedPreferences.getString(getString(R.string.pref_language_key), null);\n LocaleUtils.updateResources(this, languageCode);\n }\n}", "public class DailyResponse {\n\n private City city;\n private String cod;\n private Double message;\n private Integer cnt;\n private List<DailyForecastList> list = new ArrayList<>();\n\n public City getCity() {\n return city;\n }\n\n public String getCod() {\n return cod;\n }\n\n public Double getMessage() {\n return message;\n }\n\n public Integer getCnt() {\n return cnt;\n }\n\n public List<DailyForecastList> getList() {\n return list;\n }\n\n @Override\n public String toString() {\n return \"DailyResponse{\" +\n \"city=\" + city +\n \", cod='\" + cod + '\\'' +\n \", message=\" + message +\n \", cnt=\" + cnt +\n \", list=\" + list +\n '}';\n }\n}", "public class OpenWeatherMapResponse {\n private ArrayList<Weather> weather = new ArrayList<>();\n private Main main;\n private Wind wind;\n private Clouds clouds;\n private Rain rain;\n private long dt;\n private Sys sys;\n private long id;\n private String name;\n private List<HourlyForecastList> list = new ArrayList<>();\n\n public ArrayList<Weather> getWeather() {\n return weather;\n }\n\n public Main getMain() {\n return main;\n }\n\n public Wind getWind() {\n return wind;\n }\n\n public Clouds getClouds() {\n return clouds;\n }\n\n public Rain getRain() {\n return rain;\n }\n\n public long getDt() {\n return dt;\n }\n\n public Sys getSys() {\n return sys;\n }\n\n public long getId() {\n return id;\n }\n\n public String getName() {\n return name;\n }\n\n public List<HourlyForecastList> getList() {\n return list;\n }\n\n @Override\n public String toString() {\n return \"OpenWeatherMapResponse{\" +\n \"weather=\" + weather +\n \", main=\" + main +\n \", wind=\" + wind +\n \", clouds=\" + clouds +\n \", rain=\" + rain +\n \", dt=\" + dt +\n \", sys=\" + sys +\n \", id=\" + id +\n \", name='\" + name + '\\'' +\n \", list=\" + list +\n '}';\n }\n}", "public class Coordinate implements Comparable<Coordinate> {\n private double latitude;\n private double longitude;\n\n public Coordinate(double latitude, double longitude) {\n this.latitude = latitude;\n this.longitude = longitude;\n }\n\n public Coordinate() {\n\n }\n\n public double getLatitude() {\n return latitude;\n }\n\n public void setLatitude(double latitude) {\n this.latitude = latitude;\n }\n\n public double getLongitude() {\n return longitude;\n }\n\n public void setLongitude(double longitude) {\n this.longitude = longitude;\n }\n\n @Override\n public int compareTo(Coordinate another) {\n if (another == null) {\n return 1;\n }\n if (latitude == another.getLatitude() && longitude == another.getLongitude()) {\n return 0;\n }\n return 1;\n }\n\n @Override\n public String toString() {\n return \"Coordinate{latitude=\" + latitude + \", longitude=\" + longitude + \"}\";\n }\n\n public String convertToTimezoneUrlParameterString() {\n return String.valueOf(latitude) + \",\" + String.valueOf(longitude);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n Coordinate that = (Coordinate) o;\n\n if (Double.compare(that.latitude, latitude) != 0) return false;\n return Double.compare(that.longitude, longitude) == 0;\n\n }\n\n @Override\n public int hashCode() {\n int result;\n long temp;\n temp = Double.doubleToLongBits(latitude);\n result = (int) (temp ^ (temp >>> 32));\n temp = Double.doubleToLongBits(longitude);\n result = 31 * result + (int) (temp ^ (temp >>> 32));\n return result;\n }\n}", "public class PositionManager implements ICoordinateReceiver, ILocationNameReceiver {\n\n AppUtils.TemperatureMetrics temperatureMetric;\n AppUtils.SpeedMetrics speedMetric;\n AppUtils.PressureMetrics pressureMetric;\n private WeatherStation currStation;\n private volatile Position activePosition; // Здесь лежит \"активная\" позиция (которая на данный момент активна на экране)\n private HashMap<WeatherStationFactory.ServiceType, WeatherStation> stations;\n private volatile Position currentPosition; // Здесь лежит текущая по местоположению локация (там где находится пользователь)\n private volatile HashMap<String, Position> positions;\n List<String> favouritesPositions;\n private volatile IWeatherReceiver receiver;\n private volatile IMessageProvider messageProvider;\n private SQLiteProcessData dbManager;\n private boolean lastResponseIsFailure;\n private CurrentLocationManager locationManager;\n\n private Drawable[] iconsSet;\n IconicsDrawable iconNa = null;\n private boolean isSvgIconsUsed = false;\n private int currentWeatherIconColor;\n private int forecastWeatherIconColor;\n\n public synchronized void setReceiver(IWeatherReceiver receiver) {\n this.receiver = receiver;\n }\n\n public synchronized void setMessageProvider(IMessageProvider provider) {\n this.messageProvider = provider;\n }\n\n private static volatile PositionManager instance;\n\n private PositionManager() {\n lastResponseIsFailure = false;\n iconNa = new IconicsDrawable(MyApplication.getAppContext())\n .icon(WeatherIcons.Icon.wic_na)\n .sizeDp(80)\n .paddingDp(4);\n }\n\n public static PositionManager getInstance() {\n if (instance == null) {\n synchronized (PositionManager.class) {\n if (instance == null) {\n instance = new PositionManager();\n instance.setReceiver(null);\n instance.initManager();\n }\n }\n }\n return instance;\n }\n\n public static PositionManager getInstance(IMessageProvider provider, IWeatherReceiver receiver) {\n if (instance == null) {\n synchronized (PositionManager.class) {\n if (instance == null) {\n instance = new PositionManager();\n instance.setMessageProvider(provider);\n instance.setReceiver(receiver);\n instance.initManager();\n }\n }\n }\n return instance;\n }\n\n public synchronized void removeInstance() {\n instance = null;\n }\n\n public void initManager() {\n dbManager = new SQLiteProcessData();\n temperatureMetric = dbManager.loadTemperatureMetrics();\n speedMetric = dbManager.loadSpeedMetrics();\n pressureMetric = dbManager.loadPressureMetrics();\n initCurrentLocation();\n initPositions();\n initLocationManager();\n initStations();\n updateFavoritesList();\n }\n\n public void updateFavoritesList() {\n favouritesPositions = dbManager.loadFavoriteTownList();\n Collections.sort(favouritesPositions);\n }\n\n public List<String> getFavouritesList() {\n return favouritesPositions;\n }\n\n public boolean flipFavCity(String cityName) {\n boolean state;\n if (isFavouriteCity(cityName)) {\n state = false;\n favouritesPositions.remove(cityName);\n } else {\n state = true;\n favouritesPositions.add(cityName);\n Collections.sort(favouritesPositions);\n }\n dbManager.saveTownFavourite(state, cityName);\n return state;\n }\n\n public void removeFavoriteCity(String city) {\n if (favouritesPositions != null) {\n favouritesPositions.remove(city);\n }\n }\n\n public boolean isFavouriteCity(String cityName) {\n try {\n return favouritesPositions.contains(cityName);\n } catch (NullPointerException | ClassCastException e) {\n e.printStackTrace();\n return false;\n }\n }\n\n public void clearFavorites() {\n if (favouritesPositions != null) {\n favouritesPositions.clear();\n }\n }\n\n // Пока заглушка, потом настрки сохранять при их смене в настройках\n public void saveSettings() {\n saveCurrStation();\n saveMetrics();\n saveCurrPosition();\n }\n\n public void saveMetrics() {\n dbManager.saveSettings(temperatureMetric, speedMetric, pressureMetric);\n }\n\n public void saveCurrPosition() {\n try {\n dbManager.saveLastCurrentLocationName(currentPosition.getLocationName());\n dbManager.saveLastPositionCoordinates(currentPosition.getCoordinate());\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n public void saveCurrStation() {\n dbManager.saveSettings(currStation);\n }\n\n /**\n * Метод инициализации списка сервисов для получения информации о погодных условиях.\n */\n private void initStations() {\n WeatherStationFactory wsf = new WeatherStationFactory();\n stations = wsf\n .addOpenWeatherMap()\n .create();\n currStation = stations.get(dbManager.loadStation());\n }\n\n private void initCurrentLocation() {\n currentPosition = new Position();\n currentPosition.setLocationName(\"Smart Forecast\");\n currentPosition.setCityID(0);\n currentPosition.setCoordinate(null);\n }\n\n /**\n * Метод инициализации списка местоположений, вызывается из активити\n */\n private void initPositions() {\n ArrayList<Position> pos = dbManager.loadTownListFull();\n initPositions(pos);\n }\n\n /**\n * Метод инициализации списка местоположений, которые добавлены в список городов\n */\n private void initPositions(ArrayList<Position> pos) {\n PositionFactory positionFactory = new PositionFactory();\n\n if (pos.size() != 0) {\n for (Position entry : pos) {\n positionFactory.addFavouritePosition(entry);\n }\n }\n positions = positionFactory.getPositions();\n for (Position p : positions.values()) {\n if ((p.getCoordinate() == null) || (p.getCoordinate().getLatitude() == 0 && p.getCoordinate().getLongitude() == 0)) {\n GoogleMapsGeocoding googleMapsGeocoding = new GoogleMapsGeocoding();\n googleMapsGeocoding.requestCoordinates(p.getLocationName(), this, false);\n }\n if (!p.timeZoneIsDefined()) {\n GoogleMapsTimezone googleMapsTimezone = new GoogleMapsTimezone();\n googleMapsTimezone.requestCoordinates(p);\n }\n }\n SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MyApplication.getAppContext());\n boolean saveCurrentLocation = sp.getString(MyApplication.getAppContext().getString(R.string.pref_location_key), MyApplication.getAppContext().getString(R.string.pref_location_current)).equals(MyApplication.getAppContext().getString(R.string.pref_location_current));\n String lastActivePositionName = sp.getString(MyApplication.getAppContext().getString(R.string.last_active_position_name), \"\");\n currentPosition.setLocationName(dbManager.loadСurrentTown());\n currentPosition.setCoordinate(dbManager.loadLastPositionCoordinates());\n if (saveCurrentLocation) {\n activePosition = currentPosition;\n boolean isLocationPermissionGranted = Build.VERSION.SDK_INT < Build.VERSION_CODES.M ||\n ContextCompat.checkSelfPermission(MyApplication.getAppContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;\n if (!isLocationPermissionGranted) {\n if (!lastActivePositionName.isEmpty() && positionInListPresent(lastActivePositionName)) {\n activePosition = getPosition(lastActivePositionName);\n }\n }\n } else {\n if (!lastActivePositionName.isEmpty() && positionInListPresent(lastActivePositionName)) {\n activePosition = getPosition(lastActivePositionName);\n } else {\n activePosition = currentPosition;\n }\n }\n }\n\n /**\n * Метод, с помощью которого добавляем новую локацию в список \"Избранных\"\n * Вызывается когда пользователь добавляет новый город в список.\n *\n * @param name объект типа {@link String}, содержащий название города\n * @param coordinates геграфические координаты местоположения\n */\n public void addPosition(String name, Coordinate coordinates) {\n if (positionInListPresent(name)) {\n sendMessage(R.string.city_exist, Snackbar.LENGTH_LONG);\n return;\n }\n PositionFactory positionFactory = new PositionFactory(positions);\n positionFactory.addFavouritePosition(name, coordinates, dbManager);\n positions = positionFactory.getPositions();\n }\n\n /**\n * Метод, с помощью которого получаем список местоположений\n * Вызывается когда пользователь открывает диалог городов\n *\n * @return возвращает коллекцию {@link Set} типа {@link String}, содержащий названия городов\n */\n public Set<String> getPositions() {\n return positions.keySet();\n }\n\n public Position getActivePosition() {\n return activePosition;\n }\n\n /**\n * Метод, с помощью которого удаляем локацию в списка \"Избранных\"\n * Вызывается, когда пользователь удяляет город из списка\n *\n * @param name объект типа {@link String}, содержащий название города\n */\n public void removePosition(String name) {\n if (positions.containsKey(name)) {\n positions.remove(name);\n dbManager.deleteTown(name);\n }\n if (isFavouriteCity(name)) {\n removeFavoriteCity(name);\n }\n }\n\n public void removePositions() {\n positions.clear();\n clearFavorites();\n dbManager.deleteTowns();\n }\n\n /**\n * Метод, с помощью которого получаем название рекущей локации\n *\n * @return возвращает {@link String}, содержащий названия города\n */\n public String getActivePositionCity() {\n if (activePosition == null) {\n return \"\";\n }\n return activePosition.getLocationName();\n }\n\n /**\n * Метод, с помощью которого из списка городов выбираем другую локацию в качестве текущей\n *\n * @param city объект типа {@link String}, содержащий название города\n */\n public void setActivePosition(String city) {\n if (city.isEmpty()) {\n activePosition = currentPosition;\n } else if (positions.containsKey(city)) {\n activePosition = positions.get(city);\n } else {\n if (activePosition.getCoordinate() == null || activePosition.getCoordinate().equals(new Coordinate(0, 0))) {\n sendMessage(R.string.error_get_coordinates, Snackbar.LENGTH_LONG);\n }\n }\n }\n\n public boolean positionInListPresent(String name) {\n try {\n return positions.containsKey(name);\n } catch (ClassCastException | NullPointerException e) {\n e.printStackTrace();\n return false;\n }\n }\n\n public boolean positionIsPresent(String name) {\n if (currentPosition.getLocationName().equals(name)) {\n return true;\n } else {\n try {\n return positions.containsKey(name);\n } catch (ClassCastException | NullPointerException e) {\n e.printStackTrace();\n return false;\n }\n }\n }\n\n /**\n * Пролучение локации из списка локаций\n *\n * @param name объект типа {@link String}, хранящий название населенного пункта\n * @return обьект типа {@link Position}\n */\n\n public Position getPosition(String name) {\n return positions.get(name);\n }\n\n /**\n * Пролучение локации из списка локаций\n *\n * @param coordinate объект типа {@link Coordinate}, указывающий на местоположение локации\n * @return обьект типа {@link Position}\n */\n private Position getPosition(Coordinate coordinate) {\n for (Position pos : positions.values()) {\n if (pos.getCoordinate().compareTo(coordinate) == 0) {\n return pos;\n }\n }\n return null;\n }\n\n /**\n * Пролучение локации из списка локаций по внутреннему идентификатору локации\n *\n * @param cityID идентификатор местоположения\n * @return обьект типа {@link Position}\n */\n public Position getPosition(int cityID) {\n if (cityID == 0) {\n return currentPosition;\n }\n for (Position pos : positions.values()) {\n if (pos.getCityID() == cityID) {\n return pos;\n }\n }\n return null;\n }\n\n public AppUtils.SpeedMetrics getSpeedMetric() {\n return speedMetric;\n }\n\n public void setSpeedMetric(AppUtils.SpeedMetrics sm) {\n speedMetric = sm;\n }\n\n public AppUtils.PressureMetrics getPressureMetric() {\n return pressureMetric;\n }\n\n public void setPressureMetric(AppUtils.PressureMetrics pm) {\n pressureMetric = pm;\n }\n\n public AppUtils.PressureMetrics changePressureMetric() {\n pressureMetric = pressureMetric.change();\n return pressureMetric;\n }\n\n public AppUtils.TemperatureMetrics getTemperatureMetric() {\n return temperatureMetric;\n }\n\n public void setTemperatureMetric(AppUtils.TemperatureMetrics tm) {\n temperatureMetric = tm;\n }\n\n public AppUtils.TemperatureMetrics changeTemperatureMetric() {\n temperatureMetric = temperatureMetric.change();\n return temperatureMetric;\n }\n\n /**\n * Метод, вызывемый активити, для обновления текущей погоды от текущей погодной станции\n */\n public void updateWeather() {\n lastResponseIsFailure = false;\n if (activePosition == null || !positionIsPresent(activePosition.getLocationName())) {\n sendMessage(R.string.update_error_location_not_found, Snackbar.LENGTH_LONG);\n return;\n }\n if (activePosition == currentPosition) {\n updateCurrentLocationCoordinates();\n if (currentPosition.getCoordinate() == null) {\n updateWeatherFromDB();\n return;\n }\n }\n sendRequest();\n }\n\n /**\n * Метод, отправляет запрос на обновление погоды\n */\n public void sendRequest() {\n if (activePosition.getCoordinate() == null) {\n if (!activePosition.getLocationName().isEmpty()) {\n updateWeatherFromDB();\n }\n sendMessage(R.string.coordinates_error, Snackbar.LENGTH_LONG);\n } else if (!AppUtils.isNetworkAvailable(MyApplication.getAppContext())) {\n if (!activePosition.getLocationName().isEmpty()) {\n updateWeatherFromDB();\n }\n sendMessage(R.string.update_error_net_not_available, Snackbar.LENGTH_LONG);\n } else {\n LinkedList<WeatherStation.ResponseType> requestQueue = new LinkedList<>();\n requestQueue.add(WeatherStation.ResponseType.CURRENT);\n try {\n if (receiver.receiveHourlyWeatherFirst()) {\n requestQueue.addLast(WeatherStation.ResponseType.HOURLY);\n requestQueue.addLast(WeatherStation.ResponseType.DAILY);\n } else {\n requestQueue.addLast(WeatherStation.ResponseType.DAILY);\n requestQueue.addLast(WeatherStation.ResponseType.HOURLY);\n }\n currStation.updateWeather(requestQueue, activePosition.getCityID(), activePosition.getCoordinate());\n } catch (NullPointerException e) {\n // Отсроченный запрос активити уже уничтожено\n e.printStackTrace();\n updateWeatherFromDB();\n }\n }\n }\n\n public void updateWeatherFromDB(WeatherStation.ResponseType responseType, String positionName) {\n try {\n switch (responseType) {\n case CURRENT:\n receiver.updateInterface(responseType, getCurrentWeatherFromDB(currStation.getServiceType(), positionName));\n break;\n case HOURLY:\n receiver.updateInterface(responseType, getHourlyWeatherFromDB(currStation.getServiceType(), positionName));\n break;\n case DAILY:\n receiver.updateInterface(responseType, getDailyWeatherFromDB(currStation.getServiceType(), positionName));\n break;\n }\n } catch (NullPointerException e) {\n // Отсроченный запрос активити уже уничтожено\n e.printStackTrace();\n }\n }\n\n public void updateWeatherFromDB(WeatherStation.ResponseType responseType, Position position) {\n try {\n updateWeatherFromDB(responseType, position.getLocationName());\n } catch (NullPointerException e) {\n e.printStackTrace();\n }\n }\n\n public void updateWeatherFromDB() {\n try {\n updateWeatherFromDB(activePosition.getLocationName());\n } catch (NullPointerException e) {\n e.printStackTrace();\n }\n }\n\n public void updateWeatherFromDB(String locationName) {\n updateWeatherFromDB(WeatherStation.ResponseType.CURRENT, locationName);\n updateWeatherFromDB(WeatherStation.ResponseType.HOURLY, locationName);\n updateWeatherFromDB(WeatherStation.ResponseType.DAILY, locationName);\n }\n\n /**\n * Метод для обновления погодных данных. Вызывается погодным сервисом, когда приходят актуальные данные\n *\n * @param requestList коллекция типа {@link LinkedList}, содержащая элементы {@link com.khasang.forecast.stations.WeatherStation.ResponseType}, хранит очередность запросов (текущий прогноз, прогноз на день или неделю)\n * @param cityId внутренний идентификатор города, передается в погодную станцию во время запроса погоды\n * @param serviceType идентификатор погодного сервиса\n * @param weather обьект типа {@link Weather}, содержащий погодные характеристики\n */\n public void onResponseReceived(LinkedList<WeatherStation.ResponseType> requestList, int cityId, WeatherStationFactory.ServiceType serviceType, Map<Calendar, Weather> weather) {\n lastResponseIsFailure = false;\n WeatherStation.ResponseType rType = requestList.pollFirst();\n if (rType == null) {\n return;\n }\n Position position = getPosition(cityId);\n if (activePosition.getCityID() == cityId && currStation.getServiceType() == serviceType && position != null) {\n for (Map.Entry<Calendar, Weather> entry : weather.entrySet()) {\n if (rType == WeatherStation.ResponseType.CURRENT) {\n dbManager.deleteOldWeatherAllTowns(serviceType, entry.getKey());\n // Для CURRENT погоды сохраняем дополнительно погоду с текущим локальным временем,\n // иначе возможно расхождение с погодой из БД, например при смене метрик\n // (ближайшая в БД может отличаться от \"текущей\" погоды со станции)\n dbManager.saveWeather(serviceType, position.getLocationName(), Calendar.getInstance(), entry.getValue());\n }\n dbManager.saveWeather(serviceType, position.getLocationName(), entry.getKey(), entry.getValue());\n }\n\n for (Map.Entry<Calendar, Weather> entry : weather.entrySet()) {\n entry.setValue(AppUtils.formatWeather(entry.getValue(), temperatureMetric, speedMetric, pressureMetric));\n }\n try {\n receiver.updateInterface(rType, weather);\n } catch (NullPointerException e) {\n // Ответ пришел, когда активити уже уничтожено\n e.printStackTrace();\n }\n\n rType = requestList.peekFirst();\n if (rType == WeatherStation.ResponseType.HOURLY) {\n currStation.updateHourlyWeather(requestList, cityId, position.getCoordinate());\n } else if (rType == WeatherStation.ResponseType.DAILY) {\n currStation.updateWeeklyWeather(requestList, cityId, position.getCoordinate());\n }\n }\n }\n\n public void onFailureResponse(LinkedList<WeatherStation.ResponseType> requestList, int cityID, WeatherStationFactory.ServiceType sType) {\n/* if (!lastResponseIsFailure) {\n try {\n messageProvider.showToast(MyApplication.getAppContext().getString(R.string.update_error_from) + sType.toString());\n } catch (NullPointerException e) {\n e.printStackTrace();\n }\n lastResponseIsFailure = true;\n }*/\n WeatherStation.ResponseType rType = requestList.pollFirst();\n if (rType == null) {\n return;\n }\n Position position = getPosition(cityID);\n if (activePosition.getCityID() == cityID && currStation.getServiceType() == sType && position != null) {\n updateWeatherFromDB(rType, position);\n rType = requestList.peekFirst();\n if (rType == WeatherStation.ResponseType.HOURLY) {\n currStation.updateHourlyWeather(requestList, cityID, position.getCoordinate());\n } else if (rType == WeatherStation.ResponseType.DAILY) {\n currStation.updateWeeklyWeather(requestList, cityID, position.getCoordinate());\n }\n }\n }\n\n private HashMap<Calendar, Weather> getCurrentWeatherFromDB(WeatherStationFactory.ServiceType sType, String locationName) {\n return dbManager.loadWeather(sType, locationName, Calendar.getInstance(), temperatureMetric, speedMetric, pressureMetric);\n }\n\n private HashMap<Calendar, Weather> getHourlyWeatherFromDB(WeatherStationFactory.ServiceType sType, String locationName) {\n final int HOUR_PERIOD = 3;\n final int FORECASTS_COUNT = 8;\n Calendar calendar = Calendar.getInstance();\n calendar.add(Calendar.HOUR_OF_DAY, HOUR_PERIOD);\n calendar.set(Calendar.MINUTE, 0);\n HashMap<Calendar, Weather> forecast = new HashMap<>();\n for (int i = 0; i < FORECASTS_COUNT; i++) {\n HashMap<Calendar, Weather> temp = dbManager.loadWeather(sType, locationName, calendar, temperatureMetric, speedMetric, pressureMetric);\n if (temp == null || temp.size() == 0) {\n return null;\n }\n forecast.putAll(temp);\n calendar.add(Calendar.HOUR_OF_DAY, HOUR_PERIOD);\n }\n return forecast;\n }\n\n\n private HashMap<Calendar, Weather> getDailyWeatherFromDB(WeatherStationFactory.ServiceType sType, String locationName) {\n final int DAY_PERIOD = 1;\n final int FORECASTS_COUNT = 7;\n Calendar calendar = Calendar.getInstance();\n calendar.set(Calendar.HOUR_OF_DAY, 12);\n calendar.set(Calendar.MINUTE, 0);\n HashMap<Calendar, Weather> forecast = new HashMap<>();\n for (int i = 0; i < FORECASTS_COUNT; i++) {\n HashMap<Calendar, Weather> temp = dbManager.loadWeather(sType, locationName, calendar, temperatureMetric, speedMetric, pressureMetric);\n if (temp == null || temp.size() == 0) {\n return null;\n }\n forecast.putAll(temp);\n calendar.add(Calendar.DAY_OF_YEAR, DAY_PERIOD);\n }\n return forecast;\n }\n\n @Override\n public void updatePositionCoordinate(String city, Coordinate coordinate) {\n Position position = getPosition(city);\n if (position == null) {\n return;\n }\n position.setCoordinate(coordinate);\n dbManager.updatePositionCoordinates(position);\n }\n\n @Override\n public void updateLocation(String city, Coordinate coordinate) {\n currentPosition.setLocationName(city);\n currentPosition.setCoordinate(coordinate);\n if (activePosition == currentPosition) {\n sendRequest();\n }\n }\n\n public void updatePositionTimeZone(Position city, int timeZone) {\n city.setTimeZone(timeZone);\n dbManager.updateCityTimeZone(city);\n }\n\n public void initLocationManager() {\n locationManager = new CurrentLocationManager();\n locationManager.giveGpsAccess(true);\n try {\n updateCurrentLocation(locationManager.getLastLocation());\n } catch (AccessFineLocationNotGrantedException | EmptyCurrentAddressException e) {\n e.printStackTrace();\n }\n }\n\n public boolean isSomeLocationProviderAvailable() {\n return locationManager.checkProviders();\n }\n\n public void setUseGpsModule(boolean useGpsModule) {\n locationManager.giveGpsAccess(useGpsModule);\n }\n\n public void updateCurrentLocationCoordinates() {\n try {\n locationManager.updateCurrLocCoordinates();\n } catch (NoAvailableLocationServiceException e) {\n sendMessage(R.string.error_location_services_are_not_active, Snackbar.LENGTH_LONG);\n e.printStackTrace();\n } catch (GpsIsDisabledException e) {\n sendMessage(R.string.error_gps_disabled, Snackbar.LENGTH_LONG);\n e.printStackTrace();\n } catch (AccessFineLocationNotGrantedException | NullPointerException e) {\n e.printStackTrace();\n }\n }\n\n public Coordinate getCurrentLocationCoordinates() {\n return currentPosition.getCoordinate();\n }\n\n public String getCurrentLocationName() {\n return currentPosition.getLocationName();\n }\n\n public void setCurrentLocationCoordinates(Location location) {\n boolean coordinatesUpdated = updateCurrentLocation(location);\n if (coordinatesUpdated && activePosition == currentPosition) {\n new Handler().postDelayed(new Runnable() {\n @Override\n public void run() {\n sendRequest();\n }\n }, 3000);\n } else if (!coordinatesUpdated) {\n GoogleMapsGeocoding googleMapsGeocoding = new GoogleMapsGeocoding();\n googleMapsGeocoding.requestLocationName(location.getLatitude(), location.getLongitude(), this);\n }\n }\n\n private boolean updateCurrentLocation(Location location) {\n if (location == null) {\n sendMessage(R.string.error_service_not_available, Snackbar.LENGTH_LONG);\n return false;\n }\n Geocoder geocoder = new Geocoder(MyApplication.getAppContext());\n try {\n List<Address> list = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 3);\n currentPosition.setLocationName(new LocationParser(list).parseList().getAddressLine());\n currentPosition.setCoordinate(new Coordinate(location.getLatitude(), location.getLongitude()));\n } catch (IOException | IllegalArgumentException | EmptyCurrentAddressException | NoAvailableAddressesException | NullPointerException e) {\n e.printStackTrace();\n return false;\n } catch (Exception e) {\n e.printStackTrace();\n return false;\n }\n return true;\n }\n\n private synchronized void sendMessage(CharSequence string, int length) {\n try {\n messageProvider.showSnackbar(string, length);\n } catch (NullPointerException e) {\n e.printStackTrace();\n }\n }\n\n private synchronized void sendMessage(int stringId, int length) {\n try {\n messageProvider.showSnackbar(stringId, length);\n } catch (NullPointerException e) {\n e.printStackTrace();\n }\n }\n\n public void generateIconSet(Context context) {\n iconsSet = AppUtils.createIconsSet(context);\n SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);\n String iconsSet = sp.getString(context.getString(R.string.pref_icons_set_key), context.getString(R.string.pref_icons_set_default));\n currentWeatherIconColor = ContextCompat.getColor(context, R.color.current_weather_color);\n forecastWeatherIconColor = ContextCompat.getColor(context, R.color.text_primary);\n if (iconsSet.equals(context.getString(R.string.pref_icons_set_mike_color))) {\n isSvgIconsUsed = true;\n int currentNightMode = context.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;\n String colorScheme = sp.getString(context.getString(R.string.pref_color_scheme_key), context.getString(R.string.pref_color_scheme_teal));\n if (currentNightMode == Configuration.UI_MODE_NIGHT_YES) {\n } else if (colorScheme.equals(context.getString(R.string.pref_color_scheme_brown))) {\n forecastWeatherIconColor = ContextCompat.getColor(context, R.color.primary_brown);\n } else if (colorScheme.equals(context.getString(R.string.pref_color_scheme_teal))) {\n forecastWeatherIconColor = ContextCompat.getColor(context, R.color.primary_teal);\n } else if (colorScheme.equals(context.getString(R.string.pref_color_scheme_indigo))) {\n forecastWeatherIconColor = ContextCompat.getColor(context, R.color.primary_indigo);\n } else if (colorScheme.equals(context.getString(R.string.pref_color_scheme_purple))) {\n forecastWeatherIconColor = ContextCompat.getColor(context, R.color.primary_purple);\n } else {\n forecastWeatherIconColor = ContextCompat.getColor(context, R.color.primary_green);\n }\n } else {\n isSvgIconsUsed = iconsSet.equals(context.getString(R.string.pref_icons_set_mike_bw));\n }\n }\n\n public Drawable getWeatherIcon(int iconNumber, boolean isCurrentWeatherIcon) {\n Drawable icon;\n try {\n if (iconsSet[iconNumber] != null) {\n icon = iconsSet[iconNumber];\n if (isSvgIconsUsed) {\n if (isCurrentWeatherIcon) {\n IconicsDrawable cIcon = ((IconicsDrawable) icon).clone();\n cIcon.color(currentWeatherIconColor);\n return cIcon;\n } else {\n icon = ((IconicsDrawable) icon)\n .color(forecastWeatherIconColor);\n }\n }\n } else if (isCurrentWeatherIcon) {\n IconicsDrawable cIcon = ((IconicsDrawable) iconsSet[AppUtils.ICON_INDEX_NA])\n .clone();\n cIcon.color(currentWeatherIconColor);\n return cIcon;\n } else {\n icon = ((IconicsDrawable) iconsSet[AppUtils.ICON_INDEX_NA])\n .color(forecastWeatherIconColor);\n }\n } catch (NullPointerException e) {\n e.printStackTrace();\n if (isCurrentWeatherIcon) {\n icon = iconNa.clone();\n ((IconicsDrawable) icon).color(currentWeatherIconColor);\n } else {\n icon = iconNa.color(forecastWeatherIconColor);\n }\n }\n return icon;\n }\n}", "public class AppUtils {\n\n public static final String ApiCustomEvent = \"Error\";\n\n public static final double KELVIN_CELSIUS_DELTA = 273.15;\n public static final double HPA_TO_MM_HG = 1.33322;\n public static final double KM_TO_MILES = 0.62137;\n public static final double METER_TO_FOOT = 3.28083;\n\n //Icons set\n private static final int ICONS_COUNT = 84;\n\n public static final int ICON_INDEX_THUNDERSTORM_LIGHT_RAIN = 0;\n public static final int ICON_INDEX_THUNDERSTORM_RAIN = 1;\n public static final int ICON_INDEX_THUNDERSTORM_HEAVY_RAIN = 2;\n public static final int ICON_INDEX_LIGHT_THUNDERSTORM = 3;\n public static final int ICON_INDEX_THUNDERSTORM = 4;\n public static final int ICON_INDEX_HEAVY_THUNDERSTORM = 5;\n public static final int ICON_INDEX_RAGGED_THUNDERSTORM = 6;\n public static final int ICON_INDEX_THUNDERSTORM_LIGHT_DRIZZLE = 7;\n public static final int ICON_INDEX_THUNDERSTORM_DRIZZLE = 8;\n public static final int ICON_INDEX_THUNDERSTORM_HEAVY_DRIZZLE = 9;\n\n public static final int ICON_INDEX_LIGHT_INTENSITY_DRIZZLE = 10;\n public static final int ICON_INDEX_DRIZZLE = 11;\n public static final int ICON_INDEX_HEAVY_INTENSITY_DRIZZLE = 12;\n public static final int ICON_INDEX_LIGHT_INTENSITY_DRIZZLE_RAIN = 13;\n public static final int ICON_INDEX_DRIZZLE_RAIN = 14;\n public static final int ICON_INDEX_HEAVY_INTENSITY_DRIZZLE_RAIN = 15;\n public static final int ICON_INDEX_SHOWER_RAIN_AND_DRIZZLE = 16;\n public static final int ICON_INDEX_HEAVY_SHOWER_RAIN_AND_DRIZZLE = 17;\n public static final int ICON_INDEX_SHOWER_DRIZZLE = 18;\n\n public static final int ICON_INDEX_LIGHT_RAIN = 19;\n public static final int ICON_INDEX_MODERATE_RAIN = 20;\n public static final int ICON_INDEX_HEAVY_INTENSITY_RAIN = 21;\n public static final int ICON_INDEX_VERY_HEAVY_RAIN = 22;\n public static final int ICON_INDEX_EXTREME_RAIN = 23;\n public static final int ICON_INDEX_LIGHT_RAIN_NIGHT = 24;\n public static final int ICON_INDEX_MODERATE_RAIN_NIGHT = 25;\n public static final int ICON_INDEX_HEAVY_INTENSITY_RAIN_NIGHT = 26;\n public static final int ICON_INDEX_VERY_HEAVY_RAIN_NIGHT = 27;\n public static final int ICON_INDEX_EXTREME_RAIN_NIGHT = 28;\n public static final int ICON_INDEX_FREEZING_RAIN = 29;\n public static final int ICON_INDEX_LIGHT_INTENSITY_SHOWER_RAIN = 30;\n public static final int ICON_INDEX_SHOWER_RAIN = 31;\n public static final int ICON_INDEX_HEAVY_INTENSITY_SHOWER_RAIN = 32;\n public static final int ICON_INDEX_RAGGED_SHOWER_RAIN = 33;\n\n public static final int ICON_INDEX_LIGHT_SNOW = 34;\n public static final int ICON_INDEX_SNOW = 35;\n public static final int ICON_INDEX_HEAVY_SNOW = 36;\n public static final int ICON_INDEX_SLEET = 37;\n public static final int ICON_INDEX_SHOWER_SLEET = 38;\n public static final int ICON_INDEX_LIGHT_RAIN_AND_SNOW = 39;\n public static final int ICON_INDEX_RAIN_AND_SNOW = 40;\n public static final int ICON_INDEX_LIGHT_SHOWER_SNOW = 41;\n public static final int ICON_INDEX_SHOWER_SNOW = 42;\n public static final int ICON_INDEX_HEAVY_SHOWER_SNOW = 43;\n\n public static final int ICON_INDEX_MIST = 44;\n public static final int ICON_INDEX_SMOKE = 45;\n public static final int ICON_INDEX_HAZE = 46;\n public static final int ICON_INDEX_SAND_DUST_WHIRLS = 47;\n public static final int ICON_INDEX_FOG = 48;\n public static final int ICON_INDEX_SAND = 49;\n public static final int ICON_INDEX_DUST = 50;\n public static final int ICON_INDEX_VOLCANIC_ASH = 51;\n public static final int ICON_INDEX_SQUALLS = 52;\n public static final int ICON_INDEX_TORNADO = 53;\n\n public static final int ICON_INDEX_CLEAR_SKY_SUN = 54;\n public static final int ICON_INDEX_CLEAR_SKY_MOON = 55;\n\n public static final int ICON_INDEX_FEW_CLOUDS = 56;\n public static final int ICON_INDEX_SCATTERED_CLOUDS = 57;\n public static final int ICON_INDEX_BROKEN_CLOUDS = 58;\n public static final int ICON_INDEX_OVERCAST_CLOUDS = 59;\n public static final int ICON_INDEX_FEW_CLOUDS_NIGHT = 60;\n public static final int ICON_INDEX_SCATTERED_CLOUDS_NIGHT = 61;\n public static final int ICON_INDEX_BROKEN_CLOUDS_NIGHT = 62;\n public static final int ICON_INDEX_OVERCAST_CLOUDS_NIGHT = 63;\n\n public static final int ICON_INDEX_EXTREME_TORNADO = 64;\n public static final int ICON_INDEX_EXTREME_TROPICAL_STORM = 65;\n public static final int ICON_INDEX_EXTREME_HURRICANE = 66;\n public static final int ICON_INDEX_EXTREME_COLD = 67;\n public static final int ICON_INDEX_EXTREME_HOT = 68;\n public static final int ICON_INDEX_EXTREME_WINDY = 69;\n public static final int ICON_INDEX_EXTREME_HAIL = 70;\n\n public static final int ICON_INDEX_CALM = 71;\n public static final int ICON_INDEX_LIGHT_BREEZE = 72;\n public static final int ICON_INDEX_GENTLE_BREEZE = 73;\n public static final int ICON_INDEX_MODERATE_BREEZE = 74;\n public static final int ICON_INDEX_FRESH_BREEZE = 75;\n public static final int ICON_INDEX_STRONG_BREEZE = 76;\n public static final int ICON_INDEX_HIGH_WIND_NEAR_GALE = 77;\n public static final int ICON_INDEX_GALE = 78;\n public static final int ICON_INDEX_SEVERE_GALE = 79;\n public static final int ICON_INDEX_STORM = 80;\n public static final int ICON_INDEX_VIOLENT_STORM = 81;\n public static final int ICON_INDEX_HURRICANE = 82;\n\n public static final int ICON_INDEX_NA = 83;\n\n public enum TemperatureMetrics {\n KELVIN {\n public TemperatureMetrics change() {\n return CELSIUS;\n }\n\n public String toStringValue() {\n return MyApplication.getAppContext().getString(R.string.measure_temperature_kelvin);\n }\n },\n CELSIUS {\n public TemperatureMetrics change() {\n return FAHRENHEIT;\n }\n\n public String toStringValue() {\n return MyApplication.getAppContext().getString(R.string.measure_temperature_celsius);\n }\n\n },\n FAHRENHEIT {\n public TemperatureMetrics change() {\n return KELVIN;\n }\n\n public String toStringValue() {\n return MyApplication.getAppContext().getString(R.string.measure_temperature_fahrenheit);\n }\n };\n\n public abstract TemperatureMetrics change();\n\n public abstract String toStringValue();\n }\n\n public enum SpeedMetrics {\n METER_PER_SECOND {\n @Override\n public String toStringValue() {\n return MyApplication.getAppContext().getString(R.string.measure_speed_m_s);\n }\n },\n FOOT_PER_SECOND {\n @Override\n public String toStringValue() {\n return MyApplication.getAppContext().getString(R.string.measure_speed_fps);\n }\n },\n KM_PER_HOURS {\n @Override\n public String toStringValue() {\n return MyApplication.getAppContext().getString(R.string.measure_speed_km_h);\n }\n },\n MILES_PER_HOURS {\n @Override\n public String toStringValue() {\n return MyApplication.getAppContext().getString(R.string.measure_speed_mph);\n }\n };\n\n public abstract String toStringValue();\n }\n\n public enum PressureMetrics {\n HPA {\n public PressureMetrics change() {\n return MM_HG;\n }\n\n @Override\n public String toStringValue() {\n return MyApplication.getAppContext().getString(R.string.measure_pressure_hpa);\n }\n },\n MM_HG {\n public PressureMetrics change() {\n return HPA;\n }\n\n @Override\n public String toStringValue() {\n return MyApplication.getAppContext().getString(R.string.measure_pressure_mmHg);\n }\n };\n\n public abstract PressureMetrics change();\n\n public abstract String toStringValue();\n }\n\n public static void showSnackBar(Activity activity, View view, CharSequence string, int length) {\n if (view == null) {\n if (activity != null) {\n showInfoMessage(activity, string).show();\n } else {\n showInfoMessage(string).show();\n }\n return;\n }\n Snackbar snackbar = Snackbar.make(view, string, length);\n View snackbarView = snackbar.getView();\n // Default background fill: #323232 100%\n // snackbarView.setBackgroundColor(ContextCompat.getColor(MyApplication.getAppContext(), R.color.primary_dark));\n TextView textView = (TextView) snackbarView.findViewById(android.support.design.R.id.snackbar_text);\n textView.setTextColor(ContextCompat.getColor(MyApplication.getAppContext(), R.color.snackbar_text));\n snackbar.show();\n }\n\n public static Toast showInfoMessage(Activity activity, CharSequence string) {\n LayoutInflater inflater = activity.getLayoutInflater();\n View layout = inflater.inflate(R.layout.warning_toast, ((ViewGroup) activity.findViewById(R.id.toast_layout_root)));\n ((TextView) layout.findViewById(R.id.warningMessage)).setText(string);\n Toast toast = new Toast(MyApplication.getAppContext());\n toast.setDuration(Toast.LENGTH_SHORT);\n toast.setView(layout);\n return toast;\n }\n\n public static Toast showInfoMessage(CharSequence string) {\n return Toast.makeText(MyApplication.getAppContext(), string, Toast.LENGTH_SHORT);\n }\n\n\n /**\n * Метод для конвертирования ответа от API в коллекцию типа {@link Map}<{@link Calendar}, {@link Weather}>\n * для запроса текущего прогноза погоды.\n *\n * @param response объект типа {@link OpenWeatherMapResponse}, содержащий ответ от API.\n * @param cityID\n */\n public static Map<Calendar, Weather> convertToWeather(OpenWeatherMapResponse response, int cityID) {\n Map<Calendar, Weather> map = new HashMap<>();\n Weather weather = new Weather();\n int offset = PositionManager.getInstance().getPosition(cityID).getTimeZone();\n Calendar calendar = unixToCalendar(response.getDt() + offset);\n weather.setTemperature(response.getMain().getTemp());\n weather.setHumidity(response.getMain().getHumidity());\n weather.setPressure(response.getMain().getPressure());\n weather.setSunrise(response.getSys().getSunrise());\n weather.setSunset(response.getSys().getSunset());\n setPrecipitationType(response.getWeather().get(0).getId(), weather);\n double speed = response.getWind().getSpeed();\n double deg = response.getWind().getDeg();\n setWindDirectionAndSpeed(weather, speed, deg);\n String description = null;\n for (com.khasang.forecast.models.Weather descr : response.getWeather()) {\n description = descr.getDescription();\n }\n weather.setDescription(description);\n map.put(calendar, weather);\n return map;\n }\n\n /**\n * Метод для конвертирования ответа от API в коллекцию типа {@link Map}<{@link Calendar}, {@link Weather}>\n * для запроса почасового прогноза погоды.\n *\n * @param response объект типа {@link OpenWeatherMapResponse}, содержащий ответ от API.\n * @param cityID\n */\n public static Map<Calendar, Weather> convertToHourlyWeather(OpenWeatherMapResponse response, int cityID) {\n Map<Calendar, Weather> map = new HashMap<>();\n for (HourlyForecastList forecast : response.getList()) {\n int offset = PositionManager.getInstance().getPosition(cityID).getTimeZone();\n Calendar calendar = unixToCalendar(forecast.getDt() + offset);\n Weather weather = new Weather();\n weather.setTemperature(forecast.getMain().getTemp());\n weather.setHumidity(forecast.getMain().getHumidity());\n weather.setPressure(forecast.getMain().getPressure());\n double speed = forecast.getWind().getSpeed();\n double deg = forecast.getWind().getDeg();\n setWindDirectionAndSpeed(weather, speed, deg);\n setPrecipitationType(forecast.getWeather().get(0).getId(), weather);\n String description = null;\n for (com.khasang.forecast.models.Weather descr : forecast.getWeather()) {\n description = descr.getDescription();\n }\n weather.setDescription(description);\n map.put(calendar, weather);\n }\n return map;\n }\n\n /**\n * Метод для конвертирования ответа от API в коллекцию типа {@link Map}<{@link Calendar}, {@link Weather}>\n * для запроса прогноза погоды по дням.\n *\n * @param response объект типа {@link DailyResponse}, содержащий ответ от API.\n * @param cityID\n */\n public static Map<Calendar, Weather> convertToDailyWeather(DailyResponse response, int cityID) {\n Map<Calendar, Weather> map = new HashMap<>();\n for (DailyForecastList forecast : response.getList()) {\n int offset = PositionManager.getInstance().getPosition(cityID).getTimeZone();\n Calendar calendar = unixToCalendar(forecast.getDt() + offset);\n Weather weather = new Weather();\n weather.setTemperature(forecast.getTemp().getDay());\n weather.setHumidity(forecast.getHumidity());\n weather.setPressure(forecast.getPressure());\n double speed = forecast.getSpeed();\n double deg = forecast.getDeg();\n setWindDirectionAndSpeed(weather, speed, deg);\n setPrecipitationType(forecast.getWeather().get(0).getId(), weather);\n String description = null;\n for (com.khasang.forecast.models.Weather descr : forecast.getWeather()) {\n description = descr.getDescription();\n }\n weather.setDescription(description);\n map.put(calendar, weather);\n }\n return map;\n }\n\n /**\n * Метод преобразует градусы направления ветра в перечисление типа Wind.Direction,\n * а так же устанавливает свойства для класса {@link Weather}.\n *\n * @param weather объект типа {@link Weather}.\n * @param speed скорость ветра в м/с.\n * @param deg направление ветра в градусах.\n */\n private static void setWindDirectionAndSpeed(Weather weather, double speed, double deg) {\n if ((deg >= 0 && deg <= 22.5) || (deg > 337.5 && deg <= 360)) {\n weather.setWind(Wind.Direction.NORTH, speed);\n } else if (deg > 22.5 && deg <= 67.5) {\n weather.setWind(Wind.Direction.NORTHEAST, speed);\n } else if (deg > 67.5 && deg <= 112.5) {\n weather.setWind(Wind.Direction.EAST, speed);\n } else if (deg > 112.5 && deg <= 157.5) {\n weather.setWind(Wind.Direction.SOUTHEAST, speed);\n } else if (deg > 157.5 && deg <= 202.5) {\n weather.setWind(Wind.Direction.SOUTH, speed);\n } else if (deg > 202.5 && deg <= 247.5) {\n weather.setWind(Wind.Direction.SOUTHWEST, speed);\n } else if (deg > 247.5 && deg <= 292.5) {\n weather.setWind(Wind.Direction.WEST, speed);\n } else if (deg > 292.5 && deg <= 337.5) {\n weather.setWind(Wind.Direction.NORTHWEST, speed);\n }\n }\n\n /**\n * Метод, преобразующий UNIX-время в объект типа {@link Calendar}.\n *\n * @param unixTime UNIX-время.\n */\n private static Calendar unixToCalendar(long unixTime) {\n Calendar calendar = Calendar.getInstance();\n calendar.setTimeInMillis(unixTime * 1000L);\n return calendar;\n }\n\n public static Drawable[] createIconsSet(Context context) {\n Drawable[] iconsSet = new Drawable[ICONS_COUNT];\n SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);\n String iconSetType = sp.getString(context.getString(R.string.pref_icons_set_key), context.getString(R.string.pref_icons_set_default));\n if (iconSetType.equals(context.getString(R.string.pref_icons_set_mike_color))) {\n iconsSet[ICON_INDEX_THUNDERSTORM_LIGHT_RAIN] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_200).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_THUNDERSTORM_RAIN] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_201).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_THUNDERSTORM_HEAVY_RAIN] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_202).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_LIGHT_THUNDERSTORM] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_210).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_THUNDERSTORM] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_211).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_HEAVY_THUNDERSTORM] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_212).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_RAGGED_THUNDERSTORM] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_221).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_THUNDERSTORM_LIGHT_DRIZZLE] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_230).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_THUNDERSTORM_DRIZZLE] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_231).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_THUNDERSTORM_HEAVY_DRIZZLE] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_232).sizeDp(80).paddingDp(4);\n\n iconsSet[ICON_INDEX_LIGHT_INTENSITY_DRIZZLE] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_300).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_DRIZZLE] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_301).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_HEAVY_INTENSITY_DRIZZLE] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_302).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_LIGHT_INTENSITY_DRIZZLE_RAIN] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_310).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_DRIZZLE_RAIN] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_311).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_HEAVY_INTENSITY_DRIZZLE_RAIN] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_312).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_SHOWER_RAIN_AND_DRIZZLE] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_313).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_HEAVY_SHOWER_RAIN_AND_DRIZZLE] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_314).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_SHOWER_DRIZZLE] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_321).sizeDp(80).paddingDp(4);\n\n iconsSet[ICON_INDEX_LIGHT_RAIN] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_day_500).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_MODERATE_RAIN] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_day_501).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_HEAVY_INTENSITY_RAIN] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_day_502).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_VERY_HEAVY_RAIN] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_day_503).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_EXTREME_RAIN] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_day_504).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_LIGHT_RAIN_NIGHT] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_night_500).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_MODERATE_RAIN_NIGHT] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_night_501).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_HEAVY_INTENSITY_RAIN_NIGHT] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_night_502).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_VERY_HEAVY_RAIN_NIGHT] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_night_503).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_EXTREME_RAIN_NIGHT] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_night_504).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_FREEZING_RAIN] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_511).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_LIGHT_INTENSITY_SHOWER_RAIN] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_520).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_SHOWER_RAIN] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_521).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_HEAVY_INTENSITY_SHOWER_RAIN] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_522).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_RAGGED_SHOWER_RAIN] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_531).sizeDp(80).paddingDp(4);\n\n iconsSet[ICON_INDEX_LIGHT_SNOW] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_600).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_SNOW] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_601).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_HEAVY_SNOW] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_602).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_SLEET] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_611).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_SHOWER_SLEET] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_612).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_LIGHT_RAIN_AND_SNOW] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_615).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_RAIN_AND_SNOW] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_616).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_LIGHT_SHOWER_SNOW] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_620).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_SHOWER_SNOW] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_621).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_HEAVY_SHOWER_SNOW] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_622).sizeDp(80).paddingDp(4);\n\n iconsSet[ICON_INDEX_MIST] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_731).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_SMOKE] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_711).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_HAZE] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_721).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_SAND_DUST_WHIRLS] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_731).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_FOG] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_741).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_SAND] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_sandstorm).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_DUST] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_sandstorm).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_VOLCANIC_ASH] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_volcano).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_SQUALLS] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_771).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_TORNADO] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_781).sizeDp(80).paddingDp(4);\n\n iconsSet[ICON_INDEX_CLEAR_SKY_SUN] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_day_800).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_CLEAR_SKY_MOON] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_night_800).sizeDp(80).paddingDp(4);\n\n iconsSet[ICON_INDEX_FEW_CLOUDS] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_day_801).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_FEW_CLOUDS_NIGHT] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_night_801).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_SCATTERED_CLOUDS] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_day_802).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_SCATTERED_CLOUDS_NIGHT] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_night_802).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_BROKEN_CLOUDS] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_803).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_BROKEN_CLOUDS_NIGHT] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_803).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_OVERCAST_CLOUDS] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_804).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_OVERCAST_CLOUDS_NIGHT] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_804).sizeDp(80).paddingDp(4);\n\n iconsSet[ICON_INDEX_EXTREME_TORNADO] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_900).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_EXTREME_TROPICAL_STORM] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_901).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_EXTREME_HURRICANE] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_902).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_EXTREME_COLD] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_903).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_EXTREME_HOT] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_904).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_EXTREME_WINDY] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_strong_wind).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_EXTREME_HAIL] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_906).sizeDp(80).paddingDp(4);\n\n iconsSet[ICON_INDEX_CALM] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_wind_beaufort_1).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_LIGHT_BREEZE] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_wind_beaufort_2).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_GENTLE_BREEZE] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_wind_beaufort_3).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_MODERATE_BREEZE] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_wind_beaufort_4).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_FRESH_BREEZE] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_wind_beaufort_5).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_STRONG_BREEZE] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_wind_beaufort_6).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_HIGH_WIND_NEAR_GALE] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_wind_beaufort_7).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_GALE] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_wind_beaufort_8).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_SEVERE_GALE] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_wind_beaufort_9).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_STORM] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_wind_beaufort_10).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_VIOLENT_STORM] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_wind_beaufort_11).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_HURRICANE] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_wind_beaufort_12).sizeDp(80).paddingDp(4);\n\n } else if (iconSetType.equals(context.getString(R.string.pref_icons_set_mike_bw))) {\n\n iconsSet[ICON_INDEX_THUNDERSTORM_LIGHT_RAIN] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_cloud_flash_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_THUNDERSTORM_RAIN] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_cloud_flash_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_THUNDERSTORM_HEAVY_RAIN] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_cloud_flash_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_LIGHT_THUNDERSTORM] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_clouds_flash_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_THUNDERSTORM] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_clouds_flash_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_HEAVY_THUNDERSTORM] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_lightning).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_RAGGED_THUNDERSTORM] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_lightning).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_THUNDERSTORM_LIGHT_DRIZZLE] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_cloud_flash_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_THUNDERSTORM_DRIZZLE] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_cloud_flash_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_THUNDERSTORM_HEAVY_DRIZZLE] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_cloud_flash_inv).sizeDp(80).paddingDp(4);\n\n iconsSet[ICON_INDEX_LIGHT_INTENSITY_DRIZZLE] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_raindrop).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_DRIZZLE] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_raindrops).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_HEAVY_INTENSITY_DRIZZLE] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_rain_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_LIGHT_INTENSITY_DRIZZLE_RAIN] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_rain_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_DRIZZLE_RAIN] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_rain_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_HEAVY_INTENSITY_DRIZZLE_RAIN] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_rain_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_SHOWER_RAIN_AND_DRIZZLE] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_drizzle_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_HEAVY_SHOWER_RAIN_AND_DRIZZLE] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_rain_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_SHOWER_DRIZZLE] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_raindrops).sizeDp(80).paddingDp(4);\n\n iconsSet[ICON_INDEX_LIGHT_RAIN] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_raindrops).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_MODERATE_RAIN] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_rain_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_HEAVY_INTENSITY_RAIN] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_rain_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_VERY_HEAVY_RAIN] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_rain_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_EXTREME_RAIN] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_rain_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_LIGHT_RAIN_NIGHT] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_rain_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_MODERATE_RAIN_NIGHT] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_rain_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_HEAVY_INTENSITY_RAIN_NIGHT] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_rain_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_VERY_HEAVY_RAIN_NIGHT] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_rain_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_EXTREME_RAIN_NIGHT] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_rain_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_FREEZING_RAIN] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_rain_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_LIGHT_INTENSITY_SHOWER_RAIN] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_rain_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_SHOWER_RAIN] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_rain_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_HEAVY_INTENSITY_SHOWER_RAIN] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_rain_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_RAGGED_SHOWER_RAIN] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_cloud_flash_inv).sizeDp(80).paddingDp(4);\n\n iconsSet[ICON_INDEX_LIGHT_SNOW] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_snow_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_SNOW] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_snow_heavy_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_HEAVY_SNOW] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_snow_heavy_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_SLEET] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_snow_heavy_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_SHOWER_SLEET] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_snow_heavy_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_LIGHT_RAIN_AND_SNOW] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_snow_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_RAIN_AND_SNOW] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_snow_heavy_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_LIGHT_SHOWER_SNOW] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_snow_heavy_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_SHOWER_SNOW] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_snow_heavy_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_HEAVY_SHOWER_SNOW] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_snow_heavy_inv).sizeDp(80).paddingDp(4);\n\n iconsSet[ICON_INDEX_MIST] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_mist).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_SMOKE] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_smog).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_HAZE] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_fog).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_SAND_DUST_WHIRLS] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_fog).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_FOG] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_fog).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_SAND] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_sandstorm).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_DUST] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_sandstorm).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_VOLCANIC_ASH] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_volcano).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_SQUALLS] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_strong_wind).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_TORNADO] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_tornado).sizeDp(80).paddingDp(4);\n\n iconsSet[ICON_INDEX_CLEAR_SKY_SUN] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_sun_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_CLEAR_SKY_MOON] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_moon_inv).sizeDp(80).paddingDp(4);\n\n iconsSet[ICON_INDEX_FEW_CLOUDS] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_cloud_sun_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_FEW_CLOUDS_NIGHT] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_cloud_moon_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_SCATTERED_CLOUDS] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_cloud_sun_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_SCATTERED_CLOUDS_NIGHT] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_cloud_moon_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_BROKEN_CLOUDS] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_cloud_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_BROKEN_CLOUDS_NIGHT] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_cloud_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_OVERCAST_CLOUDS] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_clouds_inv).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_OVERCAST_CLOUDS_NIGHT] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_clouds_inv).sizeDp(80).paddingDp(4);\n\n iconsSet[ICON_INDEX_EXTREME_TORNADO] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_tornado).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_EXTREME_TROPICAL_STORM] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_lightning).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_EXTREME_HURRICANE] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_902).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_EXTREME_COLD] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_903).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_EXTREME_HOT] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_owm_904).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_EXTREME_WINDY] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_strong_wind).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_EXTREME_HAIL] = new IconicsDrawable(context).icon(Meteoconcs.Icon.met_hail_inv).sizeDp(80).paddingDp(4);\n\n iconsSet[ICON_INDEX_CALM] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_wind_beaufort_1).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_LIGHT_BREEZE] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_wind_beaufort_2).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_GENTLE_BREEZE] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_wind_beaufort_3).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_MODERATE_BREEZE] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_wind_beaufort_4).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_FRESH_BREEZE] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_wind_beaufort_5).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_STRONG_BREEZE] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_wind_beaufort_6).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_HIGH_WIND_NEAR_GALE] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_wind_beaufort_7).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_GALE] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_wind_beaufort_8).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_SEVERE_GALE] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_wind_beaufort_9).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_STORM] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_wind_beaufort_10).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_VIOLENT_STORM] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_wind_beaufort_11).sizeDp(80).paddingDp(4);\n iconsSet[ICON_INDEX_HURRICANE] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_wind_beaufort_12).sizeDp(80).paddingDp(4);\n } else {\n Drawable thunderstorm = ContextCompat.getDrawable(context, R.drawable.ic_thunderstorm);\n Drawable drizzle = ContextCompat.getDrawable(context, R.drawable.ic_drizzle);\n Drawable rain = ContextCompat.getDrawable(context, R.drawable.ic_rain);\n Drawable snow = ContextCompat.getDrawable(context, R.drawable.ic_snow);\n Drawable atmosphere = ContextCompat.getDrawable(context, R.drawable.ic_fog);\n Drawable sun = ContextCompat.getDrawable(context, R.drawable.ic_sun);\n Drawable moon = ContextCompat.getDrawable(context, R.drawable.ic_moon);\n Drawable clouds = ContextCompat.getDrawable(context, R.drawable.ic_cloud);\n Drawable extreme = ContextCompat.getDrawable(context, R.drawable.ic_extreme);\n\n for (int i = ICON_INDEX_THUNDERSTORM_LIGHT_RAIN; i <= ICON_INDEX_THUNDERSTORM_HEAVY_DRIZZLE; i++) {\n iconsSet[i] = thunderstorm;\n }\n for (int i = ICON_INDEX_LIGHT_INTENSITY_DRIZZLE; i <= ICON_INDEX_SHOWER_DRIZZLE; i++) {\n iconsSet[i] = drizzle;\n }\n for (int i = ICON_INDEX_LIGHT_RAIN; i <= ICON_INDEX_RAGGED_SHOWER_RAIN; i++) {\n iconsSet[i] = rain;\n }\n for (int i = ICON_INDEX_LIGHT_SNOW; i <= ICON_INDEX_HEAVY_SHOWER_SNOW; i++) {\n iconsSet[i] = snow;\n }\n for (int i = ICON_INDEX_MIST; i <= ICON_INDEX_TORNADO; i++) {\n iconsSet[i] = atmosphere;\n }\n iconsSet[ICON_INDEX_CLEAR_SKY_SUN] = sun;\n iconsSet[ICON_INDEX_CLEAR_SKY_MOON] = moon;\n for (int i = ICON_INDEX_FEW_CLOUDS; i <= ICON_INDEX_OVERCAST_CLOUDS_NIGHT; i++) {\n iconsSet[i] = clouds;\n }\n for (int i = ICON_INDEX_EXTREME_TORNADO; i <= ICON_INDEX_EXTREME_HAIL; i++) {\n iconsSet[i] = extreme;\n }\n for (int i = ICON_INDEX_CALM; i <= ICON_INDEX_HURRICANE; i++) {\n iconsSet[i] = extreme;\n }\n }\n iconsSet[ICON_INDEX_NA] = new IconicsDrawable(context).icon(WeatherIcons.Icon.wic_na).sizeDp(80).paddingDp(4);\n return iconsSet;\n }\n\n /**\n * Метод преобразует полученный тип осадков в перечисление типа Precipitation.Type, а так же\n * устанавливает свойства для класса {@link Weather}.\n *\n * @param id идентификатор типа осадков.\n * @param weather объект типа {@link Weather}.\n */\n private static void setPrecipitationType(int id, Weather weather) {\n if (id >= 200 && id < 300) {\n switch (id) {\n case 200:\n weather.setPrecipitation(Precipitation.Type.THUNDERSTORM_LIGHT_RAIN);\n break;\n case 201:\n weather.setPrecipitation(Precipitation.Type.THUNDERSTORM_RAIN);\n break;\n case 202:\n weather.setPrecipitation(Precipitation.Type.THUNDERSTORM_HEAVY_RAIN);\n break;\n case 210:\n weather.setPrecipitation(Precipitation.Type.LIGHT_THUNDERSTORM);\n break;\n case 212:\n weather.setPrecipitation(Precipitation.Type.HEAVY_THUNDERSTORM);\n break;\n case 221:\n weather.setPrecipitation(Precipitation.Type.RAGGED_THUNDERSTORM);\n break;\n case 230:\n weather.setPrecipitation(Precipitation.Type.THUNDERSTORM_LIGHT_DRIZZLE);\n break;\n case 231:\n weather.setPrecipitation(Precipitation.Type.THUNDERSTORM_DRIZZLE);\n break;\n case 232:\n weather.setPrecipitation(Precipitation.Type.THUNDERSTORM_HEAVY_DRIZZLE);\n break;\n default:\n weather.setPrecipitation(Precipitation.Type.THUNDERSTORM); // 211\n break;\n }\n } else if (id >= 300 && id < 400) {\n switch (id) {\n case 300:\n weather.setPrecipitation(Precipitation.Type.LIGHT_INTENSITY_DRIZZLE);\n break;\n case 302:\n weather.setPrecipitation(Precipitation.Type.HEAVY_INTENSITY_DRIZZLE);\n break;\n case 310:\n weather.setPrecipitation(Precipitation.Type.LIGHT_INTENSITY_DRIZZLE_RAIN);\n break;\n case 311:\n weather.setPrecipitation(Precipitation.Type.DRIZZLE_RAIN);\n break;\n case 312:\n weather.setPrecipitation(Precipitation.Type.HEAVY_INTENSITY_DRIZZLE_RAIN);\n break;\n case 313:\n weather.setPrecipitation(Precipitation.Type.SHOWER_RAIN_AND_DRIZZLE);\n break;\n case 314:\n weather.setPrecipitation(Precipitation.Type.HEAVY_SHOWER_RAIN_AND_DRIZZLE);\n break;\n case 321:\n weather.setPrecipitation(Precipitation.Type.SHOWER_DRIZZLE);\n break;\n default:\n weather.setPrecipitation(Precipitation.Type.DRIZZLE); // 301\n break;\n }\n } else if (id >= 500 && id < 600) {\n switch (id) {\n case 500:\n weather.setPrecipitation(Precipitation.Type.LIGHT_RAIN);\n break;\n case 501:\n weather.setPrecipitation(Precipitation.Type.MODERATE_RAIN);\n break;\n case 502:\n weather.setPrecipitation(Precipitation.Type.HEAVY_INTENSITY_RAIN);\n break;\n case 503:\n weather.setPrecipitation(Precipitation.Type.VERY_HEAVY_RAIN);\n break;\n case 504:\n weather.setPrecipitation(Precipitation.Type.EXTREME_RAIN);\n break;\n case 511:\n weather.setPrecipitation(Precipitation.Type.FREEZING_RAIN);\n break;\n case 520:\n weather.setPrecipitation(Precipitation.Type.LIGHT_INTENSITY_SHOWER_RAIN);\n break;\n case 521:\n weather.setPrecipitation(Precipitation.Type.SHOWER_RAIN);\n break;\n case 522:\n weather.setPrecipitation(Precipitation.Type.HEAVY_INTENSITY_SHOWER_RAIN);\n break;\n case 531:\n weather.setPrecipitation(Precipitation.Type.RAGGED_SHOWER_RAIN);\n break;\n default:\n weather.setPrecipitation(Precipitation.Type.RAIN); // DEFAULT == SHOWER_RAIN\n break;\n }\n } else if (id >= 600 && id < 700) {\n switch (id) {\n case 600:\n weather.setPrecipitation(Precipitation.Type.LIGHT_SNOW);\n break;\n case 602:\n weather.setPrecipitation(Precipitation.Type.HEAVY_SNOW);\n break;\n case 611:\n weather.setPrecipitation(Precipitation.Type.SLEET);\n break;\n case 612:\n weather.setPrecipitation(Precipitation.Type.SHOWER_SLEET);\n break;\n case 615:\n weather.setPrecipitation(Precipitation.Type.LIGHT_RAIN_AND_SNOW);\n break;\n case 616:\n weather.setPrecipitation(Precipitation.Type.RAIN_AND_SNOW);\n break;\n case 620:\n weather.setPrecipitation(Precipitation.Type.LIGHT_SHOWER_SNOW);\n break;\n case 621:\n weather.setPrecipitation(Precipitation.Type.SHOWER_SNOW);\n break;\n case 622:\n weather.setPrecipitation(Precipitation.Type.HEAVY_SHOWER_SNOW);\n break;\n default:\n weather.setPrecipitation(Precipitation.Type.SNOW); // 601\n break;\n }\n } else if (id >= 700 && id < 800) {\n switch (id) {\n case 701:\n weather.setPrecipitation(Precipitation.Type.MIST);\n break;\n case 711:\n weather.setPrecipitation(Precipitation.Type.SMOKE);\n break;\n case 721:\n weather.setPrecipitation(Precipitation.Type.HAZE);\n break;\n case 731:\n weather.setPrecipitation(Precipitation.Type.SAND_DUST_WHIRLS);\n break;\n case 741:\n weather.setPrecipitation(Precipitation.Type.FOG);\n break;\n case 751:\n weather.setPrecipitation(Precipitation.Type.SAND);\n break;\n case 761:\n weather.setPrecipitation(Precipitation.Type.DUST);\n break;\n case 762:\n weather.setPrecipitation(Precipitation.Type.VOLCANIC_ASH);\n break;\n case 771:\n weather.setPrecipitation(Precipitation.Type.SQUALLS);\n break;\n case 781:\n weather.setPrecipitation(Precipitation.Type.TORNADO);\n break;\n default:\n weather.setPrecipitation(Precipitation.Type.ATMOSPHERE); // DEFAULT == FOG\n break;\n }\n } else if (id == 800) {\n weather.setPrecipitation(Precipitation.Type.CLEAR_SKY);\n } else if (id > 800 && id < 805) {\n switch (id) {\n case 801:\n weather.setPrecipitation(Precipitation.Type.FEW_CLOUDS);\n break;\n case 802:\n weather.setPrecipitation(Precipitation.Type.SCATTERED_CLOUDS);\n break;\n case 803:\n weather.setPrecipitation(Precipitation.Type.BROKEN_CLOUDS);\n break;\n case 804:\n weather.setPrecipitation(Precipitation.Type.OVERCAST_CLOUDS);\n break;\n default:\n weather.setPrecipitation(Precipitation.Type.SCATTERED_CLOUDS); // DEFAULT == SCATTERED_CLOUDS\n break;\n }\n } else if (id >= 900 && id < 910) {\n switch (id) {\n case 900:\n weather.setPrecipitation(Precipitation.Type.EXTREME_TORNADO);\n break;\n case 901:\n weather.setPrecipitation(Precipitation.Type.EXTREME_TROPICAL_STORM);\n break;\n case 902:\n weather.setPrecipitation(Precipitation.Type.EXTREME_HURRICANE);\n break;\n case 903:\n weather.setPrecipitation(Precipitation.Type.EXTREME_COLD);\n break;\n case 904:\n weather.setPrecipitation(Precipitation.Type.EXTREME_HOT);\n break;\n case 905:\n weather.setPrecipitation(Precipitation.Type.EXTREME_WINDY);\n break;\n case 906:\n weather.setPrecipitation(Precipitation.Type.EXTREME_HAIL);\n break;\n default:\n weather.setPrecipitation(Precipitation.Type.EXTREME); // DEFAULT == ICON_INDEX_EXTREME_TORNADO;\n break;\n }\n } else if (id == 951) {\n weather.setPrecipitation(Precipitation.Type.CALM);\n } else if (id == 952) {\n weather.setPrecipitation(Precipitation.Type.LIGHT_BREEZE);\n } else if (id == 953) {\n weather.setPrecipitation(Precipitation.Type.GENTLE_BREEZE);\n } else if (id == 954) {\n weather.setPrecipitation(Precipitation.Type.MODERATE_BREEZE);\n } else if (id == 955) {\n weather.setPrecipitation(Precipitation.Type.FRESH_BREEZE);\n } else if (id == 956) {\n weather.setPrecipitation(Precipitation.Type.STRONG_BREEZE);\n } else if (id == 957) {\n weather.setPrecipitation(Precipitation.Type.HIGH_WIND_NEAR_GALE);\n } else if (id == 958) {\n weather.setPrecipitation(Precipitation.Type.GALE);\n } else if (id == 959) {\n weather.setPrecipitation(Precipitation.Type.SEVERE_GALE);\n } else if (id == 960) {\n weather.setPrecipitation(Precipitation.Type.STORM);\n } else if (id == 961) {\n weather.setPrecipitation(Precipitation.Type.VIOLENT_STORM);\n } else if (id == 962) {\n weather.setPrecipitation(Precipitation.Type.HURRICANE);\n } else {\n weather.setPrecipitation(Precipitation.Type.NO_DATA);\n }\n }\n\n /**\n * Метод для преобразования погодных характеристик в заданные пользователями метрики\n *\n * @param weather обьект класса {@link Weather}, в котором нужно привести погодные характеристики к заданным метрикам\n * @return обьект класса {@link Weather} с преобразованными погодными характеристиками\n */\n public static Weather formatWeather(Weather weather, AppUtils.TemperatureMetrics temperatureMetric, AppUtils.SpeedMetrics speedMetric, AppUtils.PressureMetrics pressureMetric) {\n weather.setTemperature(formatTemperature(weather.getTemperature(), temperatureMetric));\n weather.setPressure(formatPressure(weather.getPressure(), pressureMetric));\n weather.setWind(weather.getWindDirection(), formatSpeed(weather.getWindPower(), speedMetric));\n return weather;\n }\n\n /**\n * Метод для преобразования температуры в заданную пользователем метрику\n *\n * @param temperature температура на входе (в Кельвинах)\n * @param temperatureMetric\n * @return температура в выбранной пользователем метрике\n */\n public static double formatTemperature(double temperature, AppUtils.TemperatureMetrics temperatureMetric) {\n switch (temperatureMetric) {\n case KELVIN:\n break;\n case CELSIUS:\n return kelvinToCelsius(temperature);\n case FAHRENHEIT:\n return kelvinToFahrenheit(temperature);\n }\n return temperature;\n }\n\n /**\n * Метод для преобразования скорости ветра в заданную пользователем метрику\n *\n * @param speed преобразуемая скорость\n * @param speedMetric\n * @return скорость в выбранной пользователем метрике\n */\n public static double formatSpeed(double speed, AppUtils.SpeedMetrics speedMetric) {\n switch (speedMetric) {\n case METER_PER_SECOND:\n break;\n case FOOT_PER_SECOND:\n return meterInSecondToFootInSecond(speed);\n case KM_PER_HOURS:\n return meterInSecondToKmInHours(speed);\n case MILES_PER_HOURS:\n return meterInSecondToMilesInHour(speed);\n }\n return speed;\n }\n\n /**\n * Метод для преобразования давления в заданную пользователем метрику\n *\n * @param pressure преобразуемое давление\n * @param pressureMetric\n * @return давление в выбранной пользователем метрике\n */\n public static double formatPressure(double pressure, AppUtils.PressureMetrics pressureMetric) {\n switch (pressureMetric) {\n case HPA:\n break;\n case MM_HG:\n return hpaToMmHg(pressure);\n }\n return pressure;\n }\n\n /**\n * Метод для преобразования температуры из Кельвинов в Цельсии\n *\n * @param temperature температура в Кельвинах\n * @return температура в Цельсиях\n */\n public static double kelvinToCelsius(double temperature) {\n return temperature - KELVIN_CELSIUS_DELTA;\n }\n\n /**\n * Метод для преобразования температуры из Кельвина в Фаренгейт\n *\n * @param temperature температура в Кельвинах\n * @return температура в Фаренгейтах\n */\n public static double kelvinToFahrenheit(double temperature) {\n return (kelvinToCelsius(temperature) * 9 / 5) + 32;\n }\n\n /**\n * Метод для преобразования скорости ветра из метров в секунду в футы в секунду\n *\n * @param speed скорость ветра в метрах в секунду\n * @return скорость ветра в футах в секунду\n */\n public static double meterInSecondToFootInSecond(double speed) {\n return speed * METER_TO_FOOT;\n }\n\n /**\n * Метод для преобразования скорости ветра из метров в секунду в километры в час\n *\n * @param speed скорость ветра в метрах в секунду\n * @return скорость ветра в километрах в час\n */\n public static double meterInSecondToKmInHours(double speed) {\n return speed * 3.6;\n }\n\n /**\n * Метод для преобразования скорости ветра из метров в секунду в мили в час\n *\n * @param speed скорость ветра в метрах в секунду\n * @return скорость ветра в милях в час\n */\n public static double meterInSecondToMilesInHour(double speed) {\n return meterInSecondToKmInHours(speed) * KM_TO_MILES;\n }\n\n /**\n * Метод для преобразования давления из килопаскалей в мм.рт.ст.\n *\n * @param pressure давление в килопаскалях\n * @return давление в мм.рт.ст.\n */\n public static double hpaToMmHg(double pressure) {\n return pressure / HPA_TO_MM_HG;\n }\n\n /**\n * Определение времени суток\n */\n public static boolean isDayFromString(String timeString) {\n timeString = timeString.substring(0, 2);\n try {\n int time = Integer.parseInt(timeString);\n return !(time >= 21 || time < 6);\n } catch (NumberFormatException nfe) {\n return true;\n }\n }\n\n /**\n * Получение дня\n **/\n public static String getDayName(Context context, Calendar calendar) {\n int rightNow = Calendar.getInstance(Locale.getDefault()).get(Calendar.DAY_OF_MONTH);\n int today = calendar.get(Calendar.DAY_OF_MONTH);\n if (rightNow == today) {\n return context.getString(R.string.today);\n } else if (today == rightNow + 1) {\n return context.getString(R.string.tomorrow);\n } else {\n SimpleDateFormat dayFormat = new SimpleDateFormat(\"EEE, d MMMM\", Locale.getDefault());\n String myString = dayFormat.format(calendar.getTime());\n return myString.substring(0, 1).toUpperCase() + myString.substring(1);\n }\n }\n\n /**\n * Получение дня для графика\n **/\n public static String getChartDayName(Context context, Calendar calendar) {\n SimpleDateFormat dayFormat = new SimpleDateFormat(\"dd.MM\", Locale.getDefault());\n return dayFormat.format(calendar.getTime());\n }\n\n /**\n * Получение времени\n **/\n public static String getTime(Context context, Calendar calendar, int timeZone) {\n SimpleDateFormat timeFormat = new SimpleDateFormat(\"HH:mm\", Locale.getDefault());\n String time = timeFormat.format(calendar.getTime());\n return time;\n }\n\n /**\n * Получение времени для графика\n **/\n public static String getChartTime(Context context, Calendar calendar) {\n SimpleDateFormat timeFormat = new SimpleDateFormat(\"HH:mm\", Locale.getDefault());\n return timeFormat.format(calendar.getTime());\n }\n\n\n public static boolean isNetworkAvailable(Context context) {\n ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));\n return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();\n }\n}" ]
import android.content.SharedPreferences; import android.support.annotation.Nullable; import android.support.v7.preference.PreferenceManager; import com.crashlytics.android.Crashlytics; import com.crashlytics.android.answers.Answers; import com.crashlytics.android.answers.CustomEvent; import com.facebook.stetho.okhttp.StethoInterceptor; import com.khasang.forecast.MyApplication; import com.khasang.forecast.R; import com.khasang.forecast.models.DailyResponse; import com.khasang.forecast.models.OpenWeatherMapResponse; import com.khasang.forecast.position.Coordinate; import com.khasang.forecast.position.PositionManager; import com.khasang.forecast.utils.AppUtils; import com.squareup.okhttp.Cache; import com.squareup.okhttp.HttpUrl; import com.squareup.okhttp.Interceptor; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.logging.HttpLoggingInterceptor; import com.squareup.okhttp.logging.HttpLoggingInterceptor.Level; import java.io.File; import java.io.IOException; import java.util.LinkedList; import java.util.Locale; import io.fabric.sdk.android.Fabric; import retrofit.Call; import retrofit.Callback; import retrofit.GsonConverterFactory; import retrofit.Response; import retrofit.Retrofit;
package com.khasang.forecast.stations; /** * Этот класс скачивает и парсит данные с API в фоновом потоке, после чего отправляет их * на UI поток через методы onResponse или onFailure. */ public class OpenWeatherMap extends WeatherStation { private final static String API = "OpenWeaterMap API"; /** * Тэг для дебаггинга. */ private static final String TAG = OpenWeatherMap.class.getSimpleName(); /** * API URL. */ private static final String API_BASE_URL = "http://api.openweathermap.org"; /** * API ключ. */ private static final String APP_ID = MyApplication.getAppContext().getString(R.string.open_weather_map_key); /** * Количество 3-х часовых интервалов для запроса к API. */ private static final int TIME_PERIOD = 8; /** * Количество дней для запроса к API. */ private static final int DAYS_PERIOD = 7; /** * Получаем директорию кэша приложения. */ final @Nullable File baseDir = MyApplication.getAppContext().getCacheDir(); /** * Нам необходимо вручную создать экземпляр объекта HttpLoggingInterceptor и OkHttpClient, * потому что Retrofit версии 2.0.0-beta2 использует их старые версии, в которых еще нет * некоторых нужных нам возможностей. Например, получения полного тела запроса. */ private HttpLoggingInterceptor logging; private OkHttpClient client; /** * Создаем сервис из интерфейса {@link OpenWeatherMapService} с заданными конечными точками * для запроса. */ private OpenWeatherMapService service; /** * Конструктор. */ public OpenWeatherMap() { logging = new HttpLoggingInterceptor(); client = new OkHttpClient(); if (baseDir != null) { final File cacheDir = new File(baseDir, "HttpResponseCache"); client.setCache(new Cache(cacheDir, 10 * 1024 * 1024)); } addInterceptors(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(API_BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(client) .build(); service = retrofit.create(OpenWeatherMapService.class); } /** * Метод, который добавляет постоянно-используемые параметры к нашему запросу, а так же * устанавливает уровень логирования. */ private void addInterceptors() { logging.setLevel(Level.BODY); client.interceptors().add(new Interceptor() { @Override public com.squareup.okhttp.Response intercept(Chain chain) throws IOException { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MyApplication .getAppContext()); String key = MyApplication.getAppContext().getString(R.string.pref_language_key); String languageCode = sharedPreferences.getString(key, null); if (languageCode == null) { languageCode = Locale.getDefault().getLanguage(); } Request request = chain.request(); HttpUrl httpUrl = request.httpUrl().newBuilder() .addQueryParameter("lang", languageCode) .addQueryParameter("appid", APP_ID) .build(); request = request.newBuilder() .url(httpUrl) .build(); return chain.proceed(request); } }); client.interceptors().add(logging); client.networkInterceptors().add(new StethoInterceptor()); client.networkInterceptors().add(new Interceptor() { @Override public com.squareup.okhttp.Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); String cacheHeaderValue = AppUtils.isNetworkAvailable(MyApplication.getAppContext()) ? "public, max-age=900" : "public, only-if-cached, max-stale=14400"; Request request = originalRequest.newBuilder().build(); com.squareup.okhttp.Response response = chain.proceed(request); return response.newBuilder() .header("Cache-Control", cacheHeaderValue) .build(); } }); } /** * Метод для асинхронного получения текущего прогноза погоды. * * @param requestQueue коллекция типа * {@link LinkedList}, содержащая элементы {@link com.khasang.forecast.stations.WeatherStation.ResponseType}, * хранит очередность запросов (текущий прогноз, прогноз на день или неделю) * @param cityID внутренний идентификатор города. * @param coordinate объект типа {@link Coordinate}, содержащий географические координаты */ @Override
public void updateWeather(final LinkedList<ResponseType> requestQueue, final int cityID, final Coordinate
3
andrewoma/dexx
collection/src/test/java/com/github/andrewoma/dexx/collection/mutable/MutableArrayList.java
[ "public interface Builder<E, R> {\n @NotNull\n Builder<E, R> add(E element);\n\n @NotNull\n Builder<E, R> addAll(@NotNull Traversable<E> elements);\n\n @NotNull\n Builder<E, R> addAll(@NotNull java.lang.Iterable<E> elements);\n\n @NotNull\n Builder<E, R> addAll(@NotNull Iterator<E> iterator);\n\n @NotNull\n Builder<E, R> addAll(E e1, E e2, E... es);\n\n @NotNull\n R build();\n}", "public interface BuilderFactory<E, R> {\n @NotNull\n Builder<E, R> newBuilder();\n}", "public interface IndexedList<E> extends List<E> {\n @Override\n @NotNull\n IndexedList<E> set(int i, E elem);\n\n @Override\n @NotNull\n IndexedList<E> append(E elem);\n\n @Override\n @NotNull\n IndexedList<E> prepend(E elem);\n\n @Override\n @NotNull\n IndexedList<E> drop(int number);\n\n @Override\n @NotNull\n IndexedList<E> take(int number);\n\n @Override\n @NotNull\n IndexedList<E> range(int from, boolean fromInclusive, int to, boolean toInclusive);\n}", "public interface List<E> extends Iterable<E> {\n /**\n * Returns the element at the specified index in this list (zero-based).\n *\n * @throws IndexOutOfBoundsException if the index is out of range\n */\n E get(int i);\n\n /**\n * Returns a list with the element set to the value specified at the index (zero-based).\n *\n * @throws IndexOutOfBoundsException if the index is out of range\n */\n @NotNull\n List<E> set(int i, E elem);\n\n /**\n * Returns a list with the specified element appended to the bottom of the list.\n */\n @NotNull\n List<E> append(E elem);\n\n /**\n * Returns a list with the specified element prepended to the top of the list.\n */\n @NotNull\n List<E> prepend(E elem);\n\n /**\n * Returns the index of the first occurrence of the specified element in the list or -1 if there are no occurrences.\n */\n int indexOf(E elem);\n\n /**\n * Returns the index of the last occurrence of the specified element in the list or -1 if there are no occurrences.\n */\n int lastIndexOf(E elem);\n\n /**\n * Returns first element in the list or {@code null} if the list is empty.\n */\n @Nullable\n E first();\n\n /**\n * Returns last element in the list or {@code null} if the list is empty.\n */\n @Nullable\n E last();\n\n /**\n * Returns a list containing all elements in the list, excluding the first element. An empty list is\n * returned if the list is empty.\n */\n @NotNull\n List<E> tail();\n\n /**\n * Returns a list containing all elements in this list, excluding the first {@code number} of elements.\n */\n @NotNull\n List<E> drop(int number);\n\n /**\n * Returns a list containing the first {@code number} of elements from this list.\n */\n @NotNull\n List<E> take(int number);\n\n /**\n * Returns a list containing a contiguous range of elements from this list.\n *\n * @param from starting index for the range (zero-based)\n * @param fromInclusive if true, the element at the {@code from} index will be included\n * @param to end index for the range (zero-based)\n * @param toInclusive if true, the element at the {@code to} index will be included\n */\n @NotNull\n List<E> range(int from, boolean fromInclusive, int to, boolean toInclusive);\n\n /**\n * Returns an immutable view of this list as an instance of {@code java.util.List}.\n */\n @NotNull\n java.util.List<E> asList();\n}", "public abstract class AbstractIndexedList<E> extends AbstractList<E> implements IndexedList<E> {\n}", "public abstract class AbstractBuilder<E, R> implements Builder<E, R> {\n private boolean built = false;\n\n @NotNull\n @Override\n public Builder<E, R> addAll(@NotNull Traversable<E> elements) {\n elements.forEach(new Function<E, Object>() {\n @Override\n public Object invoke(E element) {\n add(element);\n return null;\n }\n });\n return this;\n }\n\n @NotNull\n @Override\n public Builder<E, R> addAll(@NotNull Iterable<E> elements) {\n for (E element : elements) {\n add(element);\n }\n return this;\n }\n\n @NotNull\n @Override\n public Builder<E, R> addAll(@NotNull Iterator<E> iterator) {\n while (iterator.hasNext()) {\n add(iterator.next());\n }\n return this;\n }\n\n @NotNull\n @Override\n public Builder<E, R> addAll(E e1, E e2, E... es) {\n add(e1);\n add(e2);\n for (E e : es) {\n add(e);\n }\n return this;\n }\n\n @NotNull\n @Override\n final public R build() {\n if (built) throw new IllegalStateException(\"Builders do not support multiple calls to build()\");\n built = true;\n return doBuild();\n }\n\n @NotNull\n public abstract R doBuild();\n}" ]
import java.util.ArrayList; import java.util.Iterator; import com.github.andrewoma.dexx.collection.Builder; import com.github.andrewoma.dexx.collection.BuilderFactory; import com.github.andrewoma.dexx.collection.IndexedList; import com.github.andrewoma.dexx.collection.List; import com.github.andrewoma.dexx.collection.internal.base.AbstractIndexedList; import com.github.andrewoma.dexx.collection.internal.builder.AbstractBuilder; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable;
/* * Copyright (c) 2014 Andrew O'Malley * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.andrewoma.dexx.collection.mutable; /** * */ public class MutableArrayList<E> extends AbstractIndexedList<E> { private java.util.List<E> underlying = new ArrayList<E>(); @NotNull public static <A> BuilderFactory<A, IndexedList<A>> factory() { return new BuilderFactory<A, IndexedList<A>>() { @NotNull @Override
public Builder<A, IndexedList<A>> newBuilder() {
0
antest1/kcanotify
app/src/main/java/com/antest1/kcanotify/KcaAkashiListViewItem.java
[ "public static String getItemTranslation(String jp_name) {\n String name = jp_name;\n if (currentLocaleCode.equals(\"jp\")) {\n return jp_name;\n } else if (kcItemTranslationData.has(name)) {\n name = kcItemTranslationData.get(name).getAsString();\n }\n return name;\n}", "public static JsonObject getKcItemStatusById(int id, String list) {\n if (kcGameData == null) return null;\n JsonObject temp = new JsonObject();\n if (kcItemData.containsKey(id)) {\n if (list.equals(\"all\")) {\n return kcItemData.get(id);\n } else {\n String[] requestList = list.split(\",\");\n for (int i = 0; i < requestList.length; i++) {\n String orig_api_item = requestList[i];\n String api_item = orig_api_item;\n if (!api_item.startsWith(\"api_\")) {\n api_item = \"api_\" + api_item;\n }\n temp.add(orig_api_item, kcItemData.get(id).get(api_item));\n }\n return temp.getAsJsonObject();\n }\n } else {\n return null;\n }\n\n}", "public static JsonObject getKcShipDataById(int id, String list) {\n if (kcGameData == null) return null;\n JsonObject temp = new JsonObject();\n if (kcShipData.containsKey(id)) {\n if (list.equals(\"all\")) {\n return kcShipData.get(id);\n } else {\n String[] requestList = list.split(\",\");\n for (int i = 0; i < requestList.length; i++) {\n String orig_api_item = requestList[i];\n String api_item = orig_api_item;\n if (!api_item.startsWith(\"api_\")) {\n api_item = \"api_\" + api_item;\n }\n temp.add(orig_api_item, kcShipData.get(id).get(api_item));\n }\n return temp;\n }\n } else {\n Log.e(\"KCA\", String.valueOf(id) + \" not in list\");\n return null;\n }\n}", "public static String getShipTranslation(String jp_name, boolean abbr) {\n if (currentLocaleCode.equals(\"jp\")) {\n return jp_name;\n }\n\n String name = jp_name;\n String name_suffix = \"\";\n if (!kcShipTranslationData.has(\"suffixes\")) {\n return jp_name;\n }\n\n JsonObject suffixes = kcShipTranslationData.getAsJsonObject(\"suffixes\");\n for (Map.Entry<String, JsonElement> entry : suffixes.entrySet()) {\n if (jp_name.endsWith(entry.getKey())) {\n name = name.replaceAll(entry.getKey(), \"\");\n name_suffix = entry.getValue().getAsString();\n break;\n }\n }\n\n if (kcShipTranslationData.has(name)) {\n name = kcShipTranslationData.get(name).getAsString();\n }\n\n if (abbr) {\n for (Map.Entry<String, JsonElement> entry : kcShipAbbrData.entrySet()) {\n if (name.startsWith(entry.getKey())) {\n name = name.replaceAll(entry.getKey(), entry.getValue().getAsString());\n break;\n }\n }\n }\n\n return name.concat(name_suffix);\n}", "public static int[] removeKai(JsonArray slist, boolean exception) {\n List<Integer> afterShipList = new ArrayList<Integer>();\n List filteredShipList = new ArrayList<>();\n for (int i = 0; i < slist.size(); i++) {\n int sid = slist.get(i).getAsInt();\n for (int lv = 1; lv <= 3; lv++) {\n int after = findAfterShipId(sid, lv);\n if (after == 0 || after != sid) {\n afterShipList.add(after);\n } else {\n break;\n }\n }\n }\n for (int i = 0; i < slist.size(); i++) {\n int sid = slist.get(i).getAsInt();\n if (exception || afterShipList.indexOf(sid) == -1) {\n filteredShipList.add(sid);\n }\n }\n int[] result = new int[filteredShipList.size()];\n for (int i = 0; i < result.length; i++) {\n result[i] = (int) filteredShipList.get(i);\n }\n return result;\n}", "public static int getId(String resourceName, Class<?> c) {\n try {\n Field idField = c.getDeclaredField(resourceName);\n return idField.getInt(idField);\n } catch (Exception e) {\n throw new RuntimeException(\"No resource ID found for: \"\n + resourceName + \" / \" + c, e);\n }\n}", "public static String joinStr(List<String> list, String delim) {\n String resultStr = \"\";\n if (list.size() > 0) {\n int i;\n for (i = 0; i < list.size() - 1; i++) {\n resultStr = resultStr.concat(list.get(i));\n resultStr = resultStr.concat(delim);\n }\n resultStr = resultStr.concat(list.get(i));\n }\n return resultStr;\n}" ]
import android.widget.Toast; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import java.util.ArrayList; import java.util.List; import static com.antest1.kcanotify.KcaApiData.getItemTranslation; import static com.antest1.kcanotify.KcaApiData.getKcItemStatusById; import static com.antest1.kcanotify.KcaApiData.getKcShipDataById; import static com.antest1.kcanotify.KcaApiData.getShipTranslation; import static com.antest1.kcanotify.KcaApiData.removeKai; import static com.antest1.kcanotify.KcaUtils.getId; import static com.antest1.kcanotify.KcaUtils.joinStr;
package com.antest1.kcanotify; public class KcaAkashiListViewItem { private int equipId; private JsonObject equipImprovementData; private int equipIconMipmap; private String equipName = ""; private String equipSupport = ""; private String equipMaterials = ""; private String equipScrews = ""; public int getEquipId() { return equipId; } public JsonObject getEquipImprovementData() { return equipImprovementData; } public int getEquipIconMipmap() { return equipIconMipmap; } public String getEquipName() { return equipName; } public String getEquipSupport() { return equipSupport; } public String getEquipMaterials() { return equipMaterials; } public String getEquipScrews() { return equipScrews; } public void setEquipDataById(int id) { JsonObject kcItemData = getKcItemStatusById(id, "type,name"); String kcItemName = getItemTranslation(kcItemData.get("name").getAsString()); int type = kcItemData.getAsJsonArray("type").get(3).getAsInt(); int typeres = 0; try { typeres = getId(KcaUtils.format("item_%d", type), R.mipmap.class); } catch (Exception e) { typeres = R.mipmap.item_0; } equipId = id; equipIconMipmap = typeres; equipName = kcItemName; } public void setEquipImprovementData(JsonObject data) { equipImprovementData = data; } // 0: sun ~ 6: sat public void setEquipImprovementElement(int day, boolean checked) { JsonArray data = equipImprovementData.getAsJsonArray("improvement"); boolean convert_exception = equipImprovementData.has("convert_exception"); String[] material1 = new String[4]; String[] material2 = new String[4]; String[] material3 = new String[4]; String[] screw1 = new String[4]; String[] screw2 = new String[4]; String[] screw3 = new String[4]; int count = 0; List<String> screw = new ArrayList<String>(); List<String> material = new ArrayList<String>(); List<String> ship = new ArrayList<String>(); for (int i = 0; i < data.size(); i++) { JsonArray req = data.get(i).getAsJsonObject().getAsJsonArray("req"); List<String> shiplist = new ArrayList<String>(); for (int j = 0; j < req.size(); j++) { JsonArray reqitem = req.get(j).getAsJsonArray(); if (reqitem.size() == 2 && reqitem.get(0).getAsJsonArray().get(day).getAsBoolean()) { JsonElement supportInfo = reqitem.get(1); if (supportInfo.isJsonArray()) { int[] filtered = removeKai(supportInfo.getAsJsonArray(), convert_exception); for(int k = 0; k < filtered.length; k++) { JsonObject kcShipData = getKcShipDataById(filtered[k], "name"); shiplist.add(getShipTranslation(kcShipData.get("name").getAsString(), false)); } } else { shiplist.add("-"); } } } if (shiplist.size() > 0) {
ship.add(joinStr(shiplist,"/"));
6
simo415/spc
src/com/sijobe/spc/worldedit/LocalPlayer.java
[ "public interface ICUIEventHandler extends IHook {\n\n /**\n * Handles a CUI Event\n * \n * @param type - the type of CUI Event\n * @param type - the parameters of the CUI Event\n */\n public void handleCUIEvent(String type, String[] params);\n}", "public enum FontColour {\n \n BLACK(\"\\2470\"),\n DARK_BLUE(\"\\2471\"),\n DARK_GREEN(\"\\2472\"),\n DARK_AQUA(\"\\2473\"),\n DARK_RED(\"\\2474\"),\n PURPLE(\"\\2475\"),\n ORANGE(\"\\2476\"),\n GREY(\"\\2477\"),\n DARK_GREY(\"\\2478\"),\n BLUE(\"\\2479\"),\n GREEN(\"\\247a\"),\n AQUA(\"\\247b\"),\n RED(\"\\247c\"),\n PINK(\"\\247d\"),\n YELLOW(\"\\247e\"),\n WHITE(\"\\247f\"),\n // Special case - random\n RANDOM(\"\\247k\");\n \n /**\n * Holds the random variables\n */\n private Random random;\n \n /**\n * The value of the enum\n */\n private final String value;\n \n /**\n * Initialises the enum using the specified value\n * \n * @param value - The value of the FontColour\n */\n private FontColour(String value) {\n this.value = value;\n random = new Random();\n }\n \n /**\n * Overrides the default toString method to return the value of the Enum\n * \n * @see java.lang.Enum#toString()\n */\n @Override\n public String toString() {\n if (value.equalsIgnoreCase(\"\\247k\")) {\n return values()[random.nextInt(values().length - 1)].toString();\n }\n return value;\n }\n}", "public class WorldEditCUIHelper {\n\n private static final HookManager HOOK_MANAGER = new HookManager();\n private static boolean hooksLoaded = false;\n \n private static final Class<?> wecuiClass;\n private static final Class<?> cuiEventClass;\n private static final Class<?> eventManagerClass;\n private static final Constructor<?> cuiEventConstructor;\n private static final Method callEventMethod;\n private static final Method getEventManagerMethod;\n \n /**\n * Gets the mod's WorldEditCUI instance and handles the event\n * \n * @param mod - instance of the WorldEditCUI Mod\n * @param type - type of CUI event\n * @param params - parameters of the event\n */\n public static void handleCUIEvent(Object mod, String type, String[] params) throws Throwable {\n Field modController = mod.getClass().getDeclaredField(\"controller\");\n modController.setAccessible(true);\n Object controller = modController.get(mod);\n Object eventManager = getEventManagerMethod.invoke(controller);\n Object event = cuiEventConstructor.newInstance(controller, type, params);\n callEventMethod.invoke(eventManager, event);\n }\n\n /**\n * Gets a list of CUI event handlers, load hooks if neccessary\n * \n * @return list of CUI event handler hooks\n */\n public static List<ICUIEventHandler> getCUIHooks() {\n if(!hooksLoaded) {\n HOOK_MANAGER.loadHooks(ICUIEventHandler.class);\n hooksLoaded = true;\n }\n return HOOK_MANAGER.getHooks(ICUIEventHandler.class);\n }\n \n static {\n wecuiClass = ReflectionHelper.getClass(\"wecui.WorldEditCUI\");\n if(wecuiClass != null) {\n getEventManagerMethod = ReflectionHelper.getMethod(wecuiClass, \"getEventManager\");\n cuiEventClass = ReflectionHelper.getClass(\"wecui.event.CUIEvent\");\n final Class<?>[] constructorArgs = new Class<?>[]{wecuiClass, String.class, String[].class};\n cuiEventConstructor = ReflectionHelper.getConstructor(cuiEventClass, constructorArgs);\n eventManagerClass = ReflectionHelper.getClass(\"wecui.fevents.EventManager\");\n callEventMethod = ReflectionHelper.getPublicMethodWithParamsLength(eventManagerClass, \"callEvent\", 1);\n } else {\n getEventManagerMethod = null;\n cuiEventClass = null;\n cuiEventConstructor = null;\n eventManagerClass = null;\n callEventMethod = null;\n }\n }\n \n}", "public class Coordinate {\n \n private final double x;\n private final double y;\n private final double z;\n \n /**\n * Initialises the class using double values\n * \n * @param x - The X coordinate\n * @param y - The Y coordinate\n * @param z - The Z coordinate\n */\n public Coordinate(double x, double y, double z) {\n this.x = x;\n this.y = y;\n this.z = z;\n }\n \n /**\n * Initialises the class using integer values\n * \n * @param x - The X coordinate\n * @param y - The Y coordinate\n * @param z - The Z coordinate\n */\n public Coordinate(int x, int y, int z) {\n this.x = x;\n this.y = y;\n this.z = z;\n }\n \n /**\n * Gets the X coordinate\n * \n * @return The X coordinate\n */\n public double getX() {\n return x;\n }\n \n /**\n * Gets the X coordinate rounded to the closest block\n * \n * @return The X coordinate\n */\n public int getBlockX() {\n int x = (int)getX();\n return getX() < (double)x ? x - 1 : x;\n }\n \n /**\n * Gets the Y coordinate\n * \n * @return The Y coordinate\n */\n public double getY() {\n return y;\n }\n \n /**\n * Gets the Y coordinate rounded to the closest block\n * \n * @return The Y coordinate\n */\n public int getBlockY() {\n return (int)getY();\n }\n \n /**\n * Gets the Z coordinate\n * \n * @return The Z coordinate\n */\n public double getZ() {\n return z;\n }\n \n /**\n * Gets the Z coordinate rounded to the closest block\n * \n * @return The Z coordinate\n */\n public int getBlockZ() {\n int z = (int)getZ();\n return getZ() < (double)z ? z - 1 : z;\n }\n \n /**\n * Gets the distance between two coordinates\n * \n * @param compare - The coordinate to compare\n * @return The distance between the coordinates\n */\n public double getDistanceBetweenCoordinates(Coordinate compare) {\n double diffX = getX() - compare.getX();\n double diffY = getY() - compare.getY();\n double diffZ = getZ() - compare.getZ();\n return Math.sqrt((diffX * diffX) + (diffY * diffY) + (diffZ * diffZ));\n }\n \n /**\n * Checks if this coordinate matches the provided object by comparing the \n * double X, Y, Z fields. If they match true is returned\n * \n * @see java.lang.Object#equals(java.lang.Object)\n */\n @Override\n public boolean equals(Object obj) {\n if (obj != null && obj instanceof Coordinate) {\n Coordinate compare = (Coordinate)obj;\n return compare.getX() == getX() && compare.getY() == getY() && compare.getZ() == getZ();\n }\n return false;\n }\n \n /**\n * Converts the Coordinate to a String value\n * \n * @see java.lang.Object#toString()\n */\n @Override\n public String toString() {\n return x + \",\" + y + \",\" + z;\n }\n}", "public class Player {\n\n /**\n * The object that the instance is wrapped around\n */\n private final EntityPlayer player;\n\n public Player(EntityPlayer player) {\n this.player = player;\n }\n\n /**\n * Sets the player position and if on server sends the update to the client\n * \n * @param c - The coordinate that the player is being moved to\n */\n public void setPosition(Coordinate c) {\n if (player instanceof EntityPlayerMP) {\n ((EntityPlayerMP) player).setPositionAndUpdate(c.getX(), c.getY(), c.getZ());\n } else {\n player.setPosition(c.getX(), c.getY(), c.getZ());\n }\n }\n\n /**\n * Gets the current position that the player is currently standing\n * \n * @return The position that the player is standing\n */\n public Coordinate getPosition() {\n return new Coordinate(player.posX, player.posY, player.posZ);\n }\n\n /**\n * Gets the player rotation yaw\n * \n * @return Rotation Yaw\n */\n public float getYaw() {\n return player.rotationYaw;\n }\n\n /**\n * Sets the rotation yaw of the player\n * \n * @param yaw - The yaw value to set to the player\n */\n public void setYaw(float yaw) {\n player.rotationYaw = yaw;\n }\n\n /**\n * Gets the player rotation pitch\n * \n * @return Rotation pitch\n */\n public float getPitch() {\n return player.rotationPitch;\n }\n\n /**\n * Sets the rotation pitch of the player\n * \n * @param pitch - The pitch value to set to the player\n */\n public void setPitch(float pitch) {\n player.rotationPitch = pitch;\n }\n\n /**\n * Gets the world that the player is currently in\n * \n * @return The world that the player is currently in\n */\n public World getWorld() {\n if (player instanceof EntityPlayerMP) {\n return new World(((EntityPlayerMP) player).theItemInWorldManager.theWorld); // why?\n } else {\n return new World(player.worldObj);\n }\n }\n\n /**\n * Sends a chat message to the user\n * \n * @param message - The message to send to the user\n */\n public void sendChatMessage(String message) {\n player.addChatMessage(message);\n }\n\n /**\n * Gives the player a maximum stack of the specified item\n * \n * @param id - The item id\n */\n public void givePlayerItem(int id) {\n givePlayerItem(id, Item.getMaxStack(id));\n }\n\n /**\n * Gives the player a maximum stack of the specified item\n * \n * @param id - The item id\n * @param quantity - The quantity of the item\n */\n public void givePlayerItem(int id, int quantity) {\n givePlayerItem(id, quantity, 0);\n }\n\n /**\n * Gives the player a maximum stack of the specified item\n * \n * @param id - The item id\n * @param quantity - The quantity of the item\n * @param damage - The \"damage\" (metadata) value of the item\n */\n public void givePlayerItem(int id, int quantity, int damage) {\n ItemStack itemStack = new ItemStack(id, quantity, damage);\n if (!player.inventory.addItemStackToInventory(itemStack)) {\n player.dropPlayerItem(itemStack);\n }\n }\n\n /**\n * Gets the players current health\n * \n * @return The value of the players health\n */\n public float getHealth() {\n return player.func_110143_aJ();\n }\n\n /**\n * Sets the players health to the specified value\n * \n * @param health - The health amount\n */\n public void setHealth(float health) {\n player.setEntityHealth(health);\n }\n\n /**\n * Heals the player the specified quantity. Use a negative number to remove\n * the specified amount from the player.\n * \n * @param quantity - The ammount to heal the player\n */\n public void heal(float quantity) {\n setHealth(getHealth() + quantity);\n }\n\n /**\n * Gets the players current hunger level\n * \n * @return The hunger level\n */\n public int getHunger() {\n return player.getFoodStats().getFoodLevel();\n }\n\n /**\n * Sets the players hunger level\n * \n * @param food - The hunger level to set to\n */\n public void setHunger(int food) {\n player.getFoodStats().setFoodLevel(food);\n }\n\n /**\n * Gets the boolean value representing whether player damage is on or off.\n * \n * @return True when damage is on, false when damage is off\n */\n public boolean getDamage() {\n return !player.capabilities.disableDamage;\n }\n\n /**\n * Sets whether player damage is on or off\n * \n * @param damage - when true it turns player damage on, false turns it off\n */\n public void setDamage(boolean damage) {\n player.capabilities.disableDamage = !damage;\n }\n\n /**\n * Sets the item contained within the specified inventory slot\n * \n * @param slot - The slot to set\n * @param id - The item id\n * @param quantity - The item quantity\n * @param damage - The item \"damage\" value\n * @return True if the slot was correctly set, false otherwise\n */\n public boolean setInventorySlot(int slot, int id, int quantity, int damage) {\n if (slot < 0 || slot >= player.inventory.mainInventory.length) {\n return false;\n } else if (!Item.isValidItem(id)) {\n if (id == 0) {\n player.inventory.mainInventory[slot] = null;\n return true;\n }\n return false;\n }\n player.inventory.mainInventory[slot] = new ItemStack(id, quantity, damage);\n return true;\n }\n\n /**\n * Performs a trace on the players view to the specified maximum distance.\n * The trace returns the coordinate where it hits a block or null if nothing\n * was found.\n * \n * @param distance - The maximum distance to check\n * @return A coordinate object containing the block that was inline with\n * the players view\n */\n public Coordinate trace(double distance) {\n MovingObjectPosition m = rayTrace(distance, 1.0F);\n if (m == null) {\n return null;\n }\n return new Coordinate(m.blockX, m.blockY, m.blockZ);\n }\n\n public MovingObjectPosition rayTrace(double distance, float partialTickTime) {\n Vec3 positionVec = getPositionVec(partialTickTime);\n Vec3 lookVec = player.getLook(partialTickTime);\n Vec3 hitVec = positionVec.addVector(lookVec.xCoord * distance, lookVec.yCoord * distance, lookVec.zCoord * distance);\n return player.worldObj.rayTraceBlocks_do_do(positionVec, hitVec, false, true); // TODO: Validate correct params\n }\n\n /**\n * interpolated position vector\n */\n public Vec3 getPositionVec(float partialTickTime) {\n double offsetY = player.posY + player.getEyeHeight();\n if (partialTickTime == 1.0F) {\n return getWorld().getMinecraftWorld().getWorldVec3Pool().getVecFromPool(player.posX, offsetY, player.posZ);\n } else {\n double var2 = player.prevPosX + (player.posX - player.prevPosX) * partialTickTime;\n double var4 = player.prevPosY + (offsetY - (player.prevPosY + player.getEyeHeight())) * partialTickTime;\n double var6 = player.prevPosZ + (player.posZ - player.prevPosZ) * partialTickTime;\n return getWorld().getMinecraftWorld().getWorldVec3Pool().getVecFromPool(var2, var4, var6);\n }\n }\n\n /*public String getGameType() { // TODO\n }*/\n\n /**\n * Sets the gametype that the player uses\n * \n * @param gametype - The player game type\n * @return True if the specified gametype was found\n */\n public boolean setGameType(String gametype) {\n EnumGameType chosen = null;\n if ((chosen = EnumGameType.getByName(gametype)) == null) {\n return false;\n }\n player.setGameType(chosen);\n return true;\n }\n\n /**\n * Gets the players name\n * \n * @return The players name\n */\n public String getPlayerName() {\n return player.getEntityName();\n }\n\n /**\n * Gets the item ID of the current held item\n * \n * @return The ID of the currently held item\n */\n public int getCurrentItem() {\n try {\n return player.inventory.mainInventory[getCurrentSlot()].itemID;\n } catch (NullPointerException e) {\n return 0;\n }\n }\n\n /**\n * Gets the slot number of the current item\n * \n * @return A value 0-8 based on the slot currently selected\n */\n public int getCurrentSlot() {\n return player.inventory.currentItem;\n }\n\n /**\n * Sets the URL that the skin is retrieved from\n * \n * @param URL - The URL the skin is taken from\n */\n public void setSkin(String URL) {\n //TODO: Set username? AbstractClientPlayer - player.skinUrl = URL;\n }\n\n /**\n * Sets the player's current motion\n * \n * @param motion - The motion to set to the player\n */\n public void setMotion(Coordinate motion) {\n player.motionX = motion.getX();\n player.motionY = motion.getY();\n player.motionZ = motion.getZ();\n }\n\n /**\n * Gets the player's current motion\n * \n * @return The motion of the player\n */\n public Coordinate getMotion() {\n return new Coordinate(player.motionX, player.motionY, player.motionZ);\n }\n\n /**\n * Checks if the specified position is able to contain a player. This\n * involves two squares at the player's height that are empty and one block\n * beneath the player's feet.\n * \n * @param player - The player object\n * @param x - The X coordinate\n * @param y - The Y coordinate\n * @param z - The Z coordinate\n * @return True if the player can stand in the specified location\n */\n public boolean isClear(Coordinate location) {\n return getWorld().getBlockId(location.getBlockX(), location.getBlockY(), location.getBlockZ()) == 0\n && getWorld().getBlockId(location.getBlockX(), location.getBlockY() + 1, location.getBlockZ()) == 0\n && !(getWorld().getBlockId(location.getBlockX(), location.getBlockY() - 1, location.getBlockZ()) == 0);\n }\n\n /**\n * Checks if the specified position is able to contain a player. This\n * involves two squares at the player's height that are empty and one block\n * below the player being empty.\n * \n * @param player - The player object\n * @param x - The X coordinate\n * @param y - The Y coordinate\n * @param z - The Z coordinate\n * @return True if the player can fall in the specified location\n */\n public boolean isClearBelow(Coordinate location) {\n return getWorld().getBlockId(location.getBlockX(), location.getBlockY(), location.getBlockZ()) == 0\n && getWorld().getBlockId(location.getBlockX(), location.getBlockY() + 1, location.getBlockZ()) == 0\n && getWorld().getBlockId(location.getBlockX(), location.getBlockY() - 1, location.getBlockZ()) == 0;\n }\n \n /**\n * Gets the movement forward. This is a value between -1 and 1. -1 is when\n * the player is moving backward, 1 is that player moving forward. The value\n * of the float is the percentage of speed the player is moving.\n * \n * @return The movement forward percentage\n */\n public float getMovementForward() {\n if (player instanceof EntityPlayerMP) {\n return ((EntityPlayerMP) player).getMoveForwardField();\n } else if (player instanceof EntityClientPlayerMP) {\n return ((EntityClientPlayerMP) player).getMovementForward();\n } else {\n return 0F;\n }\n }\n\n /**\n * Gets the movement strafe. This is a value between -1 and 1. -1 is when\n * the player is moving right, 1 is that player moving left. The value\n * of the float is the percentage of speed the player is moving.\n * \n * @return The movement strafe percentage\n */\n public float getMovementStrafe() {\n if (player instanceof EntityPlayerMP) {\n return ((EntityPlayerMP) player).getMoveStrafingField();\n } else if (player instanceof EntityClientPlayerMP) {\n return ((EntityClientPlayerMP) player).getMovementStrafe();\n } else {\n return 0F;\n }\n }\n\n /**\n * Sets the player's step height.\n * \n * @param height - The height of the player's step\n */\n public void setStepHeight(float height) {\n player.stepHeight = height;\n }\n\n /**\n * Gets the step height of the player\n * \n * @return Height (in blocks) of the player step height\n */\n public float getStepHeight() {\n return player.stepHeight;\n }\n\n /**\n * Gets the internal Minecraft player object\n * \n * @return The Minecraft player object\n */\n public EntityPlayer getMinecraftPlayer() {\n return player;\n }\n\n /**\n * Removes the specified potion from the player\n * \n * @param potion - The potion ID to remove\n */\n public void removePotionEffect(int potion) {\n player.removePotionEffect(potion);\n }\n\n /**\n * Removes all potion effects\n */\n public void removeAllPotionEffects() {\n player.clearActivePotions();\n }\n\n /**\n * Adds a potion effect to the player\n * \n * @param id - The ID of the potion\n * @param duration - The duration the potion should run for\n * @param strength - The strength of effect to add\n */\n public void addPotionEffect(int id, int duration, int strength) {\n player.addPotionEffect(new PotionEffect(id, duration, strength));\n }\n\n /**\n * Changes the dimension that the player is in\n * \n * @param dimension - The dimension to move the player to\n */\n public void changeDimension(int dimension) {\n player.travelToDimension(dimension);\n }\n\n /**\n * Sets the quantity of air that the player has\n * \n * @param air - The quantity of air that the player has\n */\n public void setAir(int air) {\n player.setAir(air);\n }\n\n /**\n * Gives the specified achievement to the player. Note that this will only\n * work in client mode, server cannot give achievements to the player.\n * \n * @param name - The name of the achievement\n * @return If the achievement was able to be added to the player\n */\n public boolean addAchievement(String name) {\n if (player instanceof EntityClientPlayerMP) {\n if (Stats.doesAchievementExist(name)) {\n player.triggerAchievement(Stats.getAchievementByName(name));\n return true;\n }\n }\n return false;\n }\n\n /**\n * Returns true if flying is permitted for the user, false otherwise\n * \n * @return True if flying is permitted\n */\n public boolean getAllowFlying() {\n return player.capabilities.allowFlying;\n }\n\n /**\n * Allows and disables Minecraft flying mode\n * \n * @param allow - True to allow flying, false to disable it\n */\n public void setAllowFlying(boolean allow) {\n player.capabilities.allowFlying = allow;\n player.capabilities.isFlying = allow;\n player.sendPlayerAbilities();\n }\n\n /**\n * Returns true if the player is currently in creative mode, false if in\n * survival or adventure mode.\n * \n * @return True is in creative mode, false otherwise.\n */\n public boolean isCreativeMode() {\n return player.capabilities.isCreativeMode;\n }\n \n /**\n * Gets the players username\n * \n * @return The players username\n */\n public String getUsername() {\n if (player instanceof EntityClientPlayerMP) {\n return ((EntityClientPlayerMP) player).getUsername();\n } else if (player instanceof EntityPlayerMP) {\n ((EntityPlayerMP) player).getUsername();\n }\n return \"\";\n }\n}" ]
import com.sijobe.spc.core.ICUIEventHandler; import com.sijobe.spc.util.FontColour; import com.sijobe.spc.util.WorldEditCUIHelper; import com.sijobe.spc.wrapper.Coordinate; import com.sijobe.spc.wrapper.Player; import com.sk89q.worldedit.ServerInterface; import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldVector; import com.sk89q.worldedit.bags.BlockBag; import com.sk89q.worldedit.cui.CUIEvent;
package com.sijobe.spc.worldedit; public class LocalPlayer extends com.sk89q.worldedit.LocalPlayer { private Player player; protected LocalPlayer(Player player, ServerInterface server) { super(server); this.player = player; } @Override public String[] getGroups() { // TODO Auto-generated method stub return null; } @Override public BlockBag getInventoryBlockBag() { // TODO Auto-generated method stub return null; } @Override public int getItemInHand() { return player.getCurrentItem(); } @Override public String getName() { return player.getPlayerName(); } @Override public double getPitch() { return player.getPitch(); } @Override public WorldVector getPosition() { Coordinate c = player.getPosition(); return new WorldVector(getWorld(), c.getX(), c.getY(), c.getZ()); } @Override public com.sk89q.worldedit.LocalWorld getWorld() { return new LocalWorld(player.getWorld()); } @Override public double getYaw() { return player.getYaw(); } @Override public void giveItem(int type, int quantity) { player.givePlayerItem(type, quantity); } @Override public boolean hasPermission(String arg0) { // TODO Check permissions return true; } @Override public void print(String message) { player.sendChatMessage(message); } @Override public void printDebug(String message) { System.out.println("WORLDEDIT-DEBUG: " + message); } @Override public void printError(String message) {
player.sendChatMessage(FontColour.RED + message);
1
dkzwm/SmoothRefreshLayout
app/src/main/java/me/dkzwm/widget/srl/sample/ui/TestQQActivityStyleActivity.java
[ "public abstract class RefreshingListenerAdapter implements SmoothRefreshLayout.OnRefreshListener {\n @Override\n public void onRefreshing() {}\n\n @Override\n public void onLoadingMore() {}\n}", "public class SmoothRefreshLayout extends ViewGroup\n implements NestedScrollingParent3, NestedScrollingChild3 {\n // status\n public static final byte SR_STATUS_INIT = 1;\n public static final byte SR_STATUS_PREPARE = 2;\n public static final byte SR_STATUS_REFRESHING = 3;\n public static final byte SR_STATUS_LOADING_MORE = 4;\n public static final byte SR_STATUS_COMPLETE = 5;\n // fresh view status\n public static final byte SR_VIEW_STATUS_INIT = 21;\n public static final byte SR_VIEW_STATUS_HEADER_IN_PROCESSING = 22;\n public static final byte SR_VIEW_STATUS_FOOTER_IN_PROCESSING = 23;\n\n protected static final Interpolator SPRING_INTERPOLATOR =\n new Interpolator() {\n public float getInterpolation(float input) {\n --input;\n return input * input * input * input * input + 1.0F;\n }\n };\n protected static final Interpolator FLING_INTERPOLATOR = new DecelerateInterpolator(.95f);\n protected static final Interpolator SPRING_BACK_INTERPOLATOR = new DecelerateInterpolator(1.6f);\n protected static final int FLAG_AUTO_REFRESH = 0x01;\n protected static final int FLAG_ENABLE_OVER_SCROLL = 0x01 << 2;\n protected static final int FLAG_ENABLE_KEEP_REFRESH_VIEW = 0x01 << 3;\n protected static final int FLAG_ENABLE_PIN_CONTENT_VIEW = 0x01 << 4;\n protected static final int FLAG_ENABLE_PULL_TO_REFRESH = 0x01 << 5;\n protected static final int FLAG_ENABLE_PIN_REFRESH_VIEW_WHILE_LOADING = 0x01 << 6;\n protected static final int FLAG_ENABLE_HEADER_DRAWER_STYLE = 0x01 << 7;\n protected static final int FLAG_ENABLE_FOOTER_DRAWER_STYLE = 0x01 << 8;\n protected static final int FLAG_DISABLE_PERFORM_LOAD_MORE = 0x01 << 9;\n protected static final int FLAG_ENABLE_NO_MORE_DATA = 0x01 << 10;\n protected static final int FLAG_DISABLE_LOAD_MORE = 0x01 << 11;\n protected static final int FLAG_DISABLE_PERFORM_REFRESH = 0x01 << 12;\n protected static final int FLAG_DISABLE_REFRESH = 0x01 << 13;\n protected static final int FLAG_ENABLE_AUTO_PERFORM_LOAD_MORE = 0x01 << 14;\n protected static final int FLAG_ENABLE_AUTO_PERFORM_REFRESH = 0x01 << 15;\n protected static final int FLAG_ENABLE_INTERCEPT_EVENT_WHILE_LOADING = 0x01 << 16;\n protected static final int FLAG_DISABLE_WHEN_ANOTHER_DIRECTION_MOVE = 0x01 << 17;\n protected static final int FLAG_ENABLE_NO_MORE_DATA_NO_BACK = 0x01 << 18;\n protected static final int FLAG_DISABLE_LOAD_MORE_WHEN_CONTENT_NOT_FULL = 0x01 << 19;\n protected static final int FLAG_ENABLE_COMPAT_SYNC_SCROLL = 0x01 << 20;\n protected static final int FLAG_ENABLE_PERFORM_FRESH_WHEN_FLING = 0x01 << 21;\n protected static final int FLAG_ENABLE_OLD_TOUCH_HANDLING = 0x01 << 22;\n protected static final int FLAG_BEEN_SET_NO_MORE_DATA = 0x01 << 23;\n protected static final int MASK_DISABLE_PERFORM_LOAD_MORE = 0x07 << 9;\n protected static final int MASK_DISABLE_PERFORM_REFRESH = 0x03 << 12;\n public static boolean sDebug = false;\n private static int sId = 0;\n private static IRefreshViewCreator sCreator;\n protected final String TAG = \"SmoothRefreshLayout-\" + sId++;\n protected final int[] mParentScrollConsumed = new int[2];\n protected final int[] mParentOffsetInWindow = new int[2];\n private final List<View> mCachedViews = new ArrayList<>();\n protected IRefreshView<IIndicator> mHeaderView;\n protected IRefreshView<IIndicator> mFooterView;\n protected IIndicator mIndicator;\n protected IIndicatorSetter mIndicatorSetter;\n protected OnRefreshListener mRefreshListener;\n protected boolean mAutomaticActionUseSmoothScroll = false;\n protected boolean mAutomaticActionTriggered = true;\n protected boolean mIsSpringBackCanNotBeInterrupted = false;\n protected boolean mDealAnotherDirectionMove = false;\n protected boolean mPreventForAnotherDirection = false;\n protected boolean mIsInterceptTouchEventInOnceTouch = false;\n protected boolean mIsLastOverScrollCanNotAbort = false;\n protected boolean mNestedScrolling = false;\n protected boolean mNestedTouchScrolling = false;\n protected byte mStatus = SR_STATUS_INIT;\n protected byte mViewStatus = SR_VIEW_STATUS_INIT;\n protected long mLoadingStartTime = 0;\n protected int mAutomaticAction = Constants.ACTION_NOTIFY;\n protected int mLastNestedType = ViewCompat.TYPE_NON_TOUCH;\n protected int mDurationToCloseHeader = 350;\n protected int mDurationToCloseFooter = 350;\n protected int mDurationOfBackToHeaderHeight = 200;\n protected int mDurationOfBackToFooterHeight = 200;\n protected int mDurationOfFlingBack = 550;\n protected int mContentResId = View.NO_ID;\n protected int mStickyHeaderResId = View.NO_ID;\n protected int mStickyFooterResId = View.NO_ID;\n protected int mTouchSlop;\n protected int mTouchPointerId;\n protected int mMinimumFlingVelocity;\n protected int mMaximumFlingVelocity;\n protected View mTargetView;\n protected View mScrollTargetView;\n protected View mAutoFoundScrollTargetView;\n protected View mStickyHeaderView;\n protected View mStickyFooterView;\n protected LayoutManager mLayoutManager;\n protected ScrollChecker mScrollChecker;\n protected VelocityTracker mVelocityTracker;\n protected MotionEvent mLastMoveEvent;\n protected OnHeaderEdgeDetectCallBack mInEdgeCanMoveHeaderCallBack;\n protected OnFooterEdgeDetectCallBack mInEdgeCanMoveFooterCallBack;\n protected OnSyncScrollCallback mSyncScrollCallback;\n protected OnPerformAutoLoadMoreCallBack mAutoLoadMoreCallBack;\n protected OnPerformAutoRefreshCallBack mAutoRefreshCallBack;\n protected OnCalculateBounceCallback mCalculateBounceCallback;\n protected int mFlag =\n FLAG_DISABLE_LOAD_MORE\n | FLAG_ENABLE_KEEP_REFRESH_VIEW\n | FLAG_ENABLE_COMPAT_SYNC_SCROLL\n | FLAG_ENABLE_OLD_TOUCH_HANDLING\n | FLAG_ENABLE_PERFORM_FRESH_WHEN_FLING;\n private NestedScrollingParentHelper mNestedScrollingParentHelper =\n new NestedScrollingParentHelper(this);\n private NestedScrollingChildHelper mNestedScrollingChildHelper;\n private Interpolator mSpringInterpolator;\n private Interpolator mSpringBackInterpolator;\n private ArrayList<OnUIPositionChangedListener> mUIPositionChangedListeners;\n private ArrayList<OnStatusChangedListener> mStatusChangedListeners;\n private ArrayList<ILifecycleObserver> mLifecycleObservers;\n private DelayToDispatchNestedFling mDelayToDispatchNestedFling;\n private DelayToRefreshComplete mDelayToRefreshComplete;\n private DelayToPerformAutoRefresh mDelayToPerformAutoRefresh;\n private RefreshCompleteHook mHeaderRefreshCompleteHook;\n private RefreshCompleteHook mFooterRefreshCompleteHook;\n private AppBarLayoutUtil mAppBarLayoutUtil;\n private Matrix mCachedMatrix = new Matrix();\n private boolean mIsLastRefreshSuccessful = true;\n private boolean mViewsZAxisNeedReset = true;\n private boolean mNeedFilterScrollEvent = false;\n private boolean mHasSendCancelEvent = false;\n private boolean mHasSendDownEvent = false;\n private boolean mLastEventIsActionDown = false;\n private float[] mCachedFloatPoint = new float[2];\n private int[] mCachedIntPoint = new int[2];\n private float mOffsetConsumed = 0f;\n private float mOffsetTotal = 0f;\n private int mMaxOverScrollDuration = 350;\n private int mMinOverScrollDuration = 100;\n private int mOffsetRemaining = 0;\n\n public SmoothRefreshLayout(Context context) {\n super(context);\n init(context, null, 0, 0);\n }\n\n public SmoothRefreshLayout(Context context, AttributeSet attrs) {\n super(context, attrs);\n init(context, attrs, 0, 0);\n }\n\n public SmoothRefreshLayout(Context context, AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n init(context, attrs, defStyleAttr, 0);\n }\n\n /**\n * Set the static refresh view creator, if the refresh view is null and the frame be needed the\n * refresh view,frame will use this creator to create refresh view.\n *\n * <p>设置默认的刷新视图构造器,当刷新视图为null且需要使用刷新视图时,Frame会使用该构造器构造刷新视图\n *\n * @param creator The static refresh view creator\n */\n public static void setDefaultCreator(IRefreshViewCreator creator) {\n sCreator = creator;\n }\n\n @CallSuper\n protected void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {\n sId++;\n createIndicator();\n if (mIndicator == null || mIndicatorSetter == null) {\n throw new IllegalArgumentException(\n \"You must create a IIndicator, current indicator is null\");\n }\n ViewConfiguration viewConfiguration = ViewConfiguration.get(getContext());\n mTouchSlop = viewConfiguration.getScaledTouchSlop();\n mMaximumFlingVelocity = viewConfiguration.getScaledMaximumFlingVelocity();\n mMinimumFlingVelocity = viewConfiguration.getScaledMinimumFlingVelocity();\n createScrollerChecker();\n mSpringInterpolator = SPRING_INTERPOLATOR;\n mSpringBackInterpolator = SPRING_BACK_INTERPOLATOR;\n mDelayToPerformAutoRefresh = new DelayToPerformAutoRefresh();\n TypedArray arr =\n context.obtainStyledAttributes(\n attrs, R.styleable.SmoothRefreshLayout, defStyleAttr, defStyleRes);\n int mode = Constants.MODE_DEFAULT;\n if (arr != null) {\n try {\n mContentResId =\n arr.getResourceId(\n R.styleable.SmoothRefreshLayout_sr_content, mContentResId);\n float resistance =\n arr.getFloat(\n R.styleable.SmoothRefreshLayout_sr_resistance,\n IIndicator.DEFAULT_RESISTANCE);\n mIndicatorSetter.setResistance(resistance);\n mIndicatorSetter.setResistanceOfHeader(\n arr.getFloat(\n R.styleable.SmoothRefreshLayout_sr_resistanceOfHeader, resistance));\n mIndicatorSetter.setResistanceOfFooter(\n arr.getFloat(\n R.styleable.SmoothRefreshLayout_sr_resistanceOfFooter, resistance));\n mDurationOfBackToHeaderHeight =\n arr.getInt(\n R.styleable.SmoothRefreshLayout_sr_backToKeepDuration,\n mDurationOfBackToHeaderHeight);\n mDurationOfBackToFooterHeight =\n arr.getInt(\n R.styleable.SmoothRefreshLayout_sr_backToKeepDuration,\n mDurationOfBackToFooterHeight);\n mDurationOfBackToHeaderHeight =\n arr.getInt(\n R.styleable.SmoothRefreshLayout_sr_backToKeepHeaderDuration,\n mDurationOfBackToHeaderHeight);\n mDurationOfBackToFooterHeight =\n arr.getInt(\n R.styleable.SmoothRefreshLayout_sr_backToKeepFooterDuration,\n mDurationOfBackToFooterHeight);\n mDurationToCloseHeader =\n arr.getInt(\n R.styleable.SmoothRefreshLayout_sr_closeDuration,\n mDurationToCloseHeader);\n mDurationToCloseFooter =\n arr.getInt(\n R.styleable.SmoothRefreshLayout_sr_closeDuration,\n mDurationToCloseFooter);\n mDurationToCloseHeader =\n arr.getInt(\n R.styleable.SmoothRefreshLayout_sr_closeHeaderDuration,\n mDurationToCloseHeader);\n mDurationToCloseFooter =\n arr.getInt(\n R.styleable.SmoothRefreshLayout_sr_closeFooterDuration,\n mDurationToCloseFooter);\n float ratio =\n arr.getFloat(\n R.styleable.SmoothRefreshLayout_sr_ratioToRefresh,\n IIndicator.DEFAULT_RATIO_TO_REFRESH);\n mIndicatorSetter.setRatioToRefresh(ratio);\n mIndicatorSetter.setRatioOfHeaderToRefresh(\n arr.getFloat(\n R.styleable.SmoothRefreshLayout_sr_ratioOfHeaderToRefresh, ratio));\n mIndicatorSetter.setRatioOfFooterToRefresh(\n arr.getFloat(\n R.styleable.SmoothRefreshLayout_sr_ratioOfFooterToRefresh, ratio));\n ratio =\n arr.getFloat(\n R.styleable.SmoothRefreshLayout_sr_ratioToKeep,\n IIndicator.DEFAULT_RATIO_TO_REFRESH);\n mIndicatorSetter.setRatioToKeepHeader(ratio);\n mIndicatorSetter.setRatioToKeepFooter(ratio);\n mIndicatorSetter.setRatioToKeepHeader(\n arr.getFloat(R.styleable.SmoothRefreshLayout_sr_ratioToKeepHeader, ratio));\n mIndicatorSetter.setRatioToKeepFooter(\n arr.getFloat(R.styleable.SmoothRefreshLayout_sr_ratioToKeepFooter, ratio));\n ratio =\n arr.getFloat(\n R.styleable.SmoothRefreshLayout_sr_maxMoveRatio,\n IIndicator.DEFAULT_MAX_MOVE_RATIO);\n mIndicatorSetter.setMaxMoveRatio(ratio);\n mIndicatorSetter.setMaxMoveRatioOfHeader(\n arr.getFloat(\n R.styleable.SmoothRefreshLayout_sr_maxMoveRatioOfHeader, ratio));\n mIndicatorSetter.setMaxMoveRatioOfFooter(\n arr.getFloat(\n R.styleable.SmoothRefreshLayout_sr_maxMoveRatioOfFooter, ratio));\n mStickyHeaderResId =\n arr.getResourceId(R.styleable.SmoothRefreshLayout_sr_stickyHeader, NO_ID);\n mStickyFooterResId =\n arr.getResourceId(R.styleable.SmoothRefreshLayout_sr_stickyFooter, NO_ID);\n setEnableKeepRefreshView(\n arr.getBoolean(R.styleable.SmoothRefreshLayout_sr_enableKeep, true));\n setEnablePinContentView(\n arr.getBoolean(R.styleable.SmoothRefreshLayout_sr_enablePinContent, false));\n setEnableOverScroll(\n arr.getBoolean(R.styleable.SmoothRefreshLayout_sr_enableOverScroll, true));\n setEnablePullToRefresh(\n arr.getBoolean(\n R.styleable.SmoothRefreshLayout_sr_enablePullToRefresh, false));\n setDisableRefresh(\n !arr.getBoolean(R.styleable.SmoothRefreshLayout_sr_enableRefresh, true));\n setDisableLoadMore(\n !arr.getBoolean(R.styleable.SmoothRefreshLayout_sr_enableLoadMore, false));\n mode = arr.getInt(R.styleable.SmoothRefreshLayout_sr_mode, 0);\n setEnabled(arr.getBoolean(R.styleable.SmoothRefreshLayout_android_enabled, true));\n } finally {\n arr.recycle();\n }\n }\n setMode(mode);\n if (mNestedScrollingChildHelper == null) {\n setNestedScrollingEnabled(true);\n }\n }\n\n protected void createIndicator() {\n DefaultIndicator indicator = new DefaultIndicator();\n mIndicator = indicator;\n mIndicatorSetter = indicator;\n }\n\n protected void createScrollerChecker() {\n mScrollChecker = new ScrollChecker();\n }\n\n public final IIndicator getIndicator() {\n return mIndicator;\n }\n\n @Override\n @SuppressWarnings(\"unchecked\")\n @CallSuper\n public void addView(View child, int index, ViewGroup.LayoutParams params) {\n if (params == null) {\n params = generateDefaultLayoutParams();\n } else {\n params = generateLayoutParams(params);\n }\n if (child instanceof IRefreshView) {\n IRefreshView<IIndicator> view = (IRefreshView<IIndicator>) child;\n switch (view.getType()) {\n case IRefreshView.TYPE_HEADER:\n if (mHeaderView != null)\n throw new IllegalArgumentException(\n \"Unsupported operation, HeaderView only can be add once !!\");\n mHeaderView = view;\n break;\n case IRefreshView.TYPE_FOOTER:\n if (mFooterView != null)\n throw new IllegalArgumentException(\n \"Unsupported operation, FooterView only can be add once !!\");\n mFooterView = view;\n break;\n }\n }\n super.addView(child, index, params);\n }\n\n @Override\n public void setEnabled(boolean enabled) {\n super.setEnabled(enabled);\n if (!enabled) {\n reset();\n }\n }\n\n @Override\n protected void onFinishInflate() {\n super.onFinishInflate();\n checkViewsZAxisNeedReset();\n }\n\n @Override\n protected void onDetachedFromWindow() {\n final List<ILifecycleObserver> observers = mLifecycleObservers;\n if (observers != null) {\n for (ILifecycleObserver observer : observers) {\n observer.onDetached(this);\n }\n }\n if (mAppBarLayoutUtil != null) {\n if (mInEdgeCanMoveHeaderCallBack == mAppBarLayoutUtil) {\n mInEdgeCanMoveHeaderCallBack = null;\n }\n if (mInEdgeCanMoveFooterCallBack == mAppBarLayoutUtil) {\n mInEdgeCanMoveFooterCallBack = null;\n }\n mAppBarLayoutUtil.detach();\n }\n mAppBarLayoutUtil = null;\n reset();\n if (mHeaderRefreshCompleteHook != null) {\n mHeaderRefreshCompleteHook.mLayout = null;\n }\n if (mFooterRefreshCompleteHook != null) {\n mFooterRefreshCompleteHook.mLayout = null;\n }\n if (mDelayToDispatchNestedFling != null) {\n mDelayToDispatchNestedFling.mLayout = null;\n }\n if (mDelayToRefreshComplete != null) {\n mDelayToRefreshComplete.mLayout = null;\n }\n mDelayToPerformAutoRefresh.mLayout = null;\n if (mVelocityTracker != null) {\n mVelocityTracker.recycle();\n }\n mVelocityTracker = null;\n if (sDebug) {\n Log.d(TAG, \"onDetachedFromWindow()\");\n }\n super.onDetachedFromWindow();\n }\n\n @Override\n protected void onAttachedToWindow() {\n super.onAttachedToWindow();\n if (sDebug) {\n Log.d(TAG, \"onAttachedToWindow()\");\n }\n final List<ILifecycleObserver> observers = mLifecycleObservers;\n if (observers != null) {\n for (ILifecycleObserver observer : observers) {\n observer.onAttached(this);\n }\n }\n if (isVerticalOrientation()) {\n View view = ViewCatcherUtil.catchAppBarLayout(this);\n if (view != null) {\n mAppBarLayoutUtil = new AppBarLayoutUtil(view);\n if (mInEdgeCanMoveHeaderCallBack == null) {\n mInEdgeCanMoveHeaderCallBack = mAppBarLayoutUtil;\n }\n if (mInEdgeCanMoveFooterCallBack == null) {\n mInEdgeCanMoveFooterCallBack = mAppBarLayoutUtil;\n }\n }\n }\n mDelayToPerformAutoRefresh.mLayout = this;\n }\n\n @Override\n public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {\n int count = getChildCount();\n if (count == 0) {\n return;\n }\n ensureTargetView();\n int maxHeight = 0;\n int maxWidth = 0;\n int childState = 0;\n mCachedViews.clear();\n final boolean measureMatchParentChildren =\n MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY\n || MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY;\n mLayoutManager.mMeasureMatchParentChildren = measureMatchParentChildren;\n mLayoutManager.mOldWidthMeasureSpec = widthMeasureSpec;\n mLayoutManager.mOldHeightMeasureSpec = heightMeasureSpec;\n for (int i = 0; i < count; i++) {\n final View child = getChildAt(i);\n if (child.getVisibility() == GONE) {\n continue;\n }\n final LayoutParams lp = (LayoutParams) child.getLayoutParams();\n if (mHeaderView != null && child == mHeaderView.getView()) {\n mLayoutManager.measureHeader(mHeaderView, widthMeasureSpec, heightMeasureSpec);\n } else if (mFooterView != null && child == mFooterView.getView()) {\n mLayoutManager.measureFooter(mFooterView, widthMeasureSpec, heightMeasureSpec);\n } else {\n measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);\n if (measureMatchParentChildren\n && (lp.width == LayoutParams.MATCH_PARENT\n || lp.height == LayoutParams.MATCH_PARENT)) {\n mCachedViews.add(child);\n }\n }\n maxWidth =\n Math.max(maxWidth, child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);\n maxHeight =\n Math.max(maxHeight, child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);\n childState = combineMeasuredStates(childState, child.getMeasuredState());\n }\n maxWidth += getPaddingLeft() + getPaddingRight();\n maxHeight += getPaddingTop() + getPaddingBottom();\n maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());\n maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());\n setMeasuredDimension(\n resolveSizeAndState(maxWidth, widthMeasureSpec, childState),\n resolveSizeAndState(\n maxHeight, heightMeasureSpec, childState << MEASURED_HEIGHT_STATE_SHIFT));\n count = mCachedViews.size();\n if (count > 1) {\n for (int i = 0; i < count; i++) {\n final View child = mCachedViews.get(i);\n final LayoutParams lp = (LayoutParams) child.getLayoutParams();\n final int[] spec = measureChildAgain(lp, widthMeasureSpec, heightMeasureSpec);\n child.measure(spec[0], spec[1]);\n }\n }\n mCachedViews.clear();\n if (MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY\n || MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY) {\n if (mHeaderView != null && mHeaderView.getView().getVisibility() != GONE) {\n final View child = mHeaderView.getView();\n final LayoutParams lp = (LayoutParams) child.getLayoutParams();\n final int[] spec = measureChildAgain(lp, widthMeasureSpec, heightMeasureSpec);\n mLayoutManager.measureHeader(mHeaderView, spec[0], spec[1]);\n }\n if (mFooterView != null && mFooterView.getView().getVisibility() != GONE) {\n final View child = mFooterView.getView();\n final LayoutParams lp = (LayoutParams) child.getLayoutParams();\n final int[] spec = measureChildAgain(lp, widthMeasureSpec, heightMeasureSpec);\n mLayoutManager.measureFooter(mFooterView, spec[0], spec[1]);\n }\n }\n }\n\n private int[] measureChildAgain(LayoutParams lp, int widthMeasureSpec, int heightMeasureSpec) {\n if (lp.width == LayoutParams.MATCH_PARENT) {\n final int width =\n Math.max(\n 0,\n getMeasuredWidth()\n - getPaddingLeft()\n - getPaddingRight()\n - lp.leftMargin\n - lp.rightMargin);\n mCachedIntPoint[0] = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);\n } else {\n mCachedIntPoint[0] =\n getChildMeasureSpec(\n widthMeasureSpec,\n getPaddingLeft() + getPaddingRight() + lp.leftMargin + lp.rightMargin,\n lp.width);\n }\n if (lp.height == LayoutParams.MATCH_PARENT) {\n final int height =\n Math.max(\n 0,\n getMeasuredHeight()\n - getPaddingTop()\n - getPaddingBottom()\n - lp.topMargin\n - lp.bottomMargin);\n mCachedIntPoint[1] = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);\n } else {\n mCachedIntPoint[1] =\n getChildMeasureSpec(\n heightMeasureSpec,\n getPaddingTop() + getPaddingBottom() + lp.topMargin + lp.bottomMargin,\n lp.height);\n }\n return mCachedIntPoint;\n }\n\n @Override\n protected void onLayout(boolean changed, int l, int t, int r, int b) {\n final int count = getChildCount();\n if (count == 0) {\n return;\n }\n mIndicator.checkConfig();\n final int parentRight = r - l - getPaddingRight();\n final int parentBottom = b - t - getPaddingBottom();\n for (int i = 0; i < count; i++) {\n final View child = getChildAt(i);\n if (child.getVisibility() == GONE) {\n continue;\n }\n if (mHeaderView != null && child == mHeaderView.getView()) {\n mLayoutManager.layoutHeaderView(mHeaderView);\n } else if (mTargetView != null && child == mTargetView) {\n mLayoutManager.layoutContentView(child);\n } else if (mStickyHeaderView != null && child == mStickyHeaderView) {\n mLayoutManager.layoutStickyHeaderView(child);\n } else if ((mFooterView == null || mFooterView.getView() != child)\n && (mStickyFooterView == null || mStickyFooterView != child)) {\n layoutOtherView(child, parentRight, parentBottom);\n }\n }\n if (mFooterView != null && mFooterView.getView().getVisibility() != GONE) {\n mLayoutManager.layoutFooterView(mFooterView);\n }\n if (mStickyFooterView != null && mStickyFooterView.getVisibility() != GONE) {\n mLayoutManager.layoutStickyFooterView(mStickyFooterView);\n }\n if (!mAutomaticActionTriggered) {\n removeCallbacks(mDelayToPerformAutoRefresh);\n postDelayed(mDelayToPerformAutoRefresh, 90);\n }\n }\n\n protected void layoutOtherView(View child, int parentRight, int parentBottom) {\n final int width = child.getMeasuredWidth();\n final int height = child.getMeasuredHeight();\n int childLeft, childTop;\n final LayoutParams lp = (LayoutParams) child.getLayoutParams();\n final int gravity = lp.gravity;\n final int layoutDirection = ViewCompat.getLayoutDirection(this);\n final int absoluteGravity = GravityCompat.getAbsoluteGravity(gravity, layoutDirection);\n final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;\n switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {\n case Gravity.CENTER_HORIZONTAL:\n childLeft =\n (int)\n (getPaddingLeft()\n + (parentRight - getPaddingLeft() - width) / 2f\n + lp.leftMargin\n - lp.rightMargin);\n break;\n case Gravity.RIGHT:\n childLeft = parentRight - width - lp.rightMargin;\n break;\n default:\n childLeft = getPaddingLeft() + lp.leftMargin;\n }\n switch (verticalGravity) {\n case Gravity.CENTER_VERTICAL:\n childTop =\n (int)\n (getPaddingTop()\n + (parentBottom - getPaddingTop() - height) / 2f\n + lp.topMargin\n - lp.bottomMargin);\n break;\n case Gravity.BOTTOM:\n childTop = parentBottom - height - lp.bottomMargin;\n break;\n default:\n childTop = getPaddingTop() + lp.topMargin;\n }\n child.layout(childLeft, childTop, childLeft + width, childTop + height);\n if (sDebug) {\n Log.d(\n TAG,\n String.format(\n \"onLayout(): child: %d %d %d %d\",\n childLeft, childTop, childLeft + width, childTop + height));\n }\n }\n\n @Override\n protected void onDraw(Canvas canvas) {\n super.onDraw(canvas);\n mLayoutManager.onLayoutDraw(canvas);\n }\n\n @Override\n public boolean dispatchTouchEvent(MotionEvent ev) {\n mLastEventIsActionDown = ev.getActionMasked() == MotionEvent.ACTION_DOWN;\n if (!isEnabled()\n || mTargetView == null\n || ((isDisabledLoadMore() && isDisabledRefresh()))\n || (isEnabledPinRefreshViewWhileLoading()\n && ((isRefreshing() && isMovingHeader())\n || (isLoadingMore() && isMovingFooter())))\n || mNestedTouchScrolling) {\n return super.dispatchTouchEvent(ev);\n }\n return processDispatchTouchEvent(ev);\n }\n\n protected final boolean dispatchTouchEventSuper(MotionEvent ev) {\n if (!isEnabledOldTouchHandling()) {\n final int index = ev.findPointerIndex(mTouchPointerId);\n if (index < 0) {\n return super.dispatchTouchEvent(ev);\n }\n if (ev.getActionMasked() == MotionEvent.ACTION_DOWN) {\n mOffsetConsumed = 0;\n mOffsetTotal = 0;\n mOffsetRemaining = mTouchSlop * 3;\n } else {\n if (!mIndicator.isAlreadyHere(IIndicator.START_POS)\n && mIndicator.getRawOffset() != 0) {\n if (mOffsetRemaining > 0) {\n mOffsetRemaining -= mTouchSlop;\n if (isMovingHeader()) {\n mOffsetTotal -= mOffsetRemaining;\n } else if (isMovingFooter()) {\n mOffsetTotal += mOffsetRemaining;\n }\n }\n mOffsetConsumed +=\n mIndicator.getRawOffset() < 0\n ? mIndicator.getLastPos() - mIndicator.getCurrentPos()\n : mIndicator.getCurrentPos() - mIndicator.getLastPos();\n mOffsetTotal += mIndicator.getRawOffset();\n }\n if (isVerticalOrientation()) {\n ev.offsetLocation(0, mOffsetConsumed - mOffsetTotal);\n } else {\n ev.offsetLocation(mOffsetConsumed - mOffsetTotal, 0);\n }\n }\n }\n return super.dispatchTouchEvent(ev);\n }\n\n public void addLifecycleObserver(@NonNull ILifecycleObserver observer) {\n if (mLifecycleObservers == null) {\n mLifecycleObservers = new ArrayList<>();\n mLifecycleObservers.add(observer);\n } else if (!mLifecycleObservers.contains(observer)) {\n mLifecycleObservers.add(observer);\n }\n }\n\n public void removeLifecycleObserver(@NonNull ILifecycleObserver observer) {\n if (mLifecycleObservers != null) {\n mLifecycleObservers.remove(observer);\n }\n }\n\n @Nullable\n public View getScrollTargetView() {\n if (mScrollTargetView != null) {\n return mScrollTargetView;\n } else if (mAutoFoundScrollTargetView != null) {\n return mAutoFoundScrollTargetView;\n } else {\n return mTargetView;\n }\n }\n\n /**\n * Set loadMore scroll target view,For example the content view is a FrameLayout,with a listView\n * in it.You can call this method,set the listView as load more scroll target view. Load more\n * compat will try to make it smooth scrolling.\n *\n * <p>设置加载更多时需要做滑动处理的视图。 例如在SmoothRefreshLayout中有一个CoordinatorLayout,\n * CoordinatorLayout中有AppbarLayout、RecyclerView等,加载更多时希望被移动的视图为RecyclerVieW\n * 而不是CoordinatorLayout,那么设置RecyclerView为TargetView即可\n *\n * @param view Target view\n */\n public void setScrollTargetView(View view) {\n mScrollTargetView = view;\n }\n\n public LayoutManager getLayoutManager() {\n return mLayoutManager;\n }\n\n /**\n * Set custom LayoutManager\n *\n * <p>设置自定义布局管理器\n *\n * @param layoutManager The custom LayoutManager\n */\n public void setLayoutManager(@NonNull LayoutManager layoutManager) {\n if (mLayoutManager != layoutManager) {\n if (mLayoutManager != null) {\n if (mLayoutManager.getOrientation() != layoutManager.getOrientation()) {\n reset();\n requestLayout();\n }\n mLayoutManager.setLayout(null);\n }\n mLayoutManager = layoutManager;\n mLayoutManager.setLayout(this);\n }\n }\n\n /**\n * Set the layout mode\n *\n * <p>设置模式,默认为刷新模式,可配置为拉伸模式\n *\n * @param mode The layout mode. {@link Constants#MODE_DEFAULT}, {@link Constants#MODE_SCALE}\n */\n public void setMode(@Mode int mode) {\n if (mode == Constants.MODE_DEFAULT) {\n if (mLayoutManager instanceof VRefreshLayoutManager) {\n return;\n }\n setLayoutManager(new VRefreshLayoutManager());\n } else {\n if (mLayoutManager instanceof VScaleLayoutManager) {\n return;\n }\n setLayoutManager(new VScaleLayoutManager());\n }\n }\n\n /**\n * Whether to enable the synchronous scroll when load more completed.\n *\n * <p>当加载更多完成时是否启用同步滚动。\n *\n * @param enable enable\n */\n public void setEnableCompatSyncScroll(boolean enable) {\n if (enable) {\n mFlag = mFlag | FLAG_ENABLE_COMPAT_SYNC_SCROLL;\n } else {\n mFlag = mFlag & ~FLAG_ENABLE_COMPAT_SYNC_SCROLL;\n }\n }\n\n /**\n * Set the custom offset calculator.\n *\n * <p>设置自定义偏移计算器\n *\n * @param calculator Offset calculator\n */\n public void setIndicatorOffsetCalculator(IIndicator.IOffsetCalculator calculator) {\n mIndicatorSetter.setOffsetCalculator(calculator);\n }\n\n /**\n * Set the listener to be notified when a refresh is triggered.\n *\n * <p>设置刷新监听回调\n *\n * @param listener Listener\n */\n public <T extends OnRefreshListener> void setOnRefreshListener(T listener) {\n mRefreshListener = listener;\n }\n\n /**\n * Add a listener to listen the views position change event.\n *\n * <p>设置UI位置变化回调\n *\n * @param listener Listener\n */\n public void addOnUIPositionChangedListener(@NonNull OnUIPositionChangedListener listener) {\n if (mUIPositionChangedListeners == null) {\n mUIPositionChangedListeners = new ArrayList<>();\n mUIPositionChangedListeners.add(listener);\n } else if (!mUIPositionChangedListeners.contains(listener)) {\n mUIPositionChangedListeners.add(listener);\n }\n }\n\n /**\n * remove the listener.\n *\n * <p>移除UI位置变化监听器\n *\n * @param listener Listener\n */\n public void removeOnUIPositionChangedListener(@NonNull OnUIPositionChangedListener listener) {\n if (mUIPositionChangedListeners != null) {\n mUIPositionChangedListeners.remove(listener);\n }\n }\n\n /**\n * Add a listener when status changed.\n *\n * <p>添加个状态改变监听\n *\n * @param listener Listener that should be called when status changed.\n */\n public void addOnStatusChangedListener(@NonNull OnStatusChangedListener listener) {\n if (mStatusChangedListeners == null) {\n mStatusChangedListeners = new ArrayList<>();\n mStatusChangedListeners.add(listener);\n } else if (!mStatusChangedListeners.contains(listener)) {\n mStatusChangedListeners.add(listener);\n }\n }\n\n /**\n * remove the listener.\n *\n * <p>移除状态改变监听器\n *\n * @param listener Listener\n */\n public void removeOnStatusChangedListener(@NonNull OnStatusChangedListener listener) {\n if (mStatusChangedListeners != null) {\n mStatusChangedListeners.remove(listener);\n }\n }\n\n /**\n * Set a sync scrolling callback when refresh competed.\n *\n * <p>设置同步滚动回调,可使用该属性对内容视图做滑动处理。例如内容视图是ListView,完成加载更多时,\n * 需要将加载出的数据显示出来,那么设置该回调,每次Footer回滚时拿到滚动的数值对ListView做向上滚动处理,将数据展示处理\n *\n * @param callback a sync scrolling callback when refresh competed.\n */\n public void setOnSyncScrollCallback(OnSyncScrollCallback callback) {\n mSyncScrollCallback = callback;\n }\n\n /**\n * Set a callback to override {@link SmoothRefreshLayout#isNotYetInEdgeCannotMoveHeader()}\n * method. Non-null callback will return the value provided by the callback and ignore all\n * internal logic.\n *\n * <p>设置{@link SmoothRefreshLayout#isNotYetInEdgeCannotMoveHeader()}的重载回调,用来检测内容视图是否在顶部\n *\n * @param callback Callback that should be called when isChildNotYetInEdgeCannotMoveHeader() is\n * called.\n */\n public void setOnHeaderEdgeDetectCallBack(OnHeaderEdgeDetectCallBack callback) {\n mInEdgeCanMoveHeaderCallBack = callback;\n }\n\n /**\n * Set a callback to override {@link SmoothRefreshLayout#isNotYetInEdgeCannotMoveFooter()}\n * method. Non-null callback will return the value provided by the callback and ignore all\n * internal logic.\n *\n * <p>设置{@link SmoothRefreshLayout#isNotYetInEdgeCannotMoveFooter()}的重载回调,用来检测内容视图是否在底部\n *\n * @param callback Callback that should be called when isChildNotYetInEdgeCannotMoveFooter() is\n * called.\n */\n public void setOnFooterEdgeDetectCallBack(OnFooterEdgeDetectCallBack callback) {\n mInEdgeCanMoveFooterCallBack = callback;\n }\n\n /**\n * Set a callback to make sure you need to customize the specified trigger the auto load more\n * rule.\n *\n * <p>设置自动加载更多的触发条件回调,可自定义具体的触发自动加载更多的条件\n *\n * @param callBack Customize the specified triggered rule\n */\n public void setOnPerformAutoLoadMoreCallBack(OnPerformAutoLoadMoreCallBack callBack) {\n mAutoLoadMoreCallBack = callBack;\n }\n\n /**\n * Set a callback to make sure you need to customize the specified trigger the auto refresh\n * rule.\n *\n * <p>设置滚到到顶自动刷新的触发条件回调,可自定义具体的触发自动刷新的条件\n *\n * @param callBack Customize the specified triggered rule\n */\n public void setOnPerformAutoRefreshCallBack(OnPerformAutoRefreshCallBack callBack) {\n mAutoRefreshCallBack = callBack;\n }\n\n public void setOnCalculateBounceCallback(OnCalculateBounceCallback callBack) {\n mCalculateBounceCallback = callBack;\n }\n\n /**\n * Set a hook callback when the refresh complete event be triggered. Only can be called on\n * refreshing.\n *\n * <p>设置一个头部视图刷新完成前的Hook回调\n *\n * @param callback Callback that should be called when refreshComplete() is called.\n */\n public void setOnHookHeaderRefreshCompleteCallback(OnHookUIRefreshCompleteCallBack callback) {\n if (mHeaderRefreshCompleteHook == null)\n mHeaderRefreshCompleteHook = new RefreshCompleteHook();\n mHeaderRefreshCompleteHook.mCallBack = callback;\n }\n\n /**\n * Set a hook callback when the refresh complete event be triggered. Only can be called on\n * loading more.\n *\n * <p>设置一个尾部视图刷新完成前的Hook回调\n *\n * @param callback Callback that should be called when refreshComplete() is called.\n */\n public void setOnHookFooterRefreshCompleteCallback(OnHookUIRefreshCompleteCallBack callback) {\n if (mFooterRefreshCompleteHook == null)\n mFooterRefreshCompleteHook = new RefreshCompleteHook();\n mFooterRefreshCompleteHook.mCallBack = callback;\n }\n\n /**\n * Whether it is refreshing state.\n *\n * <p>是否在刷新中\n *\n * @return Refreshing\n */\n public boolean isRefreshing() {\n return mStatus == SR_STATUS_REFRESHING;\n }\n\n /**\n * Whether it is loading more state.\n *\n * <p>是否在加载更多种\n *\n * @return Loading\n */\n public boolean isLoadingMore() {\n return mStatus == SR_STATUS_LOADING_MORE;\n }\n\n /**\n * Whether it is refresh successful.\n *\n * <p>是否刷新成功\n *\n * @return Is\n */\n public boolean isRefreshSuccessful() {\n return mIsLastRefreshSuccessful;\n }\n\n /**\n * Perform refresh complete, to reset the state to {@link SmoothRefreshLayout#SR_STATUS_INIT}\n * and set the last refresh operation successfully.\n *\n * <p>完成刷新,刷新状态为成功\n */\n public final void refreshComplete() {\n refreshComplete(true);\n }\n\n /**\n * Perform refresh complete, to reset the state to {@link SmoothRefreshLayout#SR_STATUS_INIT}.\n *\n * <p>完成刷新,刷新状态`isSuccessful`\n *\n * @param isSuccessful Set the last refresh operation status\n */\n public final void refreshComplete(boolean isSuccessful) {\n refreshComplete(isSuccessful, 0);\n }\n\n /**\n * Perform refresh complete, delay to reset the state to {@link\n * SmoothRefreshLayout#SR_STATUS_INIT} and set the last refresh operation successfully.\n *\n * <p>完成刷新,延迟`delayDurationToChangeState`时间\n *\n * @param delayDurationToChangeState Delay to change the state to {@link\n * SmoothRefreshLayout#SR_STATUS_COMPLETE}\n */\n public final void refreshComplete(long delayDurationToChangeState) {\n refreshComplete(true, delayDurationToChangeState);\n }\n\n /**\n * Perform refresh complete, delay to reset the state to {@link\n * SmoothRefreshLayout#SR_STATUS_INIT} and set the last refresh operation.\n *\n * <p>完成刷新,刷新状态`isSuccessful`,延迟`delayDurationToChangeState`时间\n *\n * @param delayDurationToChangeState Delay to change the state to {@link\n * SmoothRefreshLayout#SR_STATUS_INIT}\n * @param isSuccessful Set the last refresh operation\n */\n public final void refreshComplete(boolean isSuccessful, long delayDurationToChangeState) {\n if (sDebug) {\n Log.d(\n TAG,\n String.format(\n \"refreshComplete(): isSuccessful: %b, \"\n + \"delayDurationToChangeState: %d\",\n isSuccessful, delayDurationToChangeState));\n }\n mIsLastRefreshSuccessful = isSuccessful;\n if (!isRefreshing() && !isLoadingMore()) {\n return;\n }\n if (delayDurationToChangeState <= 0) {\n performRefreshComplete(true, false, true);\n } else {\n if (isRefreshing() && mHeaderView != null) {\n mHeaderView.onRefreshComplete(this, isSuccessful);\n } else if (isLoadingMore() && mFooterView != null) {\n mFooterView.onRefreshComplete(this, isSuccessful);\n }\n if (mDelayToRefreshComplete == null) {\n mDelayToRefreshComplete = new DelayToRefreshComplete();\n }\n mDelayToRefreshComplete.mLayout = this;\n mDelayToRefreshComplete.mNotifyViews = false;\n postDelayed(mDelayToRefreshComplete, delayDurationToChangeState);\n }\n }\n\n /**\n * Get the Header height, after the measurement is completed, the height will have value.\n *\n * <p>获取Header的高度,在布局计算完成前无法得到准确的值\n *\n * @return Height default is -1\n */\n public int getHeaderHeight() {\n return mIndicator.getHeaderHeight();\n }\n\n /**\n * Get the Footer height, after the measurement is completed, the height will have value.\n *\n * <p>获取Footer的高度,在布局计算完成前无法得到准确的值\n *\n * @return Height default is -1\n */\n public int getFooterHeight() {\n return mIndicator.getFooterHeight();\n }\n\n /**\n * Perform auto refresh at once.\n *\n * <p>自动刷新并立即触发刷新回调\n */\n public boolean autoRefresh() {\n return autoRefresh(Constants.ACTION_NOTIFY, true);\n }\n\n /**\n * If @param atOnce has been set to true. Auto perform refresh at once.\n *\n * <p>自动刷新,`atOnce`立即触发刷新回调\n *\n * @param atOnce Auto refresh at once\n */\n public boolean autoRefresh(boolean atOnce) {\n return autoRefresh(atOnce ? Constants.ACTION_AT_ONCE : Constants.ACTION_NOTIFY, true);\n }\n\n /**\n * If @param atOnce has been set to true. Auto perform refresh at once. If @param smooth has\n * been set to true. Auto perform refresh will using smooth scrolling.\n *\n * <p>自动刷新,`atOnce`立即触发刷新回调,`smoothScroll`滚动到触发位置\n *\n * @param atOnce Auto refresh at once\n * @param smoothScroll Auto refresh use smooth scrolling\n */\n public boolean autoRefresh(boolean atOnce, boolean smoothScroll) {\n return autoRefresh(\n atOnce ? Constants.ACTION_AT_ONCE : Constants.ACTION_NOTIFY, smoothScroll);\n }\n\n /**\n * The @param action can be used to specify the action to trigger refresh. If the `action` been\n * set to `SR_ACTION_NOTHING`, we will not notify the refresh listener when in refreshing. If\n * the `action` been set to `SR_ACTION_AT_ONCE`, we will notify the refresh listener at once. If\n * the `action` been set to `SR_ACTION_NOTIFY`, we will notify the refresh listener when in\n * refreshing be later If @param smooth has been set to true. Auto perform refresh will using\n * smooth scrolling.\n *\n * <p>自动刷新,`action`触发刷新的动作,`smoothScroll`滚动到触发位置\n *\n * @param action Auto refresh use action .{@link Constants#ACTION_NOTIFY}, {@link\n * Constants#ACTION_AT_ONCE}, {@link Constants#ACTION_NOTHING}\n * @param smoothScroll Auto refresh use smooth scrolling\n */\n public boolean autoRefresh(@Action int action, boolean smoothScroll) {\n if (mStatus != SR_STATUS_INIT || isDisabledPerformRefresh()) {\n return false;\n }\n if (sDebug) {\n Log.d(\n TAG,\n String.format(\n \"autoRefresh(): action: %d, smoothScroll: %b\", action, smoothScroll));\n }\n final byte old = mStatus;\n mStatus = SR_STATUS_PREPARE;\n notifyStatusChanged(old, mStatus);\n if (mHeaderView != null) {\n mHeaderView.onRefreshPrepare(this);\n }\n mIndicatorSetter.setMovingStatus(Constants.MOVING_HEADER);\n mViewStatus = SR_VIEW_STATUS_HEADER_IN_PROCESSING;\n mAutomaticActionUseSmoothScroll = smoothScroll;\n mAutomaticAction = action;\n if (mIndicator.getHeaderHeight() <= 0) {\n mAutomaticActionTriggered = false;\n } else {\n scrollToTriggeredAutomatic(true);\n }\n return true;\n }\n\n /**\n * Trigger refresh action directly\n *\n * <p>强制直接触发刷新\n */\n public boolean forceRefresh() {\n if (mIndicator.getHeaderHeight() <= 0 || isDisabledPerformRefresh()) {\n return false;\n }\n removeCallbacks(mDelayToRefreshComplete);\n triggeredRefresh(true);\n return true;\n }\n\n /**\n * Perform auto load more at once.\n *\n * <p>自动加载更多,并立即触发刷新回调\n */\n public boolean autoLoadMore() {\n return autoLoadMore(Constants.ACTION_NOTIFY, true);\n }\n\n /**\n * If @param atOnce has been set to true. Auto perform load more at once.\n *\n * <p>自动加载更多,`atOnce`立即触发刷新回调\n *\n * @param atOnce Auto load more at once\n */\n public boolean autoLoadMore(boolean atOnce) {\n return autoLoadMore(atOnce ? Constants.ACTION_AT_ONCE : Constants.ACTION_NOTIFY, true);\n }\n\n /**\n * If @param atOnce has been set to true. Auto perform load more at once. If @param smooth has\n * been set to true. Auto perform load more will using smooth scrolling.\n *\n * <p>自动加载更多,`atOnce`立即触发刷新回调,`smoothScroll`滚动到触发位置\n *\n * @param atOnce Auto load more at once\n * @param smoothScroll Auto load more use smooth scrolling\n */\n public boolean autoLoadMore(boolean atOnce, boolean smoothScroll) {\n return autoLoadMore(\n atOnce ? Constants.ACTION_AT_ONCE : Constants.ACTION_NOTIFY, smoothScroll);\n }\n\n /**\n * The @param action can be used to specify the action to trigger refresh. If the `action` been\n * set to `SR_ACTION_NOTHING`, we will not notify the refresh listener when in refreshing. If\n * the `action` been set to `SR_ACTION_AT_ONCE`, we will notify the refresh listener at once. If\n * the `action` been set to `SR_ACTION_NOTIFY`, we will notify the refresh listener when in\n * refreshing be later If @param smooth has been set to true. Auto perform load more will using\n * smooth scrolling.\n *\n * <p>自动加载更多,`action`触发加载更多的动作,`smoothScroll`滚动到触发位置\n *\n * @param action Auto load more use action.{@link Constants#ACTION_NOTIFY}, {@link\n * Constants#ACTION_AT_ONCE}, {@link Constants#ACTION_NOTHING}\n * @param smoothScroll Auto load more use smooth scrolling\n */\n public boolean autoLoadMore(@Action int action, boolean smoothScroll) {\n if (mStatus != SR_STATUS_INIT || isDisabledPerformLoadMore()) {\n return false;\n }\n if (sDebug) {\n Log.d(\n TAG,\n String.format(\n \"autoLoadMore(): action: %d, smoothScroll: %b\", action, smoothScroll));\n }\n final byte old = mStatus;\n mStatus = SR_STATUS_PREPARE;\n notifyStatusChanged(old, mStatus);\n if (mFooterView != null) {\n mFooterView.onRefreshPrepare(this);\n }\n mIndicatorSetter.setMovingStatus(Constants.MOVING_FOOTER);\n mViewStatus = SR_VIEW_STATUS_FOOTER_IN_PROCESSING;\n mAutomaticActionUseSmoothScroll = smoothScroll;\n if (mIndicator.getFooterHeight() <= 0) {\n mAutomaticActionTriggered = false;\n } else {\n scrollToTriggeredAutomatic(false);\n }\n return true;\n }\n\n /**\n * Trigger load more action directly\n *\n * <p>强制直接触发加载更多\n */\n public boolean forceLoadMore() {\n if (mIndicator.getFooterHeight() <= 0 || isDisabledPerformLoadMore()) {\n return false;\n }\n removeCallbacks(mDelayToRefreshComplete);\n triggeredLoadMore(true);\n return true;\n }\n\n /**\n * Set the resistance while you are moving.\n *\n * <p>移动刷新视图时候的移动阻尼\n *\n * @param resistance Resistance\n */\n public void setResistance(float resistance) {\n mIndicatorSetter.setResistance(resistance);\n }\n\n /**\n * Set the resistance while you are moving Footer.\n *\n * <p>移动Footer视图时候的移动阻尼\n *\n * @param resistance Resistance\n */\n public void setResistanceOfFooter(float resistance) {\n mIndicatorSetter.setResistanceOfFooter(resistance);\n }\n\n /**\n * Set the resistance while you are moving Header.\n *\n * <p>移动Header视图时候的移动阻尼\n *\n * @param resistance Resistance\n */\n public void setResistanceOfHeader(float resistance) {\n mIndicatorSetter.setResistanceOfHeader(resistance);\n }\n\n /**\n * Set the height ratio of the trigger refresh.\n *\n * <p>设置触发刷新时的位置占刷新视图的高度比\n *\n * @param ratio Height ratio\n */\n public void setRatioToRefresh(float ratio) {\n mIndicatorSetter.setRatioToRefresh(ratio);\n }\n\n /**\n * Set the Header height ratio of the trigger refresh.\n *\n * <p>设置触发下拉刷新时的位置占Header视图的高度比\n *\n * @param ratio Height ratio\n */\n public void setRatioOfHeaderToRefresh(float ratio) {\n mIndicatorSetter.setRatioOfHeaderToRefresh(ratio);\n }\n\n /**\n * Set the Footer height ratio of the trigger refresh.\n *\n * <p>设置触发加载更多时的位置占Footer视图的高度比\n *\n * @param ratio Height ratio\n */\n public void setRatioOfFooterToRefresh(float ratio) {\n mIndicatorSetter.setRatioOfFooterToRefresh(ratio);\n }\n\n /**\n * Set the offset of keep view in refreshing occupies the height ratio of the refresh view.\n *\n * <p>刷新中保持视图位置占刷新视图的高度比(默认:`1f`),该属性的值必须小于等于触发刷新高度比才会有效果, 当开启了{@link\n * SmoothRefreshLayout#isEnabledKeepRefreshView}后,该属性会生效\n *\n * @param ratio Height ratio\n */\n public void setRatioToKeep(float ratio) {\n mIndicatorSetter.setRatioToKeepHeader(ratio);\n mIndicatorSetter.setRatioToKeepFooter(ratio);\n }\n\n /**\n * Set the offset of keep Header in refreshing occupies the height ratio of the Header.\n *\n * <p>刷新中保持视图位置占Header视图的高度比(默认:`1f`),该属性的值必须小于等于触发刷新高度比才会有效果\n *\n * @param ratio Height ratio\n */\n public void setRatioToKeepHeader(float ratio) {\n mIndicatorSetter.setRatioToKeepHeader(ratio);\n }\n\n /**\n * Set the offset of keep Footer in refreshing occupies the height ratio of the Footer.\n *\n * <p>刷新中保持视图位置占Header视图的高度比(默认:`1f`),该属性的值必须小于等于触发刷新高度比才会有效果\n *\n * @param ratio Height ratio\n */\n public void setRatioToKeepFooter(float ratio) {\n mIndicatorSetter.setRatioToKeepFooter(ratio);\n }\n\n /**\n * Set the max duration for Cross-Boundary-Rebound(OverScroll).\n *\n * <p>设置越界回弹效果弹出时的最大持续时长(默认:`350`)\n *\n * @param duration Duration\n */\n public void setMaxOverScrollDuration(int duration) {\n mMaxOverScrollDuration = duration;\n }\n\n /**\n * Set the min duration for Cross-Boundary-Rebound(OverScroll).\n *\n * <p>设置越界回弹效果弹出时的最小持续时长(默认:`100`)\n *\n * @param duration Duration\n */\n public void setMinOverScrollDuration(int duration) {\n mMinOverScrollDuration = duration;\n }\n\n /**\n * Set the duration for Fling back.\n *\n * <p>设置越界回弹效果回弹时的持续时长(默认:`550`)\n *\n * @param duration Duration\n */\n public void setFlingBackDuration(int duration) {\n mDurationOfFlingBack = duration;\n }\n\n /**\n * Set the duration of return back to the start position.\n *\n * <p>设置刷新完成回滚到起始位置的时间\n *\n * @param duration Millis\n */\n public void setDurationToClose(int duration) {\n mDurationToCloseHeader = duration;\n mDurationToCloseFooter = duration;\n }\n\n /**\n * Set the duration of Header return to the start position.\n *\n * <p>设置Header刷新完成回滚到起始位置的时间\n *\n * @param duration Millis\n */\n public void setDurationToCloseHeader(int duration) {\n mDurationToCloseHeader = duration;\n }\n\n /**\n * Set the duration of Footer return to the start position.\n *\n * <p>设置Footer刷新完成回滚到起始位置的时间\n *\n * @param duration Millis\n */\n public void setDurationToCloseFooter(int duration) {\n mDurationToCloseFooter = duration;\n }\n\n /**\n * Set the duration of return to the keep refresh view position.\n *\n * <p>设置回滚到保持刷新视图位置的时间\n *\n * @param duration Millis\n */\n public void setDurationOfBackToKeep(int duration) {\n mDurationOfBackToHeaderHeight = duration;\n mDurationOfBackToFooterHeight = duration;\n }\n\n /**\n * Set the duration of return to the keep refresh view position when Header moves.\n *\n * <p>设置回滚到保持Header视图位置的时间\n *\n * @param duration Millis\n */\n public void setDurationOfBackToKeepHeader(int duration) {\n this.mDurationOfBackToHeaderHeight = duration;\n }\n\n /**\n * Set the duration of return to the keep refresh view position when Footer moves.\n *\n * <p>设置回顾到保持Footer视图位置的时间\n *\n * @param duration Millis\n */\n public void setDurationOfBackToKeepFooter(int duration) {\n this.mDurationOfBackToFooterHeight = duration;\n }\n\n /**\n * Set the max can move offset occupies the height ratio of the refresh view.\n *\n * <p>设置最大移动距离占刷新视图的高度比\n *\n * @param ratio The max ratio of refresh view\n */\n public void setMaxMoveRatio(float ratio) {\n mIndicatorSetter.setMaxMoveRatio(ratio);\n }\n\n /**\n * Set the max can move offset occupies the height ratio of the Header.\n *\n * <p>设置最大移动距离占Header视图的高度比\n *\n * @param ratio The max ratio of Header view\n */\n public void setMaxMoveRatioOfHeader(float ratio) {\n mIndicatorSetter.setMaxMoveRatioOfHeader(ratio);\n }\n\n /**\n * Set the max can move offset occupies the height ratio of the Footer.\n *\n * <p>设置最大移动距离占Footer视图的高度比\n *\n * @param ratio The max ratio of Footer view\n */\n public void setMaxMoveRatioOfFooter(float ratio) {\n mIndicatorSetter.setMaxMoveRatioOfFooter(ratio);\n }\n\n /**\n * The flag has set to autoRefresh.\n *\n * <p>是否处于自动刷新刷新\n *\n * @return Enabled\n */\n public boolean isAutoRefresh() {\n return (mFlag & FLAG_AUTO_REFRESH) > 0;\n }\n\n /**\n * The flag has set enabled overScroll.\n *\n * <p>是否已经开启越界回弹\n *\n * @return Enabled\n */\n public boolean isEnabledOverScroll() {\n return (mFlag & FLAG_ENABLE_OVER_SCROLL) > 0;\n }\n\n /**\n * If @param enable has been set to true. Will supports over scroll.\n *\n * <p>设置开始越界回弹\n *\n * @param enable Enable\n */\n public void setEnableOverScroll(boolean enable) {\n if (enable) {\n mFlag = mFlag | FLAG_ENABLE_OVER_SCROLL;\n } else {\n mFlag = mFlag & ~FLAG_ENABLE_OVER_SCROLL;\n }\n }\n\n /**\n * The flag has set enabled to intercept the touch event while loading.\n *\n * <p>是否已经开启刷新中拦截消耗触摸事件\n *\n * @return Enabled\n */\n public boolean isEnabledInterceptEventWhileLoading() {\n return (mFlag & FLAG_ENABLE_INTERCEPT_EVENT_WHILE_LOADING) > 0;\n }\n\n /**\n * If @param enable has been set to true. Will intercept the touch event while loading.\n *\n * <p>开启刷新中拦截消耗触摸事件\n *\n * @param enable Enable\n */\n public void setEnableInterceptEventWhileLoading(boolean enable) {\n if (enable) {\n mFlag = mFlag | FLAG_ENABLE_INTERCEPT_EVENT_WHILE_LOADING;\n } else {\n mFlag = mFlag & ~FLAG_ENABLE_INTERCEPT_EVENT_WHILE_LOADING;\n }\n }\n\n /**\n * The flag has been set to pull to refresh.\n *\n * <p>是否已经开启拉动刷新,下拉或者上拉到触发刷新位置即立即触发刷新\n *\n * @return Enabled\n */\n public boolean isEnabledPullToRefresh() {\n return (mFlag & FLAG_ENABLE_PULL_TO_REFRESH) > 0;\n }\n\n /**\n * If @param enable has been set to true. When the current pos >= refresh offsets perform\n * refresh.\n *\n * <p>设置开启拉动刷新,下拉或者上拉到触发刷新位置即立即触发刷新\n *\n * @param enable Pull to refresh\n */\n public void setEnablePullToRefresh(boolean enable) {\n if (enable) {\n mFlag = mFlag | FLAG_ENABLE_PULL_TO_REFRESH;\n } else {\n mFlag = mFlag & ~FLAG_ENABLE_PULL_TO_REFRESH;\n }\n }\n\n /**\n * The flag has been set to enabled Header drawerStyle.\n *\n * <p>是否已经开启Header的抽屉效果,即Header在Content下面\n *\n * @return Enabled\n */\n public boolean isEnabledHeaderDrawerStyle() {\n return (mFlag & FLAG_ENABLE_HEADER_DRAWER_STYLE) > 0;\n }\n\n /**\n * If @param enable has been set to true.Enable Header drawerStyle.\n *\n * <p>设置开启Header的抽屉效果,即Header在Content下面,由于该效果需要改变层级关系,所以需要重新布局\n *\n * @param enable enable Header drawerStyle\n */\n public void setEnableHeaderDrawerStyle(boolean enable) {\n if (enable) {\n mFlag = mFlag | FLAG_ENABLE_HEADER_DRAWER_STYLE;\n } else {\n mFlag = mFlag & ~FLAG_ENABLE_HEADER_DRAWER_STYLE;\n }\n mViewsZAxisNeedReset = true;\n checkViewsZAxisNeedReset();\n }\n\n /**\n * The flag has been set to enabled Footer drawerStyle.\n *\n * <p>是否已经开启Footer的抽屉效果,即Footer在Content下面\n *\n * @return Enabled\n */\n public boolean isEnabledFooterDrawerStyle() {\n return (mFlag & FLAG_ENABLE_FOOTER_DRAWER_STYLE) > 0;\n }\n\n /**\n * If @param enable has been set to true.Enable Footer drawerStyle.\n *\n * <p>设置开启Footer的抽屉效果,即Footer在Content下面,由于该效果需要改变层级关系,所以需要重新布局\n *\n * @param enable enable Footer drawerStyle\n */\n public void setEnableFooterDrawerStyle(boolean enable) {\n if (enable) {\n mFlag = mFlag | FLAG_ENABLE_FOOTER_DRAWER_STYLE;\n } else {\n mFlag = mFlag & ~FLAG_ENABLE_FOOTER_DRAWER_STYLE;\n }\n mViewsZAxisNeedReset = true;\n checkViewsZAxisNeedReset();\n }\n\n /**\n * The flag has been set to disabled perform refresh.\n *\n * <p>是否已经关闭触发下拉刷新\n *\n * @return Disabled\n */\n public boolean isDisabledPerformRefresh() {\n return (mFlag & MASK_DISABLE_PERFORM_REFRESH) > 0;\n }\n\n /**\n * If @param disable has been set to true. Will never perform refresh.\n *\n * <p>设置是否关闭触发下拉刷新\n *\n * @param disable Disable perform refresh\n */\n public void setDisablePerformRefresh(boolean disable) {\n if (disable) {\n mFlag = mFlag | FLAG_DISABLE_PERFORM_REFRESH;\n reset();\n } else {\n mFlag = mFlag & ~FLAG_DISABLE_PERFORM_REFRESH;\n }\n }\n\n /**\n * The flag has been set to disabled refresh.\n *\n * <p>是否已经关闭刷新\n *\n * @return Disabled\n */\n public boolean isDisabledRefresh() {\n return (mFlag & FLAG_DISABLE_REFRESH) > 0;\n }\n\n /**\n * If @param disable has been set to true.Will disable refresh.\n *\n * <p>设置是否关闭刷新\n *\n * @param disable Disable refresh\n */\n public void setDisableRefresh(boolean disable) {\n if (disable) {\n mFlag = mFlag | FLAG_DISABLE_REFRESH;\n reset();\n } else {\n mFlag = mFlag & ~FLAG_DISABLE_REFRESH;\n }\n }\n\n /**\n * The flag has been set to disabled perform load more.\n *\n * <p>是否已经关闭触发加载更多\n *\n * @return Disabled\n */\n public boolean isDisabledPerformLoadMore() {\n return (mFlag & MASK_DISABLE_PERFORM_LOAD_MORE) > 0;\n }\n\n /**\n * If @param disable has been set to true.Will never perform load more.\n *\n * <p>设置是否关闭触发加载更多\n *\n * @param disable Disable perform load more\n */\n public void setDisablePerformLoadMore(boolean disable) {\n if (disable) {\n mFlag = mFlag | FLAG_DISABLE_PERFORM_LOAD_MORE;\n reset();\n } else {\n mFlag = mFlag & ~FLAG_DISABLE_PERFORM_LOAD_MORE;\n }\n }\n\n /**\n * The flag has been set to disabled load more.\n *\n * <p>是否已经关闭加载更多\n *\n * @return Disabled\n */\n public boolean isDisabledLoadMore() {\n return (mFlag & FLAG_DISABLE_LOAD_MORE) > 0;\n }\n\n /**\n * If @param disable has been set to true. Will disable load more.\n *\n * <p>设置关闭加载更多\n *\n * @param disable Disable load more\n */\n public void setDisableLoadMore(boolean disable) {\n if (disable) {\n mFlag = mFlag | FLAG_DISABLE_LOAD_MORE;\n reset();\n } else {\n mFlag = mFlag & ~FLAG_DISABLE_LOAD_MORE;\n }\n }\n\n /**\n * The flag has been set to enabled the old touch handling logic.\n *\n * <p>是否已经启用老版本的事件处理逻辑\n *\n * @return Enabled\n */\n public boolean isEnabledOldTouchHandling() {\n return (mFlag & FLAG_ENABLE_OLD_TOUCH_HANDLING) > 0;\n }\n\n /**\n * If @param enable has been set to true. Frame will use the old version of the touch event\n * handling logic.\n *\n * <p>设置开启老版本的事件处理逻辑,老版本的逻辑会导致部分场景下体验下降,例如拉出刷新视图再收回视图,\n * 当刷新视图回到顶部后缓慢滑动会导致内容视图触发按下效果,视觉上产生割裂,整体性较差但兼容性最好。\n * 新版本的逻辑将一直向下传递触摸事件,不会产生割裂效果,但同时由于需要避免触发长按事件,取巧性的利用了偏移进行规避,\n * 可能导致极个别情况下兼容没有老版本的逻辑好,可按需切换。切莫在处理事件处理过程中切换!\n *\n * @param enable Enable old touch handling\n */\n public void setEnableOldTouchHandling(boolean enable) {\n if (mIndicator.hasTouched()) {\n Log.e(TAG, \"This method cannot be called during touch event handling\");\n return;\n }\n if (enable) {\n mFlag = mFlag | FLAG_ENABLE_OLD_TOUCH_HANDLING;\n } else {\n mFlag = mFlag & ~FLAG_ENABLE_OLD_TOUCH_HANDLING;\n }\n }\n\n /**\n * The flag has been set to disabled when horizontal move.\n *\n * <p>是否已经设置响应其它方向滑动\n *\n * @return Disabled\n */\n public boolean isDisabledWhenAnotherDirectionMove() {\n return (mFlag & FLAG_DISABLE_WHEN_ANOTHER_DIRECTION_MOVE) > 0;\n }\n\n /**\n * Set whether to filter the horizontal moves.\n *\n * <p>设置响应其它方向滑动,当内容视图含有需要响应其它方向滑动的子视图时,需要设置该属性,否则子视图无法响应其它方向的滑动\n *\n * @param disable Enable\n */\n public void setDisableWhenAnotherDirectionMove(boolean disable) {\n if (disable) {\n mFlag = mFlag | FLAG_DISABLE_WHEN_ANOTHER_DIRECTION_MOVE;\n } else {\n mFlag = mFlag & ~FLAG_DISABLE_WHEN_ANOTHER_DIRECTION_MOVE;\n }\n }\n\n /**\n * The flag has been set to enabled load more has no more data.\n *\n * <p>是否已经开启加载更多完成已无更多数据,自定义Footer可根据该属性判断是否显示无更多数据的提示\n *\n * @return Enabled\n */\n public boolean isEnabledNoMoreData() {\n return (mFlag & FLAG_ENABLE_NO_MORE_DATA) > 0;\n }\n\n /**\n * If @param enable has been set to true. The Footer will show no more data and will never\n * trigger load more.\n *\n * <p>设置开启加载更多完成已无更多数据,当该属性设置为`true`时,将不再触发加载更多\n *\n * @param enable Enable no more data\n */\n public void setEnableNoMoreData(boolean enable) {\n mFlag = mFlag | FLAG_BEEN_SET_NO_MORE_DATA;\n if (enable) {\n mFlag = mFlag | FLAG_ENABLE_NO_MORE_DATA;\n } else {\n mFlag = mFlag & ~(FLAG_ENABLE_NO_MORE_DATA | FLAG_ENABLE_NO_MORE_DATA_NO_BACK);\n }\n }\n\n /**\n * The flag has been set to enabled. Load more will be disabled when the content is not full.\n *\n * <p>是否已经设置了内容视图未满屏时关闭加载更多\n *\n * @return Disabled\n */\n public boolean isDisabledLoadMoreWhenContentNotFull() {\n return (mFlag & FLAG_DISABLE_LOAD_MORE_WHEN_CONTENT_NOT_FULL) > 0;\n }\n\n /**\n * If @param disable has been set to true.Load more will be disabled when the content is not\n * full.\n *\n * <p>设置当内容视图未满屏时关闭加载更多\n *\n * @param disable Disable load more when the content is not full\n */\n public void setDisableLoadMoreWhenContentNotFull(boolean disable) {\n if (disable) {\n mFlag = mFlag | FLAG_DISABLE_LOAD_MORE_WHEN_CONTENT_NOT_FULL;\n } else {\n mFlag = mFlag & ~FLAG_DISABLE_LOAD_MORE_WHEN_CONTENT_NOT_FULL;\n }\n }\n\n /**\n * The flag has been set to enabled when Footer has no more data and no spring back.\n *\n * <p>是否已经开启加载更多完成已无更多数据且不需要回滚动作\n *\n * @return Enabled\n */\n public boolean isEnabledNoMoreDataAndNoSpringBack() {\n return (mFlag & FLAG_ENABLE_NO_MORE_DATA_NO_BACK) > 0;\n }\n\n /**\n * If @param enable has been set to true. When there is no more data and no spring back.\n *\n * <p>设置开启加载更多完成已无更多数据且不需要回滚动作,当该属性设置为`true`时,将不再触发加载更多\n *\n * @param enable Enable no more data\n */\n public void setEnableNoMoreDataAndNoSpringBack(boolean enable) {\n mFlag = mFlag | FLAG_BEEN_SET_NO_MORE_DATA;\n if (enable) {\n mFlag = mFlag | FLAG_ENABLE_NO_MORE_DATA | FLAG_ENABLE_NO_MORE_DATA_NO_BACK;\n } else {\n mFlag = mFlag & ~(FLAG_ENABLE_NO_MORE_DATA | FLAG_ENABLE_NO_MORE_DATA_NO_BACK);\n }\n }\n\n /**\n * The flag has been set to keep refresh view while loading.\n *\n * <p>是否已经开启保持刷新视图\n *\n * @return Enabled\n */\n public boolean isEnabledKeepRefreshView() {\n return (mFlag & FLAG_ENABLE_KEEP_REFRESH_VIEW) > 0;\n }\n\n /**\n * If @param enable has been set to true.When the current pos> = keep refresh view pos, it rolls\n * back to the keep refresh view pos to perform refresh and remains until the refresh completed.\n *\n * <p>开启刷新中保持刷新视图位置\n *\n * @param enable Keep refresh view\n */\n public void setEnableKeepRefreshView(boolean enable) {\n\n if (enable) {\n mFlag = mFlag | FLAG_ENABLE_KEEP_REFRESH_VIEW;\n } else {\n mFlag =\n mFlag\n & ~(FLAG_ENABLE_KEEP_REFRESH_VIEW\n | FLAG_ENABLE_PIN_REFRESH_VIEW_WHILE_LOADING);\n }\n }\n\n /**\n * The flag has been set to perform load more when the content view scrolling to bottom.\n *\n * <p>是否已经开启到底部自动加载更多\n *\n * @return Enabled\n */\n public boolean isEnabledAutoLoadMore() {\n return (mFlag & FLAG_ENABLE_AUTO_PERFORM_LOAD_MORE) > 0;\n }\n\n /**\n * If @param enable has been set to true.When the content view scrolling to bottom, it will be\n * perform load more.\n *\n * <p>开启到底自动加载更多\n *\n * @param enable Enable\n */\n public void setEnableAutoLoadMore(boolean enable) {\n if (enable) {\n mFlag = mFlag | FLAG_ENABLE_AUTO_PERFORM_LOAD_MORE;\n } else {\n mFlag = mFlag & ~FLAG_ENABLE_AUTO_PERFORM_LOAD_MORE;\n }\n }\n\n /**\n * The flag has been set to perform refresh when the content view scrolling to top.\n *\n * <p>是否已经开启到顶自动刷新\n *\n * @return Enabled\n */\n public boolean isEnabledAutoRefresh() {\n return (mFlag & FLAG_ENABLE_AUTO_PERFORM_REFRESH) > 0;\n }\n\n /**\n * If @param enable has been set to true.When the content view scrolling to top, it will be\n * perform refresh.\n *\n * <p>开启到顶自动刷新\n *\n * @param enable Enable\n */\n public void setEnableAutoRefresh(boolean enable) {\n if (enable) {\n mFlag = mFlag | FLAG_ENABLE_AUTO_PERFORM_REFRESH;\n } else {\n mFlag = mFlag & ~FLAG_ENABLE_AUTO_PERFORM_REFRESH;\n }\n }\n\n /**\n * The flag has been set to pinned refresh view while loading.\n *\n * <p>是否已经开启刷新过程中固定刷新视图且不响应触摸移动\n *\n * @return Enabled\n */\n public boolean isEnabledPinRefreshViewWhileLoading() {\n return (mFlag & FLAG_ENABLE_PIN_REFRESH_VIEW_WHILE_LOADING) > 0;\n }\n\n /**\n * If @param enable has been set to true.The refresh view will pinned at the keep refresh\n * position.\n *\n * @param enable Pin content view\n */\n public void setEnablePinRefreshViewWhileLoading(boolean enable) {\n if (enable) {\n mFlag =\n mFlag\n | FLAG_ENABLE_PIN_CONTENT_VIEW\n | FLAG_ENABLE_PIN_REFRESH_VIEW_WHILE_LOADING\n | FLAG_ENABLE_KEEP_REFRESH_VIEW;\n } else {\n mFlag = mFlag & ~FLAG_ENABLE_PIN_REFRESH_VIEW_WHILE_LOADING;\n }\n }\n\n /**\n * The flag has been set to pinned content view while loading.\n *\n * <p>是否已经开启了固定内容视图\n *\n * @return Enabled\n */\n public boolean isEnabledPinContentView() {\n return (mFlag & FLAG_ENABLE_PIN_CONTENT_VIEW) > 0;\n }\n\n /**\n * If @param enable has been set to true. The content view will be pinned in the start pos.\n *\n * <p>设置开启固定内容视图\n *\n * @param enable Pin content view\n */\n public void setEnablePinContentView(boolean enable) {\n if (enable) {\n mFlag = mFlag | FLAG_ENABLE_PIN_CONTENT_VIEW;\n } else {\n mFlag =\n mFlag\n & ~(FLAG_ENABLE_PIN_CONTENT_VIEW\n | FLAG_ENABLE_PIN_REFRESH_VIEW_WHILE_LOADING);\n }\n }\n\n /**\n * The flag has been set to perform refresh when Fling.\n *\n * <p>是否已经开启了当收回刷新视图的手势被触发且当前位置大于触发刷新的位置时,将可以触发刷新同时将不存在Fling效果的功能,\n *\n * @return Enabled\n */\n public boolean isEnabledPerformFreshWhenFling() {\n return (mFlag & FLAG_ENABLE_PERFORM_FRESH_WHEN_FLING) > 0;\n }\n\n /**\n * If @param enable has been set to true. When the gesture of retracting the refresh view is\n * triggered and the current offset is greater than the trigger refresh offset, the fresh can be\n * performed without the Fling effect.\n *\n * <p>当收回刷新视图的手势被触发且当前位置大于触发刷新的位置时,将可以触发刷新同时将不存在Fling效果\n *\n * @param enable enable perform refresh when fling\n */\n public void setEnablePerformFreshWhenFling(boolean enable) {\n if (enable) {\n mFlag = mFlag | FLAG_ENABLE_PERFORM_FRESH_WHEN_FLING;\n } else {\n mFlag = mFlag & ~FLAG_ENABLE_PERFORM_FRESH_WHEN_FLING;\n }\n }\n\n @Nullable\n public IRefreshView<IIndicator> getFooterView() {\n // Use the static default creator to create the Footer view\n if (!isDisabledLoadMore() && mFooterView == null && sCreator != null) {\n final IRefreshView<IIndicator> footer = sCreator.createFooter(this);\n if (footer != null) {\n setFooterView(footer);\n }\n }\n return mFooterView;\n }\n\n /**\n * Set the Footer view.\n *\n * <p>设置Footer视图\n *\n * @param footer Footer view\n */\n public void setFooterView(@NonNull IRefreshView footer) {\n if (footer.getType() != IRefreshView.TYPE_FOOTER) {\n throw new IllegalArgumentException(\"Wrong type, FooterView type must be TYPE_FOOTER\");\n }\n if (footer == mFooterView) {\n return;\n }\n if (mFooterView != null) {\n removeView(mFooterView.getView());\n mFooterView = null;\n }\n final View view = footer.getView();\n mViewsZAxisNeedReset = true;\n addView(view, -1, view.getLayoutParams());\n }\n\n @Nullable\n public IRefreshView<IIndicator> getHeaderView() {\n // Use the static default creator to create the Header view\n if (!isDisabledRefresh() && mHeaderView == null && sCreator != null) {\n final IRefreshView<IIndicator> header = sCreator.createHeader(this);\n if (header != null) {\n setHeaderView(header);\n }\n }\n return mHeaderView;\n }\n\n /**\n * Set the Header view.\n *\n * <p>设置Header视图\n *\n * @param header Header view\n */\n public void setHeaderView(@NonNull IRefreshView header) {\n if (header.getType() != IRefreshView.TYPE_HEADER) {\n throw new IllegalArgumentException(\"Wrong type, HeaderView type must be TYPE_HEADER\");\n }\n if (header == mHeaderView) {\n return;\n }\n if (mHeaderView != null) {\n removeView(mHeaderView.getView());\n mHeaderView = null;\n }\n final View view = header.getView();\n mViewsZAxisNeedReset = true;\n addView(view, -1, view.getLayoutParams());\n }\n\n /**\n * Set the content view.\n *\n * <p>设置内容视图\n *\n * @param content Content view\n */\n public void setContentView(View content) {\n if (mTargetView == content) {\n return;\n }\n mContentResId = View.NO_ID;\n final int count = getChildCount();\n for (int i = 0; i < count; i++) {\n final View child = getChildAt(i);\n if (child == content) {\n mTargetView = content;\n return;\n }\n }\n if (mTargetView != null) {\n removeView(mTargetView);\n }\n ViewGroup.LayoutParams lp = content.getLayoutParams();\n if (lp == null) {\n lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);\n }\n mTargetView = content;\n mViewsZAxisNeedReset = true;\n addView(content, lp);\n }\n\n /**\n * Set the content view resource id.\n *\n * <p>设置内容视图\n *\n * @param id Content view resource id\n */\n public void setContentResId(@IdRes int id) {\n if (id != mContentResId) {\n mContentResId = id;\n mTargetView = null;\n ensureTargetView();\n }\n }\n\n /**\n * Reset scroller interpolator.\n *\n * <p>重置Scroller的插值器\n */\n public void resetScrollerInterpolator() {\n if (mSpringInterpolator != SPRING_INTERPOLATOR) {\n setSpringInterpolator(SPRING_INTERPOLATOR);\n }\n if (mSpringBackInterpolator != SPRING_BACK_INTERPOLATOR) {\n setSpringBackInterpolator(SPRING_BACK_INTERPOLATOR);\n }\n }\n\n /**\n * Set the scroller default interpolator.\n *\n * <p>设置Scroller的默认插值器\n *\n * @param interpolator Scroller interpolator\n */\n public void setSpringInterpolator(@NonNull Interpolator interpolator) {\n if (mSpringInterpolator != interpolator) {\n mSpringInterpolator = interpolator;\n if (mScrollChecker.isSpring()) {\n mScrollChecker.setInterpolator(interpolator);\n }\n }\n }\n\n /**\n * Set the scroller spring back interpolator.\n *\n * @param interpolator Scroller interpolator\n */\n public void setSpringBackInterpolator(@NonNull Interpolator interpolator) {\n if (mSpringBackInterpolator != interpolator) {\n mSpringBackInterpolator = interpolator;\n if (mScrollChecker.isSpringBack() || mScrollChecker.isFlingBack()) {\n mScrollChecker.setInterpolator(interpolator);\n }\n }\n }\n\n /**\n * Get the ScrollChecker current mode.\n *\n * @return the mode {@link Constants#SCROLLER_MODE_NONE}, {@link\n * Constants#SCROLLER_MODE_PRE_FLING}, {@link Constants#SCROLLER_MODE_FLING}, {@link\n * Constants#SCROLLER_MODE_CALC_FLING}, {@link Constants#SCROLLER_MODE_FLING_BACK}, {@link\n * Constants#SCROLLER_MODE_SPRING}, {@link Constants#SCROLLER_MODE_SPRING_BACK}.\n */\n public byte getScrollMode() {\n return mScrollChecker.mMode;\n }\n\n @Override\n protected ViewGroup.LayoutParams generateDefaultLayoutParams() {\n return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);\n }\n\n @Override\n protected boolean checkLayoutParams(ViewGroup.LayoutParams lp) {\n return lp instanceof LayoutParams;\n }\n\n @Override\n protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) {\n if (lp instanceof LayoutParams) {\n return lp;\n } else if (lp instanceof MarginLayoutParams) {\n return new LayoutParams((MarginLayoutParams) lp);\n } else {\n return new LayoutParams(lp);\n }\n }\n\n @Override\n public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {\n return new LayoutParams(getContext(), attrs);\n }\n\n /**\n * Set the pinned header view resource id\n *\n * @param resId Resource id\n */\n public void setStickyHeaderResId(@IdRes int resId) {\n if (mStickyHeaderResId != resId) {\n mStickyHeaderResId = resId;\n mStickyHeaderView = null;\n ensureTargetView();\n }\n }\n\n /**\n * Set the pinned footer view resource id\n *\n * @param resId Resource id\n */\n public void setStickyFooterResId(@IdRes int resId) {\n if (mStickyFooterResId != resId) {\n mStickyFooterResId = resId;\n mStickyFooterView = null;\n ensureTargetView();\n }\n }\n\n public boolean onFling(float vx, final float vy, boolean nested) {\n if (sDebug) {\n Log.d(\n TAG,\n String.format(\n \"onFling() velocityX: %f, velocityY: %f, nested: %b\", vx, vy, nested));\n }\n if ((isNeedInterceptTouchEvent() || isCanNotAbortOverScrolling())) {\n return true;\n }\n if (mPreventForAnotherDirection) {\n return nested && dispatchNestedPreFling(-vx, -vy);\n }\n float realVelocity = isVerticalOrientation() ? vy : vx;\n if (!mIndicator.isAlreadyHere(IIndicator.START_POS)) {\n if (!isEnabledPinContentView()) {\n if (Math.abs(realVelocity) > 2000) {\n if ((realVelocity > 0 && isMovingHeader())\n || (realVelocity < 0 && isMovingFooter())) {\n if (isEnabledOverScroll()) {\n if (isDisabledLoadMoreWhenContentNotFull()\n && !isNotYetInEdgeCannotMoveFooter()\n && !isNotYetInEdgeCannotMoveHeader()) {\n return true;\n }\n boolean invert = realVelocity < 0;\n realVelocity = (float) Math.pow(Math.abs(realVelocity), .5f);\n mScrollChecker.startPreFling(invert ? -realVelocity : realVelocity);\n }\n } else {\n if (mScrollChecker.getFinalY(realVelocity) > mIndicator.getCurrentPos()) {\n if (!isEnabledPerformFreshWhenFling()) {\n mScrollChecker.startPreFling(realVelocity);\n } else if (isMovingHeader()\n && (isDisabledPerformRefresh()\n || mIndicator.getCurrentPos()\n < mIndicator.getOffsetToRefresh())) {\n mScrollChecker.startPreFling(realVelocity);\n } else if (isMovingFooter()\n && (isDisabledPerformLoadMore()\n || mIndicator.getCurrentPos()\n < mIndicator.getOffsetToLoadMore())) {\n mScrollChecker.startPreFling(realVelocity);\n }\n }\n }\n }\n return true;\n }\n if (nested) {\n return dispatchNestedPreFling(-vx, -vy);\n } else {\n return false;\n }\n } else {\n tryToResetMovingStatus();\n if (isEnabledOverScroll()\n && (!isEnabledPinContentView()\n || ((realVelocity >= 0 || !isDisabledLoadMore())\n && (realVelocity <= 0 || !isDisabledRefresh())))) {\n if (isDisabledLoadMoreWhenContentNotFull()\n && realVelocity < 0\n && !isNotYetInEdgeCannotMoveHeader()\n && !isNotYetInEdgeCannotMoveFooter()) {\n return nested && dispatchNestedPreFling(-vx, -vy);\n }\n mScrollChecker.startFling(realVelocity);\n if (!nested && isEnabledOldTouchHandling()) {\n if (mDelayToDispatchNestedFling == null)\n mDelayToDispatchNestedFling = new DelayToDispatchNestedFling();\n mDelayToDispatchNestedFling.mLayout = this;\n mDelayToDispatchNestedFling.mVelocity = (int) realVelocity;\n ViewCompat.postOnAnimation(this, mDelayToDispatchNestedFling);\n invalidate();\n return true;\n }\n }\n invalidate();\n }\n return nested && dispatchNestedPreFling(-vx, -vy);\n }\n\n @Override\n public boolean onStartNestedScroll(\n @NonNull View child, @NonNull View target, int nestedScrollAxes) {\n return onStartNestedScroll(child, target, nestedScrollAxes, ViewCompat.TYPE_TOUCH);\n }\n\n @Override\n public boolean onStartNestedScroll(\n @NonNull View child, @NonNull View target, int axes, int type) {\n if (sDebug) {\n Log.d(TAG, String.format(\"onStartNestedScroll(): axes: %d, type: %d\", axes, type));\n }\n return isEnabled()\n && isNestedScrollingEnabled()\n && mTargetView != null\n && (axes & getNestedScrollAxes()) != 0\n && !(type == ViewCompat.TYPE_NON_TOUCH && !isEnabledOverScroll());\n }\n\n @Override\n public void onNestedScrollAccepted(@NonNull View child, @NonNull View target, int axes) {\n onNestedScrollAccepted(child, target, axes, ViewCompat.TYPE_TOUCH);\n }\n\n @Override\n public void onNestedScrollAccepted(\n @NonNull View child, @NonNull View target, int axes, int type) {\n if (sDebug) {\n Log.d(TAG, String.format(\"onNestedScrollAccepted(): axes: %d, type: %d\", axes, type));\n }\n // Reset the counter of how much leftover scroll needs to be consumed.\n mNestedScrollingParentHelper.onNestedScrollAccepted(child, target, axes, type);\n // Dispatch up to the nested parent\n startNestedScroll(axes & getNestedScrollAxes(), type);\n mNestedTouchScrolling = type == ViewCompat.TYPE_TOUCH;\n mLastNestedType = type;\n mNestedScrolling = true;\n }\n\n @Override\n public int getNestedScrollAxes() {\n return mLayoutManager == null\n ? ViewCompat.SCROLL_AXIS_NONE\n : mLayoutManager.getOrientation() == LayoutManager.VERTICAL\n ? ViewCompat.SCROLL_AXIS_VERTICAL\n : ViewCompat.SCROLL_AXIS_HORIZONTAL;\n }\n\n @Override\n public void onNestedPreScroll(@NonNull View target, int dx, int dy, @NonNull int[] consumed) {\n onNestedPreScroll(target, dx, dy, consumed, ViewCompat.TYPE_TOUCH);\n }\n\n @Override\n public void onNestedPreScroll(\n @NonNull View target, int dx, int dy, @NonNull int[] consumed, int type) {\n final boolean isVerticalOrientation = isVerticalOrientation();\n if (type == ViewCompat.TYPE_TOUCH) {\n if (tryToFilterTouchEvent(null)) {\n if (isVerticalOrientation) {\n consumed[1] = dy;\n } else {\n consumed[0] = dx;\n }\n } else {\n mScrollChecker.stop();\n final int distance = isVerticalOrientation ? dy : dx;\n if (distance > 0\n && !isDisabledRefresh()\n && !(isEnabledPinRefreshViewWhileLoading() && isRefreshing())\n && !isNotYetInEdgeCannotMoveHeader()) {\n if (!mIndicator.isAlreadyHere(IIndicator.START_POS) && isMovingHeader()) {\n mIndicatorSetter.onFingerMove(\n mIndicator.getLastMovePoint()[0] - dx,\n mIndicator.getLastMovePoint()[1] - dy);\n moveHeaderPos(mIndicator.getOffset());\n if (isVerticalOrientation) {\n consumed[1] = dy;\n } else {\n consumed[0] = dx;\n }\n } else {\n if (isVerticalOrientation) {\n mIndicatorSetter.onFingerMove(\n mIndicator.getLastMovePoint()[0] - dx,\n mIndicator.getLastMovePoint()[1]);\n } else {\n mIndicatorSetter.onFingerMove(\n mIndicator.getLastMovePoint()[0],\n mIndicator.getLastMovePoint()[1] - dy);\n }\n }\n } else if (distance < 0\n && !isDisabledLoadMore()\n && !(isEnabledPinRefreshViewWhileLoading() && isLoadingMore())\n && !isNotYetInEdgeCannotMoveFooter()) {\n if (!mIndicator.isAlreadyHere(IIndicator.START_POS) && isMovingFooter()) {\n mIndicatorSetter.onFingerMove(\n mIndicator.getLastMovePoint()[0] - dx,\n mIndicator.getLastMovePoint()[1] - dy);\n moveFooterPos(mIndicator.getOffset());\n if (isVerticalOrientation) {\n consumed[1] = dy;\n } else {\n consumed[0] = dx;\n }\n } else {\n if (isVerticalOrientation) {\n mIndicatorSetter.onFingerMove(\n mIndicator.getLastMovePoint()[0] - dx,\n mIndicator.getLastMovePoint()[1]);\n } else {\n mIndicatorSetter.onFingerMove(\n mIndicator.getLastMovePoint()[0],\n mIndicator.getLastMovePoint()[1] - dy);\n }\n }\n }\n }\n tryToResetMovingStatus();\n }\n // Now let our nested parent consume the leftovers\n final int[] parentConsumed = mParentScrollConsumed;\n parentConsumed[0] = 0;\n parentConsumed[1] = 0;\n if (dispatchNestedPreScroll(\n dx - consumed[0], dy - consumed[1], parentConsumed, null, type)) {\n consumed[0] += parentConsumed[0];\n consumed[1] += parentConsumed[1];\n } else if (type == ViewCompat.TYPE_NON_TOUCH) {\n if (!isMovingContent() && !isEnabledPinContentView()) {\n if (isVerticalOrientation) {\n parentConsumed[1] = dy;\n } else {\n parentConsumed[0] = dx;\n }\n consumed[0] += parentConsumed[0];\n consumed[1] += parentConsumed[1];\n }\n }\n if (sDebug) {\n Log.d(\n TAG,\n String.format(\n \"onNestedPreScroll(): dx: %d, dy: %d, consumed: %s, type: %d\",\n dx, dy, Arrays.toString(consumed), type));\n }\n }\n\n @Override\n public void onNestedScroll(\n @NonNull View target,\n int dxConsumed,\n int dyConsumed,\n int dxUnconsumed,\n int dyUnconsumed) {\n onNestedScroll(\n target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, ViewCompat.TYPE_TOUCH);\n }\n\n @Override\n public void onNestedScroll(\n @NonNull View target,\n int dxConsumed,\n int dyConsumed,\n int dxUnconsumed,\n int dyUnconsumed,\n int type) {\n mCachedIntPoint[0] = 0;\n mCachedIntPoint[1] = 0;\n onNestedScroll(\n target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type, mCachedIntPoint);\n }\n\n @Override\n public void onNestedScroll(\n @NonNull View target,\n int dxConsumed,\n int dyConsumed,\n int dxUnconsumed,\n int dyUnconsumed,\n int type,\n @NonNull int[] consumed) {\n // Dispatch up to the nested parent first\n dispatchNestedScroll(\n dxConsumed,\n dyConsumed,\n dxUnconsumed,\n dyUnconsumed,\n mParentOffsetInWindow,\n type,\n consumed);\n if (sDebug) {\n Log.d(\n TAG,\n String.format(\n \"onNestedScroll(): dxConsumed: %d, dyConsumed: %d, dxUnconsumed: %d\"\n + \" dyUnconsumed: %d, type: %d, consumed: %s\",\n dxConsumed,\n dyConsumed,\n dxUnconsumed,\n dyUnconsumed,\n type,\n Arrays.toString(consumed)));\n }\n final boolean isVerticalOrientation = isVerticalOrientation();\n if (isVerticalOrientation) {\n if (dyUnconsumed == 0 || consumed[1] == dyUnconsumed) {\n onNestedScrollChanged(true);\n return;\n }\n } else {\n if (dxUnconsumed == 0 || consumed[0] == dxUnconsumed) {\n onNestedScrollChanged(true);\n return;\n }\n }\n if (type == ViewCompat.TYPE_TOUCH) {\n if (tryToFilterTouchEvent(null)) {\n return;\n }\n final int dx = dxUnconsumed + mParentOffsetInWindow[0] - consumed[0];\n final int dy = dyUnconsumed + mParentOffsetInWindow[1] - consumed[1];\n final int distance = isVerticalOrientation ? dy : dx;\n if (distance < 0\n && !isDisabledRefresh()\n && !isNotYetInEdgeCannotMoveHeader()\n && !(isEnabledPinRefreshViewWhileLoading() && isRefreshing())) {\n mIndicatorSetter.onFingerMove(\n mIndicator.getLastMovePoint()[0] - dx,\n mIndicator.getLastMovePoint()[1] - dy);\n moveHeaderPos(mIndicator.getOffset());\n if (isVerticalOrientation) {\n consumed[1] += dy;\n } else {\n consumed[0] += dx;\n }\n } else if (distance > 0\n && !isDisabledLoadMore()\n && !isNotYetInEdgeCannotMoveFooter()\n && !(isDisabledLoadMoreWhenContentNotFull()\n && !isNotYetInEdgeCannotMoveHeader()\n && mIndicator.isAlreadyHere(IIndicator.START_POS))\n && !(isEnabledPinRefreshViewWhileLoading() && isLoadingMore())) {\n mIndicatorSetter.onFingerMove(\n mIndicator.getLastMovePoint()[0] - dx,\n mIndicator.getLastMovePoint()[1] - dy);\n moveFooterPos(mIndicator.getOffset());\n if (isVerticalOrientation) {\n consumed[1] += dy;\n } else {\n consumed[0] += dx;\n }\n }\n tryToResetMovingStatus();\n }\n if (dxConsumed != 0 || dyConsumed != 0 || consumed[0] != 0 || consumed[1] != 0) {\n onNestedScrollChanged(true);\n }\n }\n\n @Override\n public void onStopNestedScroll(@NonNull View target) {\n onStopNestedScroll(target, ViewCompat.TYPE_TOUCH);\n }\n\n @Override\n public void onStopNestedScroll(@NonNull View target, int type) {\n if (sDebug) {\n Log.d(TAG, String.format(\"onStopNestedScroll() type: %d\", type));\n }\n mNestedScrollingParentHelper.onStopNestedScroll(target, type);\n if (mLastNestedType == type) {\n mNestedScrolling = false;\n }\n mNestedTouchScrolling = false;\n mIsInterceptTouchEventInOnceTouch = isNeedInterceptTouchEvent();\n mIsLastOverScrollCanNotAbort = isCanNotAbortOverScrolling();\n // Dispatch up our nested parent\n getScrollingChildHelper().stopNestedScroll(type);\n if (!isAutoRefresh() && type == ViewCompat.TYPE_TOUCH && !mLastEventIsActionDown) {\n mIndicatorSetter.onFingerUp();\n onFingerUp();\n }\n onNestedScrollChanged(true);\n }\n\n @Override\n public boolean isNestedScrollingEnabled() {\n return getScrollingChildHelper().isNestedScrollingEnabled();\n }\n\n @Override\n public void setNestedScrollingEnabled(boolean enabled) {\n getScrollingChildHelper().setNestedScrollingEnabled(enabled);\n }\n\n @Override\n public boolean startNestedScroll(int axes) {\n return getScrollingChildHelper().startNestedScroll(axes);\n }\n\n @Override\n public boolean startNestedScroll(int axes, int type) {\n return getScrollingChildHelper().startNestedScroll(axes, type);\n }\n\n @Override\n public void stopNestedScroll() {\n stopNestedScroll(ViewCompat.TYPE_TOUCH);\n }\n\n @Override\n public void stopNestedScroll(int type) {\n if (sDebug) {\n Log.d(TAG, String.format(\"stopNestedScroll() type: %d\", type));\n }\n final View targetView = getScrollTargetView();\n if (targetView != null) {\n ViewCompat.stopNestedScroll(targetView, type);\n }\n getScrollingChildHelper().stopNestedScroll(type);\n }\n\n @Override\n public boolean hasNestedScrollingParent() {\n return getScrollingChildHelper().hasNestedScrollingParent();\n }\n\n @Override\n public boolean hasNestedScrollingParent(int type) {\n return getScrollingChildHelper().hasNestedScrollingParent(type);\n }\n\n @Override\n public boolean dispatchNestedScroll(\n int dxConsumed,\n int dyConsumed,\n int dxUnconsumed,\n int dyUnconsumed,\n int[] offsetInWindow) {\n return getScrollingChildHelper()\n .dispatchNestedScroll(\n dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, offsetInWindow);\n }\n\n @Override\n public boolean dispatchNestedScroll(\n int dxConsumed,\n int dyConsumed,\n int dxUnconsumed,\n int dyUnconsumed,\n @Nullable int[] offsetInWindow,\n int type) {\n return getScrollingChildHelper()\n .dispatchNestedScroll(\n dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, offsetInWindow, type);\n }\n\n @Override\n public void dispatchNestedScroll(\n int dxConsumed,\n int dyConsumed,\n int dxUnconsumed,\n int dyUnconsumed,\n @Nullable int[] offsetInWindow,\n int type,\n @NonNull int[] consumed) {\n getScrollingChildHelper()\n .dispatchNestedScroll(\n dxConsumed,\n dyConsumed,\n dxUnconsumed,\n dyUnconsumed,\n offsetInWindow,\n type,\n consumed);\n }\n\n @Override\n public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) {\n return getScrollingChildHelper().dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow);\n }\n\n @Override\n public boolean dispatchNestedPreScroll(\n int dx, int dy, @Nullable int[] consumed, @Nullable int[] offsetInWindow, int type) {\n return getScrollingChildHelper()\n .dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow, type);\n }\n\n @Override\n public boolean onNestedPreFling(@NonNull View target, float velocityX, float velocityY) {\n return onFling(-velocityX, -velocityY, true);\n }\n\n @Override\n public boolean onNestedFling(\n @NonNull View target, float velocityX, float velocityY, boolean consumed) {\n return dispatchNestedFling(velocityX, velocityY, consumed);\n }\n\n @Override\n public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {\n return getScrollingChildHelper().dispatchNestedFling(velocityX, velocityY, consumed);\n }\n\n @Override\n public boolean dispatchNestedPreFling(float velocityX, float velocityY) {\n return getScrollingChildHelper().dispatchNestedPreFling(velocityX, velocityY);\n }\n\n @Override\n public void computeScroll() {\n if (mNestedScrolling || !isMovingContent()) {\n return;\n }\n onNestedScrollChanged(true);\n }\n\n @Override\n public boolean canScrollVertically(int direction) {\n if (isVerticalOrientation()) {\n if (mAppBarLayoutUtil == null || mAppBarLayoutUtil != mInEdgeCanMoveHeaderCallBack) {\n if (direction < 0) {\n return super.canScrollVertically(direction) || isNotYetInEdgeCannotMoveHeader();\n } else {\n return super.canScrollVertically(direction) || isNotYetInEdgeCannotMoveFooter();\n }\n }\n }\n return super.canScrollVertically(direction);\n }\n\n @Override\n public boolean canScrollHorizontally(int direction) {\n if (!isVerticalOrientation()) {\n if (direction < 0) {\n return super.canScrollHorizontally(direction) || isNotYetInEdgeCannotMoveHeader();\n } else {\n return super.canScrollHorizontally(direction) || isNotYetInEdgeCannotMoveFooter();\n }\n }\n return super.canScrollHorizontally(direction);\n }\n\n public void onNestedScrollChanged(boolean compute) {\n if (mNeedFilterScrollEvent) {\n return;\n }\n tryScrollToPerformAutoRefresh();\n if (compute) {\n mScrollChecker.computeScrollOffset();\n }\n }\n\n public boolean isVerticalOrientation() {\n return mLayoutManager == null || mLayoutManager.getOrientation() == LayoutManager.VERTICAL;\n }\n\n /** Check the Z-Axis relationships of the views need to be rearranged */\n protected void checkViewsZAxisNeedReset() {\n final int count = getChildCount();\n if (mViewsZAxisNeedReset && count > 0 && (mHeaderView != null || mFooterView != null)) {\n mCachedViews.clear();\n if (mHeaderView != null && !isEnabledHeaderDrawerStyle()) {\n mCachedViews.add(mHeaderView.getView());\n }\n if (mFooterView != null && !isEnabledFooterDrawerStyle()) {\n mCachedViews.add(mFooterView.getView());\n }\n for (int i = count - 1; i >= 0; i--) {\n View view = getChildAt(i);\n if (!(view instanceof IRefreshView)) {\n mCachedViews.add(view);\n }\n }\n final int viewCount = mCachedViews.size();\n if (viewCount > 0) {\n for (int i = viewCount - 1; i >= 0; i--) {\n bringChildToFront(mCachedViews.get(i));\n }\n }\n mCachedViews.clear();\n }\n mViewsZAxisNeedReset = false;\n }\n\n protected void reset() {\n if (mStatus != SR_STATUS_INIT) {\n if (isRefreshing() || isLoadingMore()) {\n notifyUIRefreshComplete(false, false, true);\n }\n if (mHeaderView != null) {\n mHeaderView.onReset(this);\n }\n if (mFooterView != null) {\n mFooterView.onReset(this);\n }\n if (!mIndicator.isAlreadyHere(IIndicator.START_POS)) {\n mScrollChecker.scrollTo(IIndicator.START_POS, 0);\n }\n mScrollChecker.stop();\n mScrollChecker.setInterpolator(mSpringInterpolator);\n final byte old = mStatus;\n mStatus = SR_STATUS_INIT;\n notifyStatusChanged(old, mStatus);\n mAutomaticActionTriggered = true;\n mLayoutManager.resetLayout(\n mHeaderView, mFooterView, mStickyHeaderView, mStickyFooterView, mTargetView);\n removeCallbacks(mDelayToRefreshComplete);\n removeCallbacks(mDelayToDispatchNestedFling);\n removeCallbacks(mDelayToPerformAutoRefresh);\n if (sDebug) {\n Log.d(TAG, \"reset()\");\n }\n }\n }\n\n protected void tryToPerformAutoRefresh() {\n if (!mAutomaticActionTriggered) {\n if (sDebug) Log.d(TAG, \"tryToPerformAutoRefresh()\");\n if (isHeaderInProcessing() && isMovingHeader()) {\n if (mHeaderView == null || mIndicator.getHeaderHeight() <= 0) {\n return;\n }\n scrollToTriggeredAutomatic(true);\n } else if (isFooterInProcessing() && isMovingFooter()) {\n if (mFooterView == null || mIndicator.getFooterHeight() <= 0) {\n return;\n }\n scrollToTriggeredAutomatic(false);\n }\n }\n }\n\n private void ensureTargetView() {\n boolean ensureStickyHeader = mStickyHeaderView == null && mStickyHeaderResId != NO_ID;\n boolean ensureStickyFooter = mStickyFooterView == null && mStickyFooterResId != NO_ID;\n boolean ensureTarget = mTargetView == null && mContentResId != NO_ID;\n final int count = getChildCount();\n if (ensureStickyHeader || ensureStickyFooter || ensureTarget) {\n for (int i = count - 1; i >= 0; i--) {\n View child = getChildAt(i);\n if (ensureStickyHeader && child.getId() == mStickyHeaderResId) {\n mStickyHeaderView = child;\n ensureStickyHeader = false;\n } else if (ensureStickyFooter && child.getId() == mStickyFooterResId) {\n mStickyFooterView = child;\n ensureStickyFooter = false;\n } else if (ensureTarget) {\n if (mContentResId == child.getId()) {\n mTargetView = child;\n View view = ensureScrollTargetView(child, true, 0, 0);\n if (view != null && view != child) {\n mAutoFoundScrollTargetView = view;\n }\n ensureTarget = false;\n } else if (child instanceof ViewGroup) {\n final View view =\n foundViewInViewGroupById((ViewGroup) child, mContentResId);\n if (view != null) {\n mTargetView = child;\n mScrollTargetView = view;\n ensureTarget = false;\n }\n }\n } else if (!ensureStickyHeader && !ensureStickyFooter) {\n break;\n }\n }\n }\n if (mTargetView == null) {\n for (int i = count - 1; i >= 0; i--) {\n View child = getChildAt(i);\n if (child.getVisibility() == VISIBLE\n && !(child instanceof IRefreshView)\n && child != mStickyHeaderView\n && child != mStickyFooterView) {\n View view = ensureScrollTargetView(child, true, 0, 0);\n if (view != null) {\n mTargetView = child;\n if (view != child) {\n mAutoFoundScrollTargetView = view;\n }\n break;\n } else {\n mTargetView = child;\n break;\n }\n }\n }\n } else if (mTargetView.getParent() == null) {\n mTargetView = null;\n ensureTargetView();\n mLayoutManager.offsetChild(\n mHeaderView, mFooterView, mStickyHeaderView, mStickyFooterView, mTargetView, 0);\n return;\n }\n mHeaderView = getHeaderView();\n mFooterView = getFooterView();\n }\n\n /**\n * Returns true if a child view contains the specified point when transformed into its\n * coordinate space.\n *\n * @see ViewGroup source code\n */\n protected boolean isTransformedTouchPointInView(float x, float y, ViewGroup group, View child) {\n if (child.getVisibility() != VISIBLE\n || child.getAnimation() != null\n || child instanceof IRefreshView) {\n return false;\n }\n mCachedFloatPoint[0] = x;\n mCachedFloatPoint[1] = y;\n transformPointToViewLocal(group, mCachedFloatPoint, child);\n final boolean isInView =\n mCachedFloatPoint[0] >= 0\n && mCachedFloatPoint[1] >= 0\n && mCachedFloatPoint[0] < child.getWidth()\n && mCachedFloatPoint[1] < child.getHeight();\n if (isInView) {\n mCachedFloatPoint[0] = mCachedFloatPoint[0] - x;\n mCachedFloatPoint[1] = mCachedFloatPoint[1] - y;\n }\n return isInView;\n }\n\n public void transformPointToViewLocal(ViewGroup group, float[] point, View child) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1\n && Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) {\n group.transformPointToViewLocal(point, child);\n } else {\n // When the system version is lower than LOLLIPOP_MR1, the system source code has no\n // transformPointToViewLocal method. We need to be compatible with it.\n // When the system version is larger than R, the transformPointToViewLocal method has\n // been unavailable. We need to be compatible with it.\n point[0] += group.getScrollX() - child.getLeft();\n point[1] += group.getScrollY() - child.getTop();\n Matrix matrix = child.getMatrix();\n if (!matrix.isIdentity()) {\n mCachedMatrix.reset();\n if (matrix.invert(mCachedMatrix)) {\n mCachedMatrix.mapPoints(point);\n }\n }\n }\n }\n\n protected View ensureScrollTargetView(View target, boolean noTransform, float x, float y) {\n if (target instanceof IRefreshView\n || target.getVisibility() != VISIBLE\n || target.getAnimation() != null) {\n return null;\n }\n if (isScrollingView(target)) {\n return target;\n }\n if (target instanceof ViewGroup) {\n ViewGroup group = (ViewGroup) target;\n final int count = group.getChildCount();\n for (int i = count - 1; i >= 0; i--) {\n View child = group.getChildAt(i);\n if (noTransform || isTransformedTouchPointInView(x, y, group, child)) {\n View view =\n ensureScrollTargetView(\n child,\n noTransform,\n x + mCachedFloatPoint[0],\n y + mCachedFloatPoint[1]);\n if (view != null) {\n return view;\n }\n }\n }\n }\n return null;\n }\n\n protected boolean isWrappedByScrollingView(ViewParent parent) {\n if (parent instanceof View) {\n if (isScrollingView((View) parent)) {\n return true;\n }\n return isWrappedByScrollingView(parent.getParent());\n }\n return false;\n }\n\n protected boolean isScrollingView(View view) {\n return ScrollCompat.isScrollingView(view);\n }\n\n protected boolean processDispatchTouchEvent(MotionEvent ev) {\n final int action = ev.getAction() & MotionEvent.ACTION_MASK;\n if (sDebug) {\n Log.d(TAG, String.format(\"processDispatchTouchEvent(): action: %d\", action));\n }\n if (mVelocityTracker == null) {\n mVelocityTracker = VelocityTracker.obtain();\n }\n mVelocityTracker.addMovement(ev);\n final boolean oldTouchHanding = isEnabledOldTouchHandling();\n switch (action) {\n case MotionEvent.ACTION_UP:\n final int pointerId = ev.getPointerId(0);\n mVelocityTracker.computeCurrentVelocity(1000, mMaximumFlingVelocity);\n float vy = mVelocityTracker.getYVelocity(pointerId);\n float vx = mVelocityTracker.getXVelocity(pointerId);\n if (Math.abs(vx) >= mMinimumFlingVelocity\n || Math.abs(vy) >= mMinimumFlingVelocity) {\n final boolean handler = onFling(vx, vy, false);\n final View targetView = getScrollTargetView();\n if (handler\n && !ViewCatcherUtil.isCoordinatorLayout(mTargetView)\n && targetView != null\n && !ViewCatcherUtil.isViewPager(targetView)\n && !(targetView.getParent() instanceof View\n && ViewCatcherUtil.isViewPager(\n (View) targetView.getParent()))) {\n ev.setAction(MotionEvent.ACTION_CANCEL);\n }\n }\n case MotionEvent.ACTION_CANCEL:\n mIndicatorSetter.onFingerUp();\n mPreventForAnotherDirection = false;\n mDealAnotherDirectionMove = false;\n if (isNeedFilterTouchEvent()) {\n mIsInterceptTouchEventInOnceTouch = false;\n if (mIsLastOverScrollCanNotAbort\n && mIndicator.isAlreadyHere(IIndicator.START_POS)) {\n mScrollChecker.stop();\n }\n mIsLastOverScrollCanNotAbort = false;\n } else {\n mIsInterceptTouchEventInOnceTouch = false;\n mIsLastOverScrollCanNotAbort = false;\n if (mIndicator.hasLeftStartPosition()) {\n onFingerUp();\n } else {\n notifyFingerUp();\n }\n }\n mHasSendCancelEvent = false;\n mVelocityTracker.clear();\n break;\n case MotionEvent.ACTION_POINTER_UP:\n final int pointerIndex =\n (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK)\n >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;\n if (ev.getPointerId(pointerIndex) == mTouchPointerId) {\n // Pick a new pointer to pick up the slack.\n final int newIndex = pointerIndex == 0 ? 1 : 0;\n mTouchPointerId = ev.getPointerId(newIndex);\n mIndicatorSetter.onFingerMove(ev.getX(newIndex), ev.getY(newIndex));\n }\n final int count = ev.getPointerCount();\n mVelocityTracker.computeCurrentVelocity(1000, mMaximumFlingVelocity);\n final int upIndex = ev.getActionIndex();\n final int id1 = ev.getPointerId(upIndex);\n final float x1 = mVelocityTracker.getXVelocity(id1);\n final float y1 = mVelocityTracker.getYVelocity(id1);\n for (int i = 0; i < count; i++) {\n if (i == upIndex) continue;\n final int id2 = ev.getPointerId(i);\n final float x = x1 * mVelocityTracker.getXVelocity(id2);\n final float y = y1 * mVelocityTracker.getYVelocity(id2);\n final float dot = x + y;\n if (dot < 0) {\n mVelocityTracker.clear();\n break;\n }\n }\n break;\n case MotionEvent.ACTION_POINTER_DOWN:\n mTouchPointerId = ev.getPointerId(ev.getActionIndex());\n mIndicatorSetter.onFingerMove(\n ev.getX(ev.getActionIndex()), ev.getY(ev.getActionIndex()));\n break;\n case MotionEvent.ACTION_DOWN:\n mIndicatorSetter.onFingerUp();\n mTouchPointerId = ev.getPointerId(0);\n mIndicatorSetter.onFingerDown(ev.getX(), ev.getY());\n mIsInterceptTouchEventInOnceTouch = isNeedInterceptTouchEvent();\n mIsLastOverScrollCanNotAbort = isCanNotAbortOverScrolling();\n if (!isNeedFilterTouchEvent()) {\n mScrollChecker.stop();\n }\n mHasSendDownEvent = false;\n mPreventForAnotherDirection = false;\n if (mScrollTargetView == null) {\n View view = ensureScrollTargetView(this, false, ev.getX(), ev.getY());\n if (view != null && mTargetView != view && mAutoFoundScrollTargetView != view) {\n mAutoFoundScrollTargetView = view;\n }\n } else {\n mAutoFoundScrollTargetView = null;\n }\n removeCallbacks(mDelayToDispatchNestedFling);\n dispatchTouchEventSuper(ev);\n return true;\n case MotionEvent.ACTION_MOVE:\n final int index = ev.findPointerIndex(mTouchPointerId);\n if (index < 0) {\n Log.e(\n TAG,\n String.format(\n \"Error processing scroll; pointer index for id %d not found. Did any MotionEvents get skipped?\",\n mTouchPointerId));\n return super.dispatchTouchEvent(ev);\n }\n if (!mIndicator.hasTouched()) {\n mIndicatorSetter.onFingerDown(ev.getX(index), ev.getY(index));\n }\n mLastMoveEvent = ev;\n if (tryToFilterTouchEvent(ev)) {\n return true;\n }\n tryToResetMovingStatus();\n if (!mDealAnotherDirectionMove) {\n final float[] pressDownPoint = mIndicator.getFingerDownPoint();\n final float offsetX = ev.getX(index) - pressDownPoint[0];\n final float offsetY = ev.getY(index) - pressDownPoint[1];\n tryToDealAnotherDirectionMove(offsetX, offsetY);\n if (mDealAnotherDirectionMove && oldTouchHanding) {\n mIndicatorSetter.onFingerDown(\n ev.getX(index) - offsetX / 10, ev.getY(index) - offsetY / 10);\n }\n final ViewParent parent = getParent();\n if (!isWrappedByScrollingView(parent)) {\n parent.requestDisallowInterceptTouchEvent(true);\n }\n }\n final boolean canNotChildScrollDown = !isNotYetInEdgeCannotMoveFooter();\n final boolean canNotChildScrollUp = !isNotYetInEdgeCannotMoveHeader();\n if (mPreventForAnotherDirection) {\n if (mDealAnotherDirectionMove && isMovingHeader() && !canNotChildScrollUp) {\n mPreventForAnotherDirection = false;\n } else if (mDealAnotherDirectionMove\n && isMovingFooter()\n && !canNotChildScrollDown) {\n mPreventForAnotherDirection = false;\n } else {\n return super.dispatchTouchEvent(ev);\n }\n }\n mIndicatorSetter.onFingerMove(ev.getX(index), ev.getY(index));\n final float offset = mIndicator.getOffset();\n boolean movingDown = offset > 0;\n if (!movingDown\n && isDisabledLoadMoreWhenContentNotFull()\n && mIndicator.isAlreadyHere(IIndicator.START_POS)\n && canNotChildScrollDown\n && canNotChildScrollUp) {\n return dispatchTouchEventSuper(ev);\n }\n boolean canMoveUp = isMovingHeader() && mIndicator.hasLeftStartPosition();\n boolean canMoveDown = isMovingFooter() && mIndicator.hasLeftStartPosition();\n boolean canHeaderMoveDown = canNotChildScrollUp && !isDisabledRefresh();\n boolean canFooterMoveUp = canNotChildScrollDown && !isDisabledLoadMore();\n if (!canMoveUp && !canMoveDown) {\n if ((movingDown && !canHeaderMoveDown) || (!movingDown && !canFooterMoveUp)) {\n if (isLoadingMore() && mIndicator.hasLeftStartPosition()) {\n moveFooterPos(offset);\n if (oldTouchHanding) {\n return true;\n }\n } else if (isRefreshing() && mIndicator.hasLeftStartPosition()) {\n moveHeaderPos(offset);\n if (oldTouchHanding) {\n return true;\n }\n }\n } else if (movingDown) {\n if (!isDisabledRefresh()) {\n moveHeaderPos(offset);\n if (oldTouchHanding) {\n return true;\n }\n }\n } else if (!isDisabledLoadMore()) {\n moveFooterPos(offset);\n if (oldTouchHanding) {\n return true;\n }\n }\n } else if (canMoveUp) {\n if (isDisabledRefresh()) {\n return dispatchTouchEventSuper(ev);\n }\n if ((!canHeaderMoveDown && movingDown)) {\n if (oldTouchHanding) {\n sendDownEvent(ev);\n return true;\n }\n return dispatchTouchEventSuper(ev);\n }\n moveHeaderPos(offset);\n if (oldTouchHanding) {\n return true;\n }\n } else {\n if (isDisabledLoadMore()) {\n return dispatchTouchEventSuper(ev);\n }\n if ((!canFooterMoveUp && !movingDown)) {\n if (oldTouchHanding) {\n sendDownEvent(ev);\n return true;\n }\n return dispatchTouchEventSuper(ev);\n }\n moveFooterPos(offset);\n if (oldTouchHanding) {\n return true;\n }\n }\n }\n return dispatchTouchEventSuper(ev);\n }\n\n protected void tryToDealAnotherDirectionMove(float offsetX, float offsetY) {\n if (isDisabledWhenAnotherDirectionMove()) {\n if ((Math.abs(offsetX) >= mTouchSlop && Math.abs(offsetX) > Math.abs(offsetY))) {\n mPreventForAnotherDirection = true;\n mDealAnotherDirectionMove = true;\n } else if (Math.abs(offsetX) < mTouchSlop && Math.abs(offsetY) < mTouchSlop) {\n mDealAnotherDirectionMove = false;\n mPreventForAnotherDirection = true;\n } else {\n mDealAnotherDirectionMove = true;\n mPreventForAnotherDirection = false;\n }\n } else {\n mPreventForAnotherDirection =\n Math.abs(offsetX) < mTouchSlop && Math.abs(offsetY) < mTouchSlop;\n if (!mPreventForAnotherDirection) {\n mDealAnotherDirectionMove = true;\n }\n }\n }\n\n protected boolean tryToFilterTouchEvent(MotionEvent ev) {\n if (mIsInterceptTouchEventInOnceTouch) {\n if ((!isAutoRefresh()\n && mIndicator.isAlreadyHere(IIndicator.START_POS)\n && !mScrollChecker.mIsScrolling)\n || (isAutoRefresh() && (isRefreshing() || isLoadingMore()))) {\n mScrollChecker.stop();\n if (ev != null) {\n makeNewTouchDownEvent(ev);\n }\n mIsInterceptTouchEventInOnceTouch = false;\n }\n return true;\n }\n if (mIsLastOverScrollCanNotAbort) {\n if (mIndicator.isAlreadyHere(IIndicator.START_POS) && !mScrollChecker.mIsScrolling) {\n if (ev != null) {\n makeNewTouchDownEvent(ev);\n }\n mIsLastOverScrollCanNotAbort = false;\n }\n return true;\n }\n if (mIsSpringBackCanNotBeInterrupted) {\n if (isEnabledNoMoreDataAndNoSpringBack()) {\n mIsSpringBackCanNotBeInterrupted = false;\n return false;\n }\n if (mIndicator.isAlreadyHere(IIndicator.START_POS) && !mScrollChecker.mIsScrolling) {\n if (ev != null) {\n makeNewTouchDownEvent(ev);\n }\n mIsSpringBackCanNotBeInterrupted = false;\n }\n return true;\n }\n return false;\n }\n\n private NestedScrollingChildHelper getScrollingChildHelper() {\n if (mNestedScrollingChildHelper == null) {\n mNestedScrollingChildHelper = new NestedScrollingChildHelper(this);\n }\n return mNestedScrollingChildHelper;\n }\n\n private void scrollToTriggeredAutomatic(boolean isRefresh) {\n if (sDebug) {\n Log.d(TAG, \"scrollToTriggeredAutomatic()\");\n }\n switch (mAutomaticAction) {\n case Constants.ACTION_NOTHING:\n if (isRefresh) {\n triggeredRefresh(false);\n } else {\n triggeredLoadMore(false);\n }\n break;\n case Constants.ACTION_NOTIFY:\n mFlag |= FLAG_AUTO_REFRESH;\n break;\n case Constants.ACTION_AT_ONCE:\n if (isRefresh) {\n triggeredRefresh(true);\n } else {\n triggeredLoadMore(true);\n }\n break;\n }\n int offset;\n if (isRefresh) {\n if (isEnabledKeepRefreshView()) {\n final int offsetToKeepHeaderWhileLoading =\n mIndicator.getOffsetToKeepHeaderWhileLoading();\n final int offsetToRefresh = mIndicator.getOffsetToRefresh();\n offset = Math.max(offsetToKeepHeaderWhileLoading, offsetToRefresh);\n } else {\n offset = mIndicator.getOffsetToRefresh();\n }\n } else {\n if (isEnabledKeepRefreshView()) {\n final int offsetToKeepFooterWhileLoading =\n mIndicator.getOffsetToKeepFooterWhileLoading();\n final int offsetToLoadMore = mIndicator.getOffsetToLoadMore();\n offset = Math.max(offsetToKeepFooterWhileLoading, offsetToLoadMore);\n } else {\n offset = mIndicator.getOffsetToLoadMore();\n }\n }\n mAutomaticActionTriggered = true;\n mScrollChecker.scrollTo(\n offset,\n mAutomaticActionUseSmoothScroll\n ? isRefresh ? mDurationToCloseHeader : mDurationToCloseFooter\n : 0);\n }\n\n protected boolean isNeedInterceptTouchEvent() {\n return (isEnabledInterceptEventWhileLoading() && (isRefreshing() || isLoadingMore()))\n || mAutomaticActionUseSmoothScroll;\n }\n\n protected boolean isNeedFilterTouchEvent() {\n return mIsLastOverScrollCanNotAbort\n || mIsSpringBackCanNotBeInterrupted\n || mIsInterceptTouchEventInOnceTouch;\n }\n\n protected boolean isCanNotAbortOverScrolling() {\n return ((mScrollChecker.isFling()\n || mScrollChecker.isFlingBack()\n || mScrollChecker.isPreFling())\n && (((isMovingHeader() && isDisabledRefresh()))\n || (isMovingFooter() && isDisabledLoadMore())));\n }\n\n public boolean isNotYetInEdgeCannotMoveHeader() {\n final View targetView = getScrollTargetView();\n if (mInEdgeCanMoveHeaderCallBack != null) {\n return mInEdgeCanMoveHeaderCallBack.isNotYetInEdgeCannotMoveHeader(\n this, targetView, mHeaderView);\n }\n return targetView != null && targetView.canScrollVertically(-1);\n }\n\n public boolean isNotYetInEdgeCannotMoveFooter() {\n final View targetView = getScrollTargetView();\n if (mInEdgeCanMoveFooterCallBack != null) {\n return mInEdgeCanMoveFooterCallBack.isNotYetInEdgeCannotMoveFooter(\n this, targetView, mFooterView);\n }\n return targetView != null && targetView.canScrollVertically(1);\n }\n\n protected void makeNewTouchDownEvent(MotionEvent ev) {\n if (sDebug) {\n Log.d(TAG, \"makeNewTouchDownEvent()\");\n }\n sendCancelEvent(ev);\n sendDownEvent(ev);\n mOffsetConsumed = 0;\n mOffsetTotal = 0;\n mOffsetRemaining = mTouchSlop * 3;\n mIndicatorSetter.onFingerUp();\n mIndicatorSetter.onFingerDown(ev.getX(), ev.getY());\n }\n\n protected void sendCancelEvent(MotionEvent event) {\n if (mHasSendCancelEvent || (event == null && mLastMoveEvent == null)) {\n return;\n }\n if (sDebug) {\n Log.d(TAG, \"sendCancelEvent()\");\n }\n final MotionEvent last = event == null ? mLastMoveEvent : event;\n final long now = SystemClock.uptimeMillis();\n final MotionEvent ev =\n MotionEvent.obtain(\n now, now, MotionEvent.ACTION_CANCEL, last.getX(), last.getY(), 0);\n ev.setSource(InputDevice.SOURCE_TOUCHSCREEN);\n mHasSendCancelEvent = true;\n mHasSendDownEvent = false;\n super.dispatchTouchEvent(ev);\n ev.recycle();\n }\n\n protected void sendDownEvent(MotionEvent event) {\n if (mHasSendDownEvent || (event == null && mLastMoveEvent == null)) {\n return;\n }\n if (sDebug) {\n Log.d(TAG, \"sendDownEvent()\");\n }\n final MotionEvent last = event == null ? mLastMoveEvent : event;\n final long now = SystemClock.uptimeMillis();\n final float[] rawOffsets = mIndicator.getRawOffsets();\n final MotionEvent downEv =\n MotionEvent.obtain(\n now,\n now,\n MotionEvent.ACTION_DOWN,\n last.getX() - rawOffsets[0],\n last.getY() - rawOffsets[1],\n 0);\n downEv.setSource(InputDevice.SOURCE_TOUCHSCREEN);\n super.dispatchTouchEvent(downEv);\n downEv.recycle();\n final MotionEvent moveEv =\n MotionEvent.obtain(now, now, MotionEvent.ACTION_MOVE, last.getX(), last.getY(), 0);\n moveEv.setSource(InputDevice.SOURCE_TOUCHSCREEN);\n mHasSendCancelEvent = false;\n mHasSendDownEvent = true;\n super.dispatchTouchEvent(moveEv);\n moveEv.recycle();\n }\n\n protected void notifyFingerUp() {\n if (isHeaderInProcessing() && mHeaderView != null && !isDisabledRefresh()) {\n mHeaderView.onFingerUp(this, mIndicator);\n } else if (isFooterInProcessing() && mFooterView != null && !isDisabledLoadMore()) {\n mFooterView.onFingerUp(this, mIndicator);\n }\n }\n\n protected void onFingerUp() {\n if (sDebug) {\n Log.d(TAG, \"onFingerUp()\");\n }\n notifyFingerUp();\n if (!mScrollChecker.isPreFling()) {\n if (isEnabledKeepRefreshView() && mStatus != SR_STATUS_COMPLETE) {\n if (isHeaderInProcessing()\n && mHeaderView != null\n && !isDisabledPerformRefresh()\n && isMovingHeader()\n && mIndicator.isOverOffsetToRefresh()) {\n if (!mIndicator.isAlreadyHere(mIndicator.getOffsetToKeepHeaderWhileLoading())) {\n mScrollChecker.scrollTo(\n mIndicator.getOffsetToKeepHeaderWhileLoading(),\n mDurationOfBackToHeaderHeight);\n return;\n }\n } else if (isFooterInProcessing()\n && mFooterView != null\n && !isDisabledPerformLoadMore()\n && isMovingFooter()\n && mIndicator.isOverOffsetToLoadMore()) {\n if (!mIndicator.isAlreadyHere(mIndicator.getOffsetToKeepFooterWhileLoading())) {\n mScrollChecker.scrollTo(\n mIndicator.getOffsetToKeepFooterWhileLoading(),\n mDurationOfBackToFooterHeight);\n return;\n }\n }\n }\n onRelease();\n }\n }\n\n protected void onRelease() {\n if (sDebug) {\n Log.d(TAG, \"onRelease()\");\n }\n if ((isMovingFooter() && isEnabledNoMoreDataAndNoSpringBack())) {\n mScrollChecker.stop();\n return;\n }\n tryToPerformRefresh();\n if (mStatus == SR_STATUS_COMPLETE) {\n notifyUIRefreshComplete(true, false, false);\n return;\n } else if (isEnabledKeepRefreshView()) {\n if (isHeaderInProcessing() && mHeaderView != null && !isDisabledPerformRefresh()) {\n if (isRefreshing()\n && isMovingHeader()\n && mIndicator.isAlreadyHere(\n mIndicator.getOffsetToKeepHeaderWhileLoading())) {\n return;\n } else if (isMovingHeader() && mIndicator.isOverOffsetToKeepHeaderWhileLoading()) {\n mScrollChecker.scrollTo(\n mIndicator.getOffsetToKeepHeaderWhileLoading(),\n mDurationOfBackToHeaderHeight);\n return;\n } else if (isRefreshing() && !isMovingFooter()) {\n return;\n }\n } else if (isFooterInProcessing()\n && mFooterView != null\n && !isDisabledPerformLoadMore()) {\n if (isLoadingMore()\n && isMovingFooter()\n && mIndicator.isAlreadyHere(\n mIndicator.getOffsetToKeepFooterWhileLoading())) {\n return;\n } else if (isMovingFooter() && mIndicator.isOverOffsetToKeepFooterWhileLoading()) {\n mScrollChecker.scrollTo(\n mIndicator.getOffsetToKeepFooterWhileLoading(),\n mDurationOfBackToFooterHeight);\n return;\n } else if (isLoadingMore() && !isMovingHeader()) {\n return;\n }\n }\n }\n tryScrollBackToTop();\n }\n\n protected void tryScrollBackToTop() {\n // Use the current percentage duration of the current position to scroll back to the top\n if (mScrollChecker.isFlingBack()) {\n tryScrollBackToTop(mDurationOfFlingBack);\n } else if (isMovingHeader()) {\n tryScrollBackToTop(mDurationToCloseHeader);\n } else if (isMovingFooter()) {\n tryScrollBackToTop(mDurationToCloseFooter);\n } else {\n tryToNotifyReset();\n }\n }\n\n protected void tryScrollBackToTop(int duration) {\n if (sDebug) {\n Log.d(TAG, String.format(\"tryScrollBackToTop(): duration: %d\", duration));\n }\n if (mIndicator.hasLeftStartPosition()\n && (!mIndicator.hasTouched() || !mIndicator.hasMoved())) {\n mScrollChecker.scrollTo(IIndicator.START_POS, duration);\n return;\n }\n if (isNeedFilterTouchEvent() && mIndicator.hasLeftStartPosition()) {\n mScrollChecker.scrollTo(IIndicator.START_POS, duration);\n return;\n }\n tryToNotifyReset();\n }\n\n protected void moveHeaderPos(float delta) {\n if (sDebug) {\n Log.d(TAG, String.format(\"moveHeaderPos(): delta: %f\", delta));\n }\n mNeedFilterScrollEvent = false;\n if (!mNestedScrolling\n && !mHasSendCancelEvent\n && isEnabledOldTouchHandling()\n && mIndicator.hasTouched()\n && !mIndicator.isAlreadyHere(IIndicator.START_POS)) sendCancelEvent(null);\n mIndicatorSetter.setMovingStatus(Constants.MOVING_HEADER);\n if (mHeaderView != null) {\n if (delta > 0) {\n final float maxHeaderDistance = mIndicator.getCanMoveTheMaxDistanceOfHeader();\n final int current = mIndicator.getCurrentPos();\n final boolean isFling = mScrollChecker.isFling() || mScrollChecker.isPreFling();\n if (maxHeaderDistance > 0) {\n if (current >= maxHeaderDistance) {\n if (!mScrollChecker.mIsScrolling || isFling) {\n updateAnotherDirectionPos();\n return;\n }\n } else if (current + delta > maxHeaderDistance) {\n if (!mScrollChecker.mIsScrolling || isFling) {\n delta = maxHeaderDistance - current;\n if (isFling) {\n mScrollChecker.mScroller.forceFinished(true);\n }\n }\n }\n }\n } else {\n // check if it is needed to compatible scroll\n if ((mFlag & FLAG_ENABLE_COMPAT_SYNC_SCROLL) > 0\n && !isEnabledPinContentView()\n && mIsLastRefreshSuccessful\n && mStatus == SR_STATUS_COMPLETE\n && isNotYetInEdgeCannotMoveHeader()) {\n if (sDebug) {\n Log.d(\n TAG,\n String.format(\n \"moveHeaderPos(): compatible scroll delta: %f\", delta));\n }\n mNeedFilterScrollEvent = true;\n tryToCompatSyncScroll(getScrollTargetView(), delta);\n }\n }\n }\n movePos(delta);\n }\n\n protected void moveFooterPos(float delta) {\n if (sDebug) {\n Log.d(TAG, String.format(\"moveFooterPos(): delta: %f\", delta));\n }\n mNeedFilterScrollEvent = false;\n if (!mNestedScrolling\n && !mHasSendCancelEvent\n && isEnabledOldTouchHandling()\n && mIndicator.hasTouched()\n && !mIndicator.isAlreadyHere(IIndicator.START_POS)) sendCancelEvent(null);\n mIndicatorSetter.setMovingStatus(Constants.MOVING_FOOTER);\n if (mFooterView != null) {\n if (delta < 0) {\n final float maxFooterDistance = mIndicator.getCanMoveTheMaxDistanceOfFooter();\n final int current = mIndicator.getCurrentPos();\n final boolean isFling = mScrollChecker.isFling() || mScrollChecker.isPreFling();\n if (maxFooterDistance > 0) {\n if (current >= maxFooterDistance) {\n if (!mScrollChecker.mIsScrolling || isFling) {\n updateAnotherDirectionPos();\n return;\n }\n } else if (current - delta > maxFooterDistance) {\n if (!mScrollChecker.mIsScrolling || isFling) {\n delta = current - maxFooterDistance;\n if (isFling) {\n mScrollChecker.mScroller.forceFinished(true);\n }\n }\n }\n }\n } else {\n // check if it is needed to compatible scroll\n if ((mFlag & FLAG_ENABLE_COMPAT_SYNC_SCROLL) > 0\n && !isEnabledPinContentView()\n && mIsLastRefreshSuccessful\n && mStatus == SR_STATUS_COMPLETE\n && isNotYetInEdgeCannotMoveFooter()) {\n if (sDebug) {\n Log.d(\n TAG,\n String.format(\n \"moveFooterPos(): compatible scroll delta: %f\", delta));\n }\n mNeedFilterScrollEvent = true;\n tryToCompatSyncScroll(getScrollTargetView(), delta);\n }\n }\n }\n movePos(-delta);\n }\n\n protected void tryToCompatSyncScroll(View view, float delta) {\n if (mSyncScrollCallback != null) {\n mSyncScrollCallback.onScroll(view, delta);\n } else {\n if (!ScrollCompat.scrollCompat(view, delta)) {\n Log.w(TAG, \"tryToCompatSyncScroll(): scrollCompat failed!\");\n }\n }\n }\n\n protected void movePos(float delta) {\n if (delta == 0f) {\n if (sDebug) {\n Log.d(TAG, \"movePos(): delta is zero\");\n }\n return;\n }\n int to = (int) (mIndicator.getCurrentPos() + delta);\n // over top\n if (to < IIndicator.START_POS && mLayoutManager.isNeedFilterOverTop(delta)) {\n to = IIndicator.START_POS;\n if (sDebug) {\n Log.d(TAG, \"movePos(): over top\");\n }\n }\n mIndicatorSetter.setCurrentPos(to);\n int change = to - mIndicator.getLastPos();\n updatePos(isMovingFooter() ? -change : change);\n }\n\n /**\n * Update view's Y position\n *\n * @param change The changed value\n */\n protected void updatePos(int change) {\n if (sDebug) {\n Log.d(\n TAG,\n String.format(\n \"updatePos(): change: %d, current: %d last: %d\",\n change, mIndicator.getCurrentPos(), mIndicator.getLastPos()));\n }\n // leave initiated position or just refresh complete\n if ((mIndicator.hasJustLeftStartPosition() || mViewStatus == SR_VIEW_STATUS_INIT)\n && mStatus == SR_STATUS_INIT) {\n final byte old = mStatus;\n mStatus = SR_STATUS_PREPARE;\n notifyStatusChanged(old, mStatus);\n if (isMovingHeader()) {\n mViewStatus = SR_VIEW_STATUS_HEADER_IN_PROCESSING;\n if (mHeaderView != null) {\n mHeaderView.onRefreshPrepare(this);\n }\n } else if (isMovingFooter()) {\n mViewStatus = SR_VIEW_STATUS_FOOTER_IN_PROCESSING;\n if (mFooterView != null) {\n mFooterView.onRefreshPrepare(this);\n }\n }\n }\n tryToPerformRefreshWhenMoved();\n notifyUIPositionChanged();\n boolean needRequestLayout =\n mLayoutManager.offsetChild(\n mHeaderView,\n mFooterView,\n mStickyHeaderView,\n mStickyFooterView,\n mTargetView,\n change);\n // back to initiated position\n if (!(isAutoRefresh() && mStatus != SR_STATUS_COMPLETE)\n && mIndicator.hasJustBackToStartPosition()) {\n tryToNotifyReset();\n if (isEnabledOldTouchHandling()) {\n if (mIndicator.hasTouched() && !mNestedScrolling && !mHasSendDownEvent) {\n sendDownEvent(null);\n }\n }\n }\n if (needRequestLayout) {\n requestLayout();\n } else if (mIndicator.isAlreadyHere(IIndicator.START_POS)) {\n invalidate();\n }\n }\n\n protected void tryToPerformRefreshWhenMoved() {\n // try to perform refresh\n if (mStatus == SR_STATUS_PREPARE && !isAutoRefresh()) {\n // reach fresh height while moving from top to bottom or reach load more height while\n // moving from bottom to top\n if (isHeaderInProcessing() && isMovingHeader() && !isDisabledPerformRefresh()) {\n if (isEnabledPullToRefresh() && mIndicator.isOverOffsetToRefresh()) {\n triggeredRefresh(true);\n } else if (isEnabledPerformFreshWhenFling()\n && !mIndicator.hasTouched()\n && !(mScrollChecker.isPreFling() || mScrollChecker.isFling())\n && mIndicator.isJustReturnedOffsetToRefresh()) {\n mScrollChecker.stop();\n triggeredRefresh(true);\n }\n } else if (isFooterInProcessing() && isMovingFooter() && !isDisabledPerformLoadMore()) {\n if (isEnabledPullToRefresh() && mIndicator.isOverOffsetToLoadMore()) {\n triggeredLoadMore(true);\n } else if (isEnabledPerformFreshWhenFling()\n && !mIndicator.hasTouched()\n && !(mScrollChecker.isPreFling() || mScrollChecker.isFling())\n && mIndicator.isJustReturnedOffsetToLoadMore()) {\n mScrollChecker.stop();\n triggeredLoadMore(true);\n }\n }\n }\n }\n\n /** We need to notify the X pos changed */\n protected void updateAnotherDirectionPos() {\n if (mHeaderView != null\n && !isDisabledRefresh()\n && isMovingHeader()\n && mHeaderView.getView().getVisibility() == VISIBLE) {\n if (isHeaderInProcessing()) {\n mHeaderView.onRefreshPositionChanged(this, mStatus, mIndicator);\n } else {\n mHeaderView.onPureScrollPositionChanged(this, mStatus, mIndicator);\n }\n } else if (mFooterView != null\n && !isDisabledLoadMore()\n && isMovingFooter()\n && mFooterView.getView().getVisibility() == VISIBLE) {\n if (isFooterInProcessing()) {\n mFooterView.onRefreshPositionChanged(this, mStatus, mIndicator);\n } else {\n mFooterView.onPureScrollPositionChanged(this, mStatus, mIndicator);\n }\n }\n }\n\n public boolean isMovingHeader() {\n return mIndicator.getMovingStatus() == Constants.MOVING_HEADER;\n }\n\n public boolean isMovingContent() {\n return mIndicator.getMovingStatus() == Constants.MOVING_CONTENT;\n }\n\n public boolean isMovingFooter() {\n return mIndicator.getMovingStatus() == Constants.MOVING_FOOTER;\n }\n\n public boolean isHeaderInProcessing() {\n return mViewStatus == SR_VIEW_STATUS_HEADER_IN_PROCESSING;\n }\n\n public boolean isFooterInProcessing() {\n return mViewStatus == SR_VIEW_STATUS_FOOTER_IN_PROCESSING;\n }\n\n protected void tryToDispatchNestedFling() {\n if (mScrollChecker.isPreFling() && mIndicator.isAlreadyHere(IIndicator.START_POS)) {\n if (sDebug) {\n Log.d(TAG, \"tryToDispatchNestedFling()\");\n }\n final int velocity = (int) (mScrollChecker.getCurrVelocity() + 0.5f);\n mIndicatorSetter.setMovingStatus(Constants.MOVING_CONTENT);\n if (isEnabledOverScroll()\n && !(isDisabledLoadMoreWhenContentNotFull()\n && !isNotYetInEdgeCannotMoveHeader()\n && !isNotYetInEdgeCannotMoveFooter())) {\n mScrollChecker.startFling(velocity);\n } else {\n mScrollChecker.stop();\n }\n dispatchNestedFling(velocity);\n postInvalidateDelayed(30);\n }\n }\n\n protected boolean tryToNotifyReset() {\n if ((mStatus == SR_STATUS_COMPLETE || mStatus == SR_STATUS_PREPARE)\n && mIndicator.isAlreadyHere(IIndicator.START_POS)) {\n if (sDebug) {\n Log.d(TAG, \"tryToNotifyReset()\");\n }\n if (mHeaderView != null) {\n mHeaderView.onReset(this);\n }\n if (mFooterView != null) {\n mFooterView.onReset(this);\n }\n final byte old = mStatus;\n mStatus = SR_STATUS_INIT;\n notifyStatusChanged(old, mStatus);\n mViewStatus = SR_VIEW_STATUS_INIT;\n mAutomaticActionTriggered = true;\n mNeedFilterScrollEvent = false;\n tryToResetMovingStatus();\n if (!mIndicator.hasTouched()) {\n mIsSpringBackCanNotBeInterrupted = false;\n }\n if (mScrollChecker.isSpringBack()\n || mScrollChecker.isSpring()\n || mScrollChecker.isFlingBack()) {\n mScrollChecker.stop();\n }\n mLayoutManager.resetLayout(\n mHeaderView, mFooterView, mStickyHeaderView, mStickyFooterView, mTargetView);\n if (getParent() != null) {\n getParent().requestDisallowInterceptTouchEvent(false);\n }\n return true;\n }\n return false;\n }\n\n protected void performRefreshComplete(\n boolean hook, boolean immediatelyNoScrolling, boolean notifyViews) {\n if (sDebug) {\n Log.d(\n TAG,\n String.format(\n \"performRefreshComplete(): hook: %b, immediatelyNoScrolling: %b, notifyViews: %b\",\n hook, immediatelyNoScrolling, notifyViews));\n }\n if (isRefreshing()\n && hook\n && mHeaderRefreshCompleteHook != null\n && mHeaderRefreshCompleteHook.mCallBack != null) {\n mHeaderRefreshCompleteHook.mLayout = this;\n mHeaderRefreshCompleteHook.mNotifyViews = notifyViews;\n mHeaderRefreshCompleteHook.doHook();\n return;\n }\n if (isLoadingMore()\n && hook\n && mFooterRefreshCompleteHook != null\n && mFooterRefreshCompleteHook.mCallBack != null) {\n mFooterRefreshCompleteHook.mLayout = this;\n mFooterRefreshCompleteHook.mNotifyViews = notifyViews;\n mFooterRefreshCompleteHook.doHook();\n return;\n }\n if ((mFlag & FLAG_BEEN_SET_NO_MORE_DATA) <= 0) {\n if (mIsLastRefreshSuccessful) {\n mFlag = mFlag & ~(FLAG_ENABLE_NO_MORE_DATA | FLAG_ENABLE_NO_MORE_DATA_NO_BACK);\n }\n } else {\n mFlag = mFlag & ~FLAG_BEEN_SET_NO_MORE_DATA;\n }\n final byte old = mStatus;\n mStatus = SR_STATUS_COMPLETE;\n notifyStatusChanged(old, mStatus);\n notifyUIRefreshComplete(\n !(isMovingFooter() && isEnabledNoMoreDataAndNoSpringBack()),\n immediatelyNoScrolling,\n notifyViews);\n }\n\n protected void notifyUIRefreshComplete(\n boolean useScroll, boolean immediatelyNoScrolling, boolean notifyViews) {\n if (sDebug) {\n Log.d(\n TAG,\n String.format(\n \"notifyUIRefreshComplete(): useScroll: %b, immediatelyNoScrolling: %b, notifyViews: %b\",\n useScroll, immediatelyNoScrolling, notifyViews));\n }\n mIsSpringBackCanNotBeInterrupted = true;\n if (notifyViews) {\n if (isHeaderInProcessing() && mHeaderView != null) {\n mHeaderView.onRefreshComplete(this, mIsLastRefreshSuccessful);\n } else if (isFooterInProcessing() && mFooterView != null) {\n mFooterView.onRefreshComplete(this, mIsLastRefreshSuccessful);\n }\n }\n if (useScroll) {\n if (mScrollChecker.isFlingBack()) {\n mScrollChecker.stop();\n }\n if (immediatelyNoScrolling) {\n tryScrollBackToTop(0);\n } else {\n tryScrollBackToTop();\n }\n }\n }\n\n /** try to perform refresh or loading , if performed return true */\n protected void tryToPerformRefresh() {\n // status not be prepare or over scrolling or moving content go to break;\n if (mStatus != SR_STATUS_PREPARE || isMovingContent()) {\n return;\n }\n if (sDebug) {\n Log.d(TAG, \"tryToPerformRefresh()\");\n }\n final boolean isEnabledKeep = isEnabledKeepRefreshView();\n if (isHeaderInProcessing() && !isDisabledPerformRefresh() && mHeaderView != null) {\n if ((isEnabledKeep && mIndicator.isAlreadyHere(mIndicator.getOffsetToRefresh())\n || mIndicator.isAlreadyHere(mIndicator.getOffsetToKeepHeaderWhileLoading()))) {\n triggeredRefresh(true);\n return;\n }\n }\n if (isFooterInProcessing() && !isDisabledPerformLoadMore() && mFooterView != null) {\n if ((isEnabledKeep && mIndicator.isAlreadyHere(mIndicator.getOffsetToLoadMore())\n || mIndicator.isAlreadyHere(mIndicator.getOffsetToKeepFooterWhileLoading()))) {\n triggeredLoadMore(true);\n }\n }\n }\n\n protected void tryScrollToPerformAutoRefresh() {\n if (isMovingContent() && (mStatus == SR_STATUS_INIT || mStatus == SR_STATUS_PREPARE)) {\n if ((isEnabledAutoLoadMore() && !isDisabledPerformLoadMore())\n || (isEnabledAutoRefresh() && !isDisabledPerformRefresh())) {\n if (sDebug) {\n Log.d(TAG, \"tryScrollToPerformAutoRefresh()\");\n }\n final View targetView = getScrollTargetView();\n if (targetView != null) {\n if (isEnabledAutoLoadMore() && canAutoLoadMore(targetView)) {\n if (!isDisabledLoadMoreWhenContentNotFull()\n || isNotYetInEdgeCannotMoveHeader()\n || isNotYetInEdgeCannotMoveFooter()) {\n triggeredLoadMore(true);\n }\n } else if (isEnabledAutoRefresh() && canAutoRefresh(targetView)) {\n triggeredRefresh(true);\n }\n }\n }\n }\n }\n\n protected boolean canAutoLoadMore(View view) {\n if (mAutoLoadMoreCallBack != null) {\n return mAutoLoadMoreCallBack.canAutoLoadMore(this, view);\n }\n return ScrollCompat.canAutoLoadMore(view);\n }\n\n protected boolean canAutoRefresh(View view) {\n if (mAutoRefreshCallBack != null) {\n return mAutoRefreshCallBack.canAutoRefresh(this, view);\n }\n return ScrollCompat.canAutoRefresh(view);\n }\n\n protected void triggeredRefresh(boolean notify) {\n if (sDebug) {\n Log.d(TAG, \"triggeredRefresh()\");\n }\n byte old = mStatus;\n if (old != SR_STATUS_PREPARE) {\n notifyStatusChanged(old, SR_STATUS_PREPARE);\n old = SR_STATUS_PREPARE;\n if (mHeaderView != null) {\n mHeaderView.onRefreshPrepare(this);\n }\n }\n mStatus = SR_STATUS_REFRESHING;\n notifyStatusChanged(old, mStatus);\n mViewStatus = SR_VIEW_STATUS_HEADER_IN_PROCESSING;\n mFlag &= ~FLAG_AUTO_REFRESH;\n mIsSpringBackCanNotBeInterrupted = false;\n performRefresh(notify);\n }\n\n protected void triggeredLoadMore(boolean notify) {\n if (sDebug) {\n Log.d(TAG, \"triggeredLoadMore()\");\n }\n byte old = mStatus;\n if (old != SR_STATUS_PREPARE) {\n notifyStatusChanged(old, SR_STATUS_PREPARE);\n old = SR_STATUS_PREPARE;\n if (mFooterView != null) {\n mFooterView.onRefreshPrepare(this);\n }\n }\n mStatus = SR_STATUS_LOADING_MORE;\n notifyStatusChanged(old, mStatus);\n mViewStatus = SR_VIEW_STATUS_FOOTER_IN_PROCESSING;\n mFlag &= ~FLAG_AUTO_REFRESH;\n mIsSpringBackCanNotBeInterrupted = false;\n performRefresh(notify);\n }\n\n protected void tryToResetMovingStatus() {\n if (mIndicator.isAlreadyHere(IIndicator.START_POS) && !isMovingContent()) {\n mIndicatorSetter.setMovingStatus(Constants.MOVING_CONTENT);\n notifyUIPositionChanged();\n }\n }\n\n protected void performRefresh(boolean notify) {\n // loading start milliseconds since boot\n mLoadingStartTime = SystemClock.uptimeMillis();\n if (sDebug) {\n Log.d(TAG, String.format(\"onRefreshBegin systemTime: %d\", mLoadingStartTime));\n }\n if (isRefreshing()) {\n if (mHeaderView != null) {\n mHeaderView.onRefreshBegin(this, mIndicator);\n }\n } else if (isLoadingMore()) {\n if (mFooterView != null) {\n mFooterView.onRefreshBegin(this, mIndicator);\n }\n }\n if (notify && mRefreshListener != null) {\n if (isRefreshing()) {\n mRefreshListener.onRefreshing();\n } else {\n mRefreshListener.onLoadingMore();\n }\n }\n }\n\n protected void dispatchNestedFling(int velocity) {\n if (sDebug) {\n Log.d(TAG, String.format(\"dispatchNestedFling() : velocity: %d\", velocity));\n }\n final View targetView = getScrollTargetView();\n ScrollCompat.flingCompat(targetView, -velocity);\n }\n\n private void notifyUIPositionChanged() {\n final List<OnUIPositionChangedListener> listeners = mUIPositionChangedListeners;\n if (listeners != null) {\n for (OnUIPositionChangedListener listener : listeners) {\n listener.onChanged(mStatus, mIndicator);\n }\n }\n }\n\n protected void notifyStatusChanged(byte old, byte now) {\n final List<OnStatusChangedListener> listeners = mStatusChangedListeners;\n if (listeners != null) {\n for (OnStatusChangedListener listener : listeners) {\n listener.onStatusChanged(old, now);\n }\n }\n }\n\n private View foundViewInViewGroupById(ViewGroup group, int id) {\n final int size = group.getChildCount();\n for (int i = 0; i < size; i++) {\n View view = group.getChildAt(i);\n if (view.getId() == id) {\n return view;\n } else if (view instanceof ViewGroup) {\n final View found = foundViewInViewGroupById((ViewGroup) view, id);\n if (found != null) {\n return found;\n }\n }\n }\n return null;\n }\n\n /**\n * Classes that wish to override {@link SmoothRefreshLayout#isNotYetInEdgeCannotMoveHeader()}\n * method behavior\n */\n public interface OnHeaderEdgeDetectCallBack {\n /**\n * Callback that will be called when {@link\n * SmoothRefreshLayout#isNotYetInEdgeCannotMoveHeader()} method is called to allow the\n * implementer to override its behavior.\n *\n * @param parent SmoothRefreshLayout that this callback is overriding.\n * @param child The child view.\n * @param header The Header view.\n * @return Whether it is possible for the child view of parent layout to scroll up.\n */\n boolean isNotYetInEdgeCannotMoveHeader(\n SmoothRefreshLayout parent, @Nullable View child, @Nullable IRefreshView header);\n }\n\n /**\n * Classes that wish to override {@link SmoothRefreshLayout#isNotYetInEdgeCannotMoveFooter()}\n * method behavior\n */\n public interface OnFooterEdgeDetectCallBack {\n /**\n * Callback that will be called when {@link\n * SmoothRefreshLayout#isNotYetInEdgeCannotMoveFooter()} method is called to allow the\n * implementer to override its behavior.\n *\n * @param parent SmoothRefreshLayout that this callback is overriding.\n * @param child The child view.\n * @param footer The Footer view.\n * @return Whether it is possible for the child view of parent layout to scroll down.\n */\n boolean isNotYetInEdgeCannotMoveFooter(\n SmoothRefreshLayout parent, @Nullable View child, @Nullable IRefreshView footer);\n }\n\n /** Classes that wish to be notified when the swipe gesture correctly triggers a refresh */\n public interface OnRefreshListener {\n /** Called when a refresh is triggered. */\n void onRefreshing();\n\n /** Called when a load more is triggered. */\n void onLoadingMore();\n }\n\n /** Classes that wish to be notified when the views position changes */\n public interface OnUIPositionChangedListener {\n /**\n * UI position changed\n *\n * @param status {@link #SR_STATUS_INIT}, {@link #SR_STATUS_PREPARE}, {@link\n * #SR_STATUS_REFRESHING},{@link #SR_STATUS_LOADING_MORE},{@link #SR_STATUS_COMPLETE}.\n * @param indicator @see {@link IIndicator}\n */\n void onChanged(byte status, IIndicator indicator);\n }\n\n /** Classes that wish to be called when refresh completed spring back to start position */\n public interface OnSyncScrollCallback {\n /**\n * Called when refresh completed spring back to start position, each move triggers a\n * callback once\n *\n * @param content The content view\n * @param delta The scroll distance in current axis\n */\n void onScroll(View content, float delta);\n }\n\n public interface OnHookUIRefreshCompleteCallBack {\n void onHook(RefreshCompleteHook hook);\n }\n\n /**\n * Classes that wish to be called when {@link\n * SmoothRefreshLayout#setEnableAutoLoadMore(boolean)} has been set true and {@link\n * SmoothRefreshLayout#isDisabledLoadMore()} not be true and sure you need to customize the\n * specified trigger rule\n */\n public interface OnPerformAutoLoadMoreCallBack {\n /**\n * Whether need trigger auto load more\n *\n * @param parent The frame\n * @param child the child view\n * @return whether need trigger\n */\n boolean canAutoLoadMore(SmoothRefreshLayout parent, @Nullable View child);\n }\n\n /**\n * Classes that wish to be called when {@link SmoothRefreshLayout#setEnableAutoRefresh(boolean)}\n * has been set true and {@link SmoothRefreshLayout#isDisabledRefresh()} not be true and sure\n * you need to customize the specified trigger rule\n */\n public interface OnPerformAutoRefreshCallBack {\n /**\n * Whether need trigger auto refresh\n *\n * @param parent The frame\n * @param child the child view\n * @return whether need trigger\n */\n boolean canAutoRefresh(SmoothRefreshLayout parent, @Nullable View child);\n }\n\n /** Classes that wish to be notified when the status changed */\n public interface OnStatusChangedListener {\n /**\n * Status changed\n *\n * @param old the old status, as follows {@link #SR_STATUS_INIT}, {@link\n * #SR_STATUS_PREPARE}, {@link #SR_STATUS_REFRESHING},{@link #SR_STATUS_LOADING_MORE},\n * {@link #SR_STATUS_COMPLETE}}\n * @param now the current status, as follows {@link #SR_STATUS_INIT}, {@link\n * #SR_STATUS_PREPARE}, {@link #SR_STATUS_REFRESHING},{@link #SR_STATUS_LOADING_MORE},\n * {@link #SR_STATUS_COMPLETE}}\n */\n void onStatusChanged(byte old, byte now);\n }\n\n /** Classes that wish to override the calculate bounce duration and distance method */\n public interface OnCalculateBounceCallback {\n int onCalculateDistance(float velocity);\n\n int onCalculateDuration(float velocity);\n }\n\n public static class LayoutParams extends MarginLayoutParams {\n public int gravity = Gravity.TOP | Gravity.START;\n\n @SuppressWarnings(\"WeakerAccess\")\n public LayoutParams(Context c, AttributeSet attrs) {\n super(c, attrs);\n final TypedArray a =\n c.obtainStyledAttributes(attrs, R.styleable.SmoothRefreshLayout_Layout);\n gravity =\n a.getInt(\n R.styleable.SmoothRefreshLayout_Layout_android_layout_gravity, gravity);\n a.recycle();\n }\n\n public LayoutParams(int width, int height) {\n super(width, height);\n }\n\n @SuppressWarnings(\"unused\")\n public LayoutParams(MarginLayoutParams source) {\n super(source);\n }\n\n @SuppressWarnings(\"WeakerAccess\")\n public LayoutParams(ViewGroup.LayoutParams source) {\n super(source);\n }\n }\n\n public static class RefreshCompleteHook {\n private SmoothRefreshLayout mLayout;\n private OnHookUIRefreshCompleteCallBack mCallBack;\n private boolean mNotifyViews;\n\n public void onHookComplete(boolean immediatelyNoScrolling) {\n if (mLayout != null) {\n if (sDebug) {\n Log.d(\n mLayout.TAG,\n String.format(\n \"RefreshCompleteHook: onHookComplete(): immediatelyNoScrolling: %b\",\n immediatelyNoScrolling));\n }\n mLayout.performRefreshComplete(false, immediatelyNoScrolling, mNotifyViews);\n }\n }\n\n private void doHook() {\n if (mCallBack != null) {\n if (sDebug) {\n Log.d(mLayout.TAG, \"RefreshCompleteHook: doHook()\");\n }\n mCallBack.onHook(this);\n }\n }\n }\n\n /** Delayed completion of loading */\n private static class DelayToRefreshComplete implements Runnable {\n private SmoothRefreshLayout mLayout;\n private boolean mNotifyViews;\n\n @Override\n public void run() {\n if (mLayout != null) {\n if (sDebug) {\n Log.d(mLayout.TAG, \"DelayToRefreshComplete: run()\");\n }\n mLayout.performRefreshComplete(true, false, mNotifyViews);\n }\n }\n }\n\n /** Delayed to dispatch nested fling */\n private static class DelayToDispatchNestedFling implements Runnable {\n private SmoothRefreshLayout mLayout;\n private int mVelocity;\n\n @Override\n public void run() {\n if (mLayout != null) {\n if (sDebug) {\n Log.d(mLayout.TAG, \"DelayToDispatchNestedFling: run()\");\n }\n mLayout.dispatchNestedFling(mVelocity);\n }\n }\n }\n\n /** Delayed to perform auto refresh */\n private static class DelayToPerformAutoRefresh implements Runnable {\n private SmoothRefreshLayout mLayout;\n\n @Override\n public void run() {\n if (mLayout != null) {\n if (sDebug) {\n Log.d(mLayout.TAG, \"DelayToPerformAutoRefresh: run()\");\n }\n mLayout.tryToPerformAutoRefresh();\n }\n }\n }\n\n public abstract static class LayoutManager {\n public static final int HORIZONTAL = 0;\n public static final int VERTICAL = 1;\n protected final String TAG = getClass().getSimpleName() + \"-\" + SmoothRefreshLayout.sId++;\n protected SmoothRefreshLayout mLayout;\n protected boolean mMeasureMatchParentChildren;\n protected int mOldWidthMeasureSpec;\n protected int mOldHeightMeasureSpec;\n\n @Orientation\n public abstract int getOrientation();\n\n @CallSuper\n public void setLayout(SmoothRefreshLayout layout) {\n mLayout = layout;\n }\n\n public void onLayoutDraw(Canvas canvas) {}\n\n public boolean isNeedFilterOverTop(float delta) {\n return true;\n }\n\n public abstract void measureHeader(\n @NonNull IRefreshView<IIndicator> header,\n int widthMeasureSpec,\n int heightMeasureSpec);\n\n public abstract void measureFooter(\n @NonNull IRefreshView<IIndicator> footer,\n int widthMeasureSpec,\n int heightMeasureSpec);\n\n public abstract void layoutHeaderView(@NonNull IRefreshView<IIndicator> header);\n\n public abstract void layoutFooterView(@NonNull IRefreshView<IIndicator> footer);\n\n public abstract void layoutContentView(@NonNull View content);\n\n public abstract void layoutStickyHeaderView(@NonNull View stickyHeader);\n\n public abstract void layoutStickyFooterView(@NonNull View stickyFooter);\n\n public abstract boolean offsetChild(\n @Nullable IRefreshView<IIndicator> header,\n @Nullable IRefreshView<IIndicator> footer,\n @Nullable View stickyHeader,\n @Nullable View stickyFooter,\n @Nullable View content,\n int change);\n\n public void resetLayout(\n @Nullable IRefreshView<IIndicator> header,\n @Nullable IRefreshView<IIndicator> footer,\n @Nullable View stickyHeader,\n @Nullable View stickyFooter,\n @Nullable View content) {}\n\n protected void setHeaderHeight(int height) {\n if (mLayout != null) {\n mLayout.mIndicatorSetter.setHeaderHeight(height);\n }\n }\n\n protected void setFooterHeight(int height) {\n if (mLayout != null) {\n mLayout.mIndicatorSetter.setFooterHeight(height);\n }\n }\n\n protected byte getRefreshStatus() {\n return mLayout == null ? SmoothRefreshLayout.SR_STATUS_INIT : mLayout.mStatus;\n }\n\n protected final void measureChildWithMargins(\n View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) {\n final ViewGroup.MarginLayoutParams lp =\n (ViewGroup.MarginLayoutParams) child.getLayoutParams();\n final int childWidthMeasureSpec =\n ViewGroup.getChildMeasureSpec(\n parentWidthMeasureSpec,\n mLayout.getPaddingLeft()\n + mLayout.getPaddingRight()\n + lp.leftMargin\n + lp.rightMargin,\n lp.width);\n final int childHeightMeasureSpec =\n ViewGroup.getChildMeasureSpec(\n parentHeightMeasureSpec,\n mLayout.getPaddingTop()\n + mLayout.getPaddingBottom()\n + lp.topMargin\n + lp.bottomMargin,\n lp.height);\n child.measure(childWidthMeasureSpec, childHeightMeasureSpec);\n }\n }\n\n class ScrollChecker implements Runnable {\n private static final float GRAVITY_EARTH = 9.80665f;\n final int mMaxDistance;\n private final float mPhysical;\n Scroller[] mCachedScroller;\n Scroller mScroller;\n Scroller mCalcScroller;\n Interpolator mInterpolator;\n float mLastY;\n float mLastStart;\n float mLastTo;\n int mDuration;\n byte mMode = Constants.SCROLLER_MODE_NONE;\n float mVelocity;\n boolean mIsScrolling = false;\n private int[] mCachedPair = new int[2];\n\n ScrollChecker() {\n DisplayMetrics dm = getResources().getDisplayMetrics();\n mMaxDistance = (int) (dm.heightPixels / 8f);\n mPhysical = GRAVITY_EARTH * 39.37f * dm.density * 160f * 0.84f;\n mCalcScroller = new Scroller(getContext());\n mInterpolator = SPRING_INTERPOLATOR;\n mCachedScroller =\n new Scroller[] {\n new Scroller(getContext(), SPRING_INTERPOLATOR),\n new Scroller(getContext(), SPRING_BACK_INTERPOLATOR),\n new Scroller(getContext(), FLING_INTERPOLATOR)\n };\n mScroller = mCachedScroller[0];\n }\n\n @Override\n public void run() {\n if (mMode == Constants.SCROLLER_MODE_NONE || isCalcFling()) {\n return;\n }\n boolean finished = !mScroller.computeScrollOffset() && mScroller.getCurrY() == mLastY;\n int curY = mScroller.getCurrY();\n float deltaY = curY - mLastY;\n if (sDebug) {\n Log.d(\n TAG,\n String.format(\n \"ScrollChecker: run(): finished: %b, mode: %d, start: %f, to: %f,\"\n + \" curPos: %d, curY:%d, last: %f, delta: %f\",\n finished,\n mMode,\n mLastStart,\n mLastTo,\n mIndicator.getCurrentPos(),\n curY,\n mLastY,\n deltaY));\n }\n if (!finished) {\n mLastY = curY;\n if (isMovingHeader()) {\n moveHeaderPos(deltaY);\n } else if (isMovingFooter()) {\n if (isPreFling()) {\n moveFooterPos(deltaY);\n } else {\n moveFooterPos(-deltaY);\n }\n }\n ViewCompat.postOnAnimation(SmoothRefreshLayout.this, this);\n tryToDispatchNestedFling();\n } else {\n switch (mMode) {\n case Constants.SCROLLER_MODE_SPRING:\n case Constants.SCROLLER_MODE_FLING_BACK:\n case Constants.SCROLLER_MODE_SPRING_BACK:\n stop();\n if (!mIndicator.isAlreadyHere(IIndicator.START_POS)) {\n onRelease();\n }\n break;\n case Constants.SCROLLER_MODE_PRE_FLING:\n case Constants.SCROLLER_MODE_FLING:\n stop();\n mMode = Constants.SCROLLER_MODE_FLING_BACK;\n if (isEnabledPerformFreshWhenFling()\n || isRefreshing()\n || isLoadingMore()\n || (isEnabledAutoLoadMore() && isMovingFooter())\n || (isEnabledAutoRefresh() && isMovingHeader())) {\n onRelease();\n } else {\n tryScrollBackToTop();\n }\n break;\n }\n }\n }\n\n boolean isPreFling() {\n return mMode == Constants.SCROLLER_MODE_PRE_FLING;\n }\n\n boolean isFling() {\n return mMode == Constants.SCROLLER_MODE_FLING;\n }\n\n boolean isFlingBack() {\n return mMode == Constants.SCROLLER_MODE_FLING_BACK;\n }\n\n boolean isSpringBack() {\n return mMode == Constants.SCROLLER_MODE_SPRING_BACK;\n }\n\n boolean isSpring() {\n return mMode == Constants.SCROLLER_MODE_SPRING;\n }\n\n boolean isCalcFling() {\n return mMode == Constants.SCROLLER_MODE_CALC_FLING;\n }\n\n float getCurrVelocity() {\n final int originalSymbol = mVelocity > 0 ? 1 : -1;\n float v = mScroller.getCurrVelocity() * originalSymbol;\n if (sDebug) {\n Log.d(TAG, String.format(\"ScrollChecker: getCurrVelocity(): v: %f\", v));\n }\n return v;\n }\n\n int getFinalY(float v) {\n mCalcScroller.fling(\n 0,\n 0,\n 0,\n (int) v,\n Integer.MIN_VALUE,\n Integer.MAX_VALUE,\n Integer.MIN_VALUE,\n Integer.MAX_VALUE);\n final int y = Math.abs(mCalcScroller.getFinalY());\n if (sDebug) {\n Log.d(\n TAG,\n String.format(\n \"ScrollChecker: getFinalY(): v: %s, finalY: %d, currentY: %d\",\n v, y, mIndicator.getCurrentPos()));\n }\n mCalcScroller.abortAnimation();\n return y;\n }\n\n void startPreFling(float v) {\n stop();\n mMode = Constants.SCROLLER_MODE_PRE_FLING;\n setInterpolator(FLING_INTERPOLATOR);\n mVelocity = v;\n mScroller.fling(\n 0,\n 0,\n 0,\n (int) v,\n Integer.MIN_VALUE,\n Integer.MAX_VALUE,\n Integer.MIN_VALUE,\n Integer.MAX_VALUE);\n if (sDebug) {\n Log.d(TAG, String.format(\"ScrollChecker: startPreFling(): v: %s\", v));\n }\n ViewCompat.postOnAnimation(SmoothRefreshLayout.this, this);\n }\n\n void startFling(float v) {\n stop();\n mMode = Constants.SCROLLER_MODE_CALC_FLING;\n setInterpolator(FLING_INTERPOLATOR);\n mVelocity = v;\n mScroller.fling(\n 0,\n 0,\n 0,\n (int) v,\n Integer.MIN_VALUE,\n Integer.MAX_VALUE,\n Integer.MIN_VALUE,\n Integer.MAX_VALUE);\n if (sDebug) {\n Log.d(TAG, String.format(\"ScrollChecker: startFling(): v: %s\", v));\n }\n }\n\n void scrollTo(int to, int duration) {\n final int curPos = mIndicator.getCurrentPos();\n if (to > curPos) {\n stop();\n setInterpolator(mSpringInterpolator);\n mMode = Constants.SCROLLER_MODE_SPRING;\n } else if (to < curPos) {\n if (!mScrollChecker.isFlingBack()) {\n stop();\n mMode = Constants.SCROLLER_MODE_SPRING_BACK;\n }\n setInterpolator(mSpringBackInterpolator);\n } else {\n mMode = Constants.SCROLLER_MODE_NONE;\n return;\n }\n mLastStart = curPos;\n mLastTo = to;\n if (sDebug) {\n Log.d(\n TAG,\n String.format(\n \"ScrollChecker: scrollTo(): to: %d, duration: %d\", to, duration));\n }\n int distance = (int) (mLastTo - mLastStart);\n mLastY = 0;\n mDuration = duration;\n mIsScrolling = true;\n mScroller.startScroll(0, 0, 0, distance, duration);\n removeCallbacks(this);\n if (duration <= 0) {\n run();\n } else {\n ViewCompat.postOnAnimation(SmoothRefreshLayout.this, this);\n }\n }\n\n void computeScrollOffset() {\n if (mScroller.computeScrollOffset()) {\n if (sDebug) {\n Log.d(TAG, \"ScrollChecker: computeScrollOffset()\");\n }\n if (isCalcFling()) {\n if (mVelocity > 0\n && mIndicator.isAlreadyHere(IIndicator.START_POS)\n && !isNotYetInEdgeCannotMoveHeader()) {\n final float velocity = Math.abs(getCurrVelocity());\n stop();\n mIndicatorSetter.setMovingStatus(Constants.MOVING_HEADER);\n final int[] result = computeScroll(velocity);\n if (getHeaderHeight() > 0 && (isRefreshing() || isEnabledAutoRefresh())) {\n startBounce(\n Math.min(result[0] * 3, getHeaderHeight()),\n Math.min(\n Math.max(result[1] / 2 * 5, mMinOverScrollDuration),\n mMaxOverScrollDuration));\n } else {\n startBounce(result[0], result[1]);\n }\n return;\n } else if (mVelocity < 0\n && mIndicator.isAlreadyHere(IIndicator.START_POS)\n && !isNotYetInEdgeCannotMoveFooter()) {\n final float velocity = Math.abs(getCurrVelocity());\n stop();\n mIndicatorSetter.setMovingStatus(Constants.MOVING_FOOTER);\n final int[] result = computeScroll(velocity);\n if (getFooterHeight() > 0\n && (isLoadingMore()\n || isEnabledAutoLoadMore()\n || isEnabledNoMoreData())) {\n startBounce(\n Math.min(result[0] * 3, getFooterHeight()),\n Math.min(\n Math.max(result[1] / 2 * 5, mMinOverScrollDuration),\n mMaxOverScrollDuration));\n } else {\n startBounce(result[0], result[1]);\n }\n return;\n }\n }\n invalidate();\n }\n }\n\n int[] computeScroll(float velocity) {\n int distance, duration;\n if (mCalculateBounceCallback != null) {\n distance = mCalculateBounceCallback.onCalculateDistance(velocity);\n duration = mCalculateBounceCallback.onCalculateDuration(velocity);\n mCachedPair[0] = Math.max(distance, mTouchSlop);\n } else {\n // Multiply by a given empirical value\n velocity = velocity * .535f;\n float deceleration =\n (float)\n Math.log(\n Math.abs(velocity / 4.5f)\n / (ViewConfiguration.getScrollFriction()\n * mPhysical));\n float ratio = (float) ((Math.exp(-Math.log10(velocity) / 1.2d)) * 2f);\n distance =\n (int)\n ((ViewConfiguration.getScrollFriction()\n * mPhysical\n * Math.exp(deceleration))\n * ratio);\n duration = (int) (1000f * ratio);\n mCachedPair[0] = Math.max(Math.min(distance, mMaxDistance), mTouchSlop);\n }\n mCachedPair[1] =\n Math.min(Math.max(duration, mMinOverScrollDuration), mMaxOverScrollDuration);\n return mCachedPair;\n }\n\n void startBounce(int to, int duration) {\n mMode = Constants.SCROLLER_MODE_FLING;\n setInterpolator(SPRING_INTERPOLATOR);\n mLastStart = mIndicator.getCurrentPos();\n mLastTo = to;\n if (sDebug) {\n Log.d(\n TAG,\n String.format(\n \"ScrollChecker: startBounce(): to: %d, duration: %d\",\n to, duration));\n }\n int distance = (int) (mLastTo - mLastStart);\n mLastY = 0;\n mDuration = duration;\n mIsScrolling = true;\n mScroller.startScroll(0, 0, 0, distance, duration);\n removeCallbacks(this);\n ViewCompat.postOnAnimation(SmoothRefreshLayout.this, this);\n }\n\n void setInterpolator(Interpolator interpolator) {\n if (mInterpolator == interpolator) {\n return;\n }\n if (sDebug) {\n Log.d(\n TAG,\n String.format(\n \"ScrollChecker: updateInterpolator(): interpolator: %s\",\n interpolator == null\n ? \"null\"\n : interpolator.getClass().getSimpleName()));\n }\n mInterpolator = interpolator;\n if (!mScroller.isFinished()) {\n switch (mMode) {\n case Constants.SCROLLER_MODE_SPRING:\n case Constants.SCROLLER_MODE_FLING_BACK:\n case Constants.SCROLLER_MODE_SPRING_BACK:\n mLastStart = mIndicator.getCurrentPos();\n int distance = (int) (mLastTo - mLastStart);\n int passed = mScroller.timePassed();\n mScroller = makeOrGetScroller(interpolator);\n mScroller.startScroll(0, 0, 0, distance, mDuration - passed);\n removeCallbacks(this);\n ViewCompat.postOnAnimation(SmoothRefreshLayout.this, this);\n break;\n case Constants.SCROLLER_MODE_PRE_FLING:\n case Constants.SCROLLER_MODE_CALC_FLING:\n final float currentVelocity = getCurrVelocity();\n mScroller = makeOrGetScroller(interpolator);\n if (isCalcFling()) {\n startFling(currentVelocity);\n } else {\n startPreFling(currentVelocity);\n }\n break;\n default:\n mScroller = makeOrGetScroller(interpolator);\n break;\n }\n } else {\n mScroller = makeOrGetScroller(interpolator);\n }\n }\n\n void stop() {\n if (mMode != Constants.SCROLLER_MODE_NONE) {\n if (sDebug) {\n Log.d(TAG, \"ScrollChecker: stop()\");\n }\n if (mNestedScrolling && isCalcFling()) {\n mMode = Constants.SCROLLER_MODE_NONE;\n stopNestedScroll(ViewCompat.TYPE_NON_TOUCH);\n } else {\n mMode = Constants.SCROLLER_MODE_NONE;\n }\n mAutomaticActionUseSmoothScroll = false;\n mIsScrolling = false;\n mScroller.forceFinished(true);\n mDuration = 0;\n mLastY = 0;\n mLastTo = -1;\n mLastStart = 0;\n removeCallbacks(this);\n }\n }\n\n private Scroller makeOrGetScroller(Interpolator interpolator) {\n if (interpolator == SPRING_INTERPOLATOR) {\n return mCachedScroller[0];\n } else if (interpolator == SPRING_BACK_INTERPOLATOR) {\n return mCachedScroller[1];\n } else if (interpolator == FLING_INTERPOLATOR) {\n return mCachedScroller[2];\n } else {\n return new Scroller(getContext(), interpolator);\n }\n }\n }\n}", "public class ClassicFooter<T extends IIndicator> extends AbsClassicRefreshView<T> {\n private boolean mNoMoreDataChangedView = false;\n @StringRes private int mPullUpToLoadRes = R.string.sr_pull_up_to_load;\n @StringRes private int mPullUpRes = R.string.sr_pull_up;\n @StringRes private int mLoadingRes = R.string.sr_loading;\n @StringRes private int mLoadSuccessfulRes = R.string.sr_load_complete;\n @StringRes private int mLoadFailRes = R.string.sr_load_failed;\n @StringRes private int mReleaseToLoadRes = R.string.sr_release_to_load;\n @StringRes private int mNoMoreDataRes = R.string.sr_no_more_data;\n private View.OnClickListener mNoMoreDataClickListener;\n\n public ClassicFooter(Context context) {\n this(context, null);\n }\n\n public ClassicFooter(Context context, AttributeSet attrs) {\n this(context, attrs, 0);\n }\n\n public ClassicFooter(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n Bitmap bitmap =\n BitmapFactory.decodeResource(getResources(), R.drawable.sr_classic_arrow_icon);\n Matrix matrix = new Matrix();\n matrix.postRotate(180);\n Bitmap dstBitmap =\n Bitmap.createBitmap(\n bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);\n if (!bitmap.isRecycled()) bitmap.recycle();\n mArrowImageView.setImageBitmap(dstBitmap);\n }\n\n public void setPullUpToLoadRes(@StringRes int pullUpToLoadRes) {\n mPullUpToLoadRes = pullUpToLoadRes;\n }\n\n public void setPullUpRes(@StringRes int pullUpRes) {\n mPullUpRes = pullUpRes;\n }\n\n public void setLoadingRes(@StringRes int loadingRes) {\n mLoadingRes = loadingRes;\n }\n\n public void setLoadSuccessfulRes(@StringRes int loadSuccessfulRes) {\n mLoadSuccessfulRes = loadSuccessfulRes;\n }\n\n public void setLoadFailRes(@StringRes int loadFailRes) {\n mLoadFailRes = loadFailRes;\n }\n\n public void setReleaseToLoadRes(@StringRes int releaseToLoadRes) {\n mReleaseToLoadRes = releaseToLoadRes;\n }\n\n public void setNoMoreDataRes(int noMoreDataRes) {\n mNoMoreDataRes = noMoreDataRes;\n }\n\n public void setNoMoreDataClickListener(View.OnClickListener onClickListener) {\n mNoMoreDataClickListener = onClickListener;\n }\n\n @Override\n public int getType() {\n return TYPE_FOOTER;\n }\n\n @Override\n public void onReset(SmoothRefreshLayout frame) {\n super.onReset(frame);\n mNoMoreDataChangedView = false;\n mTitleTextView.setOnClickListener(null);\n }\n\n @Override\n public void onRefreshPrepare(SmoothRefreshLayout frame) {\n mArrowImageView.clearAnimation();\n mShouldShowLastUpdate = true;\n mNoMoreDataChangedView = false;\n tryUpdateLastUpdateTime();\n if (!TextUtils.isEmpty(mLastUpdateTimeKey)) {\n mLastUpdateTimeUpdater.start();\n }\n mProgressBar.setVisibility(INVISIBLE);\n mArrowImageView.setVisibility(VISIBLE);\n mTitleTextView.setVisibility(VISIBLE);\n mTitleTextView.setOnClickListener(null);\n if (frame.isEnabledPullToRefresh() && !frame.isDisabledPerformLoadMore()) {\n mTitleTextView.setText(mPullUpToLoadRes);\n } else {\n mTitleTextView.setText(mPullUpRes);\n }\n requestLayout();\n }\n\n @Override\n public void onRefreshBegin(SmoothRefreshLayout frame, T indicator) {\n mArrowImageView.clearAnimation();\n mArrowImageView.setVisibility(INVISIBLE);\n mProgressBar.setVisibility(VISIBLE);\n mTitleTextView.setVisibility(VISIBLE);\n mTitleTextView.setText(mLoadingRes);\n tryUpdateLastUpdateTime();\n }\n\n @Override\n public void onRefreshComplete(SmoothRefreshLayout frame, boolean isSuccessful) {\n mArrowImageView.clearAnimation();\n mArrowImageView.setVisibility(INVISIBLE);\n mProgressBar.setVisibility(INVISIBLE);\n mTitleTextView.setVisibility(VISIBLE);\n final boolean noMoreData = frame.isEnabledNoMoreData();\n if (frame.isRefreshSuccessful()) {\n mTitleTextView.setText(noMoreData ? mNoMoreDataRes : mLoadSuccessfulRes);\n mLastUpdateTime = System.currentTimeMillis();\n ClassicConfig.updateTime(getContext(), mLastUpdateTimeKey, mLastUpdateTime);\n } else {\n mTitleTextView.setText(noMoreData ? mNoMoreDataRes : mLoadFailRes);\n }\n mLastUpdateTimeUpdater.stop();\n mLastUpdateTextView.setVisibility(GONE);\n if (noMoreData) {\n mTitleTextView.setOnClickListener(mNoMoreDataClickListener);\n }\n }\n\n @Override\n public void onRefreshPositionChanged(SmoothRefreshLayout frame, byte status, T indicator) {\n final int offsetToLoadMore = indicator.getOffsetToLoadMore();\n final int currentPos = indicator.getCurrentPos();\n final int lastPos = indicator.getLastPos();\n if (frame.isEnabledNoMoreData()) {\n if (currentPos > lastPos && !mNoMoreDataChangedView) {\n mTitleTextView.setVisibility(VISIBLE);\n mLastUpdateTextView.setVisibility(GONE);\n mProgressBar.setVisibility(INVISIBLE);\n mLastUpdateTimeUpdater.stop();\n mArrowImageView.clearAnimation();\n mArrowImageView.setVisibility(GONE);\n mTitleTextView.setText(mNoMoreDataRes);\n mTitleTextView.setOnClickListener(mNoMoreDataClickListener);\n mNoMoreDataChangedView = true;\n }\n return;\n }\n mNoMoreDataChangedView = false;\n if (currentPos < offsetToLoadMore && lastPos >= offsetToLoadMore) {\n if (indicator.hasTouched() && status == SmoothRefreshLayout.SR_STATUS_PREPARE) {\n mTitleTextView.setVisibility(VISIBLE);\n if (frame.isEnabledPullToRefresh() && !frame.isDisabledPerformLoadMore()) {\n mTitleTextView.setText(mPullUpToLoadRes);\n } else {\n mTitleTextView.setText(mPullUpRes);\n }\n mArrowImageView.setVisibility(VISIBLE);\n mArrowImageView.clearAnimation();\n mArrowImageView.startAnimation(mReverseFlipAnimation);\n }\n } else if (currentPos > offsetToLoadMore && lastPos <= offsetToLoadMore) {\n if (indicator.hasTouched() && status == SmoothRefreshLayout.SR_STATUS_PREPARE) {\n mTitleTextView.setVisibility(VISIBLE);\n if (!frame.isEnabledPullToRefresh() && !frame.isDisabledPerformLoadMore()) {\n mTitleTextView.setText(mReleaseToLoadRes);\n }\n mArrowImageView.setVisibility(VISIBLE);\n mArrowImageView.clearAnimation();\n mArrowImageView.startAnimation(mFlipAnimation);\n }\n }\n }\n}", "public class ClassicHeader<T extends IIndicator> extends AbsClassicRefreshView<T> {\n @StringRes private int mPullDownToRefreshRes = R.string.sr_pull_down_to_refresh;\n @StringRes private int mPullDownRes = R.string.sr_pull_down;\n @StringRes private int mRefreshingRes = R.string.sr_refreshing;\n @StringRes private int mRefreshSuccessfulRes = R.string.sr_refresh_complete;\n @StringRes private int mRefreshFailRes = R.string.sr_refresh_failed;\n @StringRes private int mReleaseToRefreshRes = R.string.sr_release_to_refresh;\n\n public ClassicHeader(Context context) {\n this(context, null);\n }\n\n public ClassicHeader(Context context, AttributeSet attrs) {\n this(context, attrs, 0);\n }\n\n public ClassicHeader(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n mArrowImageView.setImageResource(R.drawable.sr_classic_arrow_icon);\n }\n\n public void setPullDownToRefreshRes(@StringRes int pullDownToRefreshRes) {\n mPullDownToRefreshRes = pullDownToRefreshRes;\n }\n\n public void setPullDownRes(@StringRes int pullDownRes) {\n mPullDownRes = pullDownRes;\n }\n\n public void setRefreshingRes(@StringRes int refreshingRes) {\n mRefreshingRes = refreshingRes;\n }\n\n public void setRefreshSuccessfulRes(@StringRes int refreshSuccessfulRes) {\n mRefreshSuccessfulRes = refreshSuccessfulRes;\n }\n\n public void setRefreshFailRes(@StringRes int refreshFailRes) {\n mRefreshFailRes = refreshFailRes;\n }\n\n public void setReleaseToRefreshRes(@StringRes int releaseToRefreshRes) {\n mReleaseToRefreshRes = releaseToRefreshRes;\n }\n\n @Override\n public int getType() {\n return TYPE_HEADER;\n }\n\n @Override\n public void onRefreshPrepare(SmoothRefreshLayout frame) {\n mArrowImageView.clearAnimation();\n mShouldShowLastUpdate = true;\n tryUpdateLastUpdateTime();\n if (!TextUtils.isEmpty(mLastUpdateTimeKey)) {\n mLastUpdateTimeUpdater.start();\n }\n mProgressBar.setVisibility(INVISIBLE);\n mArrowImageView.setVisibility(VISIBLE);\n mTitleTextView.setVisibility(VISIBLE);\n if (frame.isEnabledPullToRefresh()) {\n mTitleTextView.setText(mPullDownToRefreshRes);\n } else {\n mTitleTextView.setText(mPullDownRes);\n }\n requestLayout();\n }\n\n @Override\n public void onRefreshBegin(SmoothRefreshLayout frame, T indicator) {\n mArrowImageView.clearAnimation();\n mArrowImageView.setVisibility(INVISIBLE);\n mProgressBar.setVisibility(VISIBLE);\n mTitleTextView.setVisibility(VISIBLE);\n mTitleTextView.setText(mRefreshingRes);\n tryUpdateLastUpdateTime();\n }\n\n @Override\n public void onRefreshComplete(SmoothRefreshLayout frame, boolean isSuccessful) {\n mArrowImageView.clearAnimation();\n mArrowImageView.setVisibility(INVISIBLE);\n mProgressBar.setVisibility(INVISIBLE);\n mTitleTextView.setVisibility(VISIBLE);\n if (frame.isRefreshSuccessful()) {\n mTitleTextView.setText(mRefreshSuccessfulRes);\n mLastUpdateTime = System.currentTimeMillis();\n ClassicConfig.updateTime(getContext(), mLastUpdateTimeKey, mLastUpdateTime);\n } else {\n mTitleTextView.setText(mRefreshFailRes);\n }\n mLastUpdateTimeUpdater.stop();\n mLastUpdateTextView.setVisibility(GONE);\n }\n\n @Override\n public void onRefreshPositionChanged(SmoothRefreshLayout frame, byte status, T indicator) {\n final int offsetToRefresh = indicator.getOffsetToRefresh();\n final int currentPos = indicator.getCurrentPos();\n final int lastPos = indicator.getLastPos();\n\n if (currentPos < offsetToRefresh && lastPos >= offsetToRefresh) {\n if (indicator.hasTouched() && status == SmoothRefreshLayout.SR_STATUS_PREPARE) {\n mTitleTextView.setVisibility(VISIBLE);\n if (frame.isEnabledPullToRefresh()) {\n mTitleTextView.setText(mPullDownToRefreshRes);\n } else {\n mTitleTextView.setText(mPullDownRes);\n }\n mArrowImageView.setVisibility(VISIBLE);\n mArrowImageView.clearAnimation();\n mArrowImageView.startAnimation(mReverseFlipAnimation);\n }\n } else if (currentPos > offsetToRefresh && lastPos <= offsetToRefresh) {\n if (indicator.hasTouched() && status == SmoothRefreshLayout.SR_STATUS_PREPARE) {\n mTitleTextView.setVisibility(VISIBLE);\n if (!frame.isEnabledPullToRefresh()) {\n mTitleTextView.setText(mReleaseToRefreshRes);\n }\n mArrowImageView.setVisibility(VISIBLE);\n mArrowImageView.clearAnimation();\n mArrowImageView.startAnimation(mFlipAnimation);\n }\n }\n }\n}", "public interface IIndicator {\n float DEFAULT_RATIO_TO_REFRESH = 1f;\n float DEFAULT_MAX_MOVE_RATIO = 0f;\n float DEFAULT_RATIO_TO_KEEP = 1;\n float DEFAULT_RESISTANCE = 1.65f;\n int START_POS = 0;\n\n @MovingStatus\n int getMovingStatus();\n\n int getCurrentPos();\n\n boolean hasTouched();\n\n boolean hasMoved();\n\n int getOffsetToRefresh();\n\n int getOffsetToLoadMore();\n\n float getOffset();\n\n float getRawOffset();\n\n float[] getRawOffsets();\n\n int getLastPos();\n\n int getHeaderHeight();\n\n int getFooterHeight();\n\n boolean hasLeftStartPosition();\n\n boolean hasJustLeftStartPosition();\n\n boolean hasJustBackToStartPosition();\n\n boolean isJustReturnedOffsetToRefresh();\n\n boolean isJustReturnedOffsetToLoadMore();\n\n boolean isOverOffsetToKeepHeaderWhileLoading();\n\n boolean isOverOffsetToRefresh();\n\n boolean isOverOffsetToKeepFooterWhileLoading();\n\n boolean isOverOffsetToLoadMore();\n\n int getOffsetToKeepHeaderWhileLoading();\n\n int getOffsetToKeepFooterWhileLoading();\n\n boolean isAlreadyHere(int to);\n\n float getCanMoveTheMaxDistanceOfHeader();\n\n float getCanMoveTheMaxDistanceOfFooter();\n\n @NonNull\n float[] getFingerDownPoint();\n\n @NonNull\n float[] getLastMovePoint();\n\n float getCurrentPercentOfRefreshOffset();\n\n float getCurrentPercentOfLoadMoreOffset();\n\n void checkConfig();\n\n /**\n * Created by dkzwm on 2017/10/24.\n *\n * @author dkzwm\n */\n interface IOffsetCalculator {\n float calculate(@MovingStatus int status, int currentPos, float offset);\n }\n}", "public class RecyclerViewAdapter\n extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerViewHolder> {\n private LayoutInflater mInflater;\n private Context mContext;\n private ArrayList<String> mList = new ArrayList<>();\n\n public RecyclerViewAdapter(Context context, LayoutInflater inflater) {\n mContext = context;\n mInflater = inflater;\n }\n\n public void updateData(List<String> list) {\n mList.clear();\n mList.addAll(list);\n notifyDataSetChanged();\n }\n\n public void insertData(List<String> list) {\n mList.addAll(0, list);\n notifyItemRangeInserted(0, list.size());\n }\n\n public void appendData(List<String> list) {\n int size = mList.size();\n mList.addAll(list);\n notifyItemInserted(size);\n }\n\n @Override\n @NonNull\n public RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {\n View view = mInflater.inflate(R.layout.layout_list_view_item, parent, false);\n return new RecyclerViewHolder(view);\n }\n\n @Override\n public void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position) {\n holder.mTextView.setText(String.valueOf(position));\n Glide.with(mContext).asBitmap().load(mList.get(position)).into(holder.mImageView);\n }\n\n @Override\n public int getItemCount() {\n return mList.size();\n }\n\n class RecyclerViewHolder extends RecyclerView.ViewHolder {\n private TextView mTextView;\n private ImageView mImageView;\n\n RecyclerViewHolder(View itemView) {\n super(itemView);\n mImageView = itemView.findViewById(R.id.imageView_list_item);\n mTextView = itemView.findViewById(R.id.textView_list_item);\n itemView.setOnClickListener(\n new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Toast.makeText(\n v.getContext(),\n \"Click:\" + getAdapterPosition(),\n Toast.LENGTH_SHORT)\n .show();\n }\n });\n itemView.setOnLongClickListener(\n new View.OnLongClickListener() {\n @Override\n public boolean onLongClick(View v) {\n Toast.makeText(\n v.getContext(),\n \"LongClick:\" + getAdapterPosition(),\n Toast.LENGTH_SHORT)\n .show();\n return true;\n }\n });\n }\n }\n}", "public class CustomQQActivityHeader extends FrameLayout implements IRefreshView {\n private TextView mTextViewTitle;\n private boolean mStartedCounter;\n private int mCount = 0;\n\n public CustomQQActivityHeader(@NonNull Context context) {\n this(context, null);\n }\n\n public CustomQQActivityHeader(@NonNull Context context, @Nullable AttributeSet attrs) {\n this(context, attrs, 0);\n }\n\n public CustomQQActivityHeader(\n @NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n View header =\n LayoutInflater.from(context)\n .inflate(R.layout.layout_custom_qq_activity_header, this);\n mTextViewTitle = (TextView) header.findViewById(R.id.textView_qq_activity_header_title);\n }\n\n @Override\n public int getType() {\n return TYPE_HEADER;\n }\n\n @Override\n public int getStyle() {\n return STYLE_PIN;\n }\n\n @Override\n public int getCustomHeight() {\n return 0;\n }\n\n @NonNull\n @Override\n public View getView() {\n return this;\n }\n\n @Override\n public void onFingerUp(SmoothRefreshLayout layout, IIndicator indicator) {\n final int mOffsetToRefresh = indicator.getOffsetToRefresh();\n final int currentPos = indicator.getCurrentPos();\n\n if (currentPos > mOffsetToRefresh) {\n mCount++;\n mTextViewTitle.setText(\"x\" + mCount);\n }\n }\n\n @Override\n public void onReset(SmoothRefreshLayout layout) {\n mTextViewTitle.setText(R.string.brush);\n mStartedCounter = false;\n mCount = 0;\n }\n\n @Override\n public void onRefreshPrepare(SmoothRefreshLayout layout) {}\n\n @Override\n public void onRefreshBegin(SmoothRefreshLayout layout, IIndicator indicator) {}\n\n @Override\n public void onRefreshComplete(SmoothRefreshLayout layout, boolean isSuccessful) {}\n\n @Override\n public void onRefreshPositionChanged(\n SmoothRefreshLayout layout, byte status, IIndicator indicator) {\n final int mOffsetToRefresh = indicator.getOffsetToRefresh();\n final int currentPos = indicator.getCurrentPos();\n\n if (currentPos > mOffsetToRefresh && !mStartedCounter) {\n if (indicator.hasTouched() && status == SmoothRefreshLayout.SR_STATUS_PREPARE) {\n mStartedCounter = true;\n mTextViewTitle.setText(\"x\" + mCount);\n }\n }\n }\n\n @Override\n public void onPureScrollPositionChanged(\n SmoothRefreshLayout layout, byte status, IIndicator indicator) {}\n}", "public class DataUtil {\n private static List<String> sUrls = new ArrayList<>();\n\n static {\n sUrls.add(\n \"https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2770691011,100164542&fm=27&gp=0.jpg\");\n sUrls.add(\n \"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1508325599929&di=66fa1178688bfc77b44cb4edbf2db7f2&imgtype=0&src=http%3A%2F%2Fimg.dongqiudi.com%2Fuploads%2Favatar%2F2015%2F07%2F25%2FQM387nh7As_thumb_1437790672318.jpg\");\n sUrls.add(\n \"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1508325599927&di=389e03784785e34bb333b65e67ab2de0&imgtype=0&src=http%3A%2F%2Fimg.mp.itc.cn%2Fupload%2F20160706%2F95b9d87f089c4c3e959475584cb12148.jpg\");\n sUrls.add(\n \"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1508325663850&di=a5bcb74d9dd5257b1cf40f31677cf647&imgtype=jpg&src=http%3A%2F%2Fimg0.imgtn.bdimg.com%2Fit%2Fu%3D4079384686%2C3997373627%26fm%3D214%26gp%3D0.jpg\");\n sUrls.add(\n \"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1508325701432&di=233f6d3da9d53158690dabadab402606&imgtype=0&src=http%3A%2F%2Fimg4.duitang.com%2Fuploads%2Fitem%2F201407%2F22%2F20140722183209_KEQms.jpeg\");\n sUrls.add(\n \"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1508326471704&di=e6a8459b8cc041cf8e66f7ecf30b3d60&imgtype=0&src=http%3A%2F%2Fimg3.a0bi.com%2Fupload%2Fttq%2F20150418%2F1429356614113.jpg\");\n sUrls.add(\n \"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1508325701429&di=26499a340f41a6d03686151944f0e26f&imgtype=0&src=http%3A%2F%2Fd.hiphotos.baidu.com%2Fzhidao%2Fwh%253D600%252C800%2Fsign%3D007336919245d688a357baa294f25126%2F91ef76c6a7efce1b5e983768af51f3deb58f65e5.jpg\");\n sUrls.add(\n \"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1508325745159&di=15cc4586d679884655418e2bf39967b9&imgtype=jpg&src=http%3A%2F%2Fimg4.imgtn.bdimg.com%2Fit%2Fu%3D3993012754%2C3747813528%26fm%3D214%26gp%3D0.jpg\");\n sUrls.add(\n \"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1508325769929&di=b2f4dcf016acbe10df9a3568aaddfd87&imgtype=0&src=http%3A%2F%2Felf-work-4.qiniudn.com%2F1399116203yHJDXI3sUT_300.jpeg\");\n }\n\n public static List<String> createList(int count, int size) {\n List<String> list = new ArrayList<>();\n for (int i = 0; i < size; i++) {\n list.add(sUrls.get((count + i) % sUrls.size()));\n }\n return list;\n }\n}" ]
import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.MenuItem; import android.view.ViewGroup; import android.widget.RadioButton; import android.widget.RadioGroup; import androidx.annotation.IdRes; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import java.util.List; import me.dkzwm.widget.srl.RefreshingListenerAdapter; import me.dkzwm.widget.srl.SmoothRefreshLayout; import me.dkzwm.widget.srl.extra.footer.ClassicFooter; import me.dkzwm.widget.srl.extra.header.ClassicHeader; import me.dkzwm.widget.srl.indicator.IIndicator; import me.dkzwm.widget.srl.sample.R; import me.dkzwm.widget.srl.sample.adapter.RecyclerViewAdapter; import me.dkzwm.widget.srl.sample.header.CustomQQActivityHeader; import me.dkzwm.widget.srl.sample.utils.DataUtil;
package me.dkzwm.widget.srl.sample.ui; /** * Created by dkzwm on 2017/6/20. * * @author dkzwm */ public class TestQQActivityStyleActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener { private SmoothRefreshLayout mRefreshLayout; private RecyclerView mRecyclerView; private RecyclerViewAdapter mAdapter; private Handler mHandler = new Handler(); private RadioGroup mRadioGroup; private RadioButton mRadioButtonNormal; private RadioButton mRadioButtonActivity; private int mCount = 0; private ClassicHeader mClassicHeader; private ClassicFooter mClassicFooter; private CustomQQActivityHeader mQQActivityHeader; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_qq_activity_style); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setTitle(R.string.test_qq_activity_style); mRecyclerView = findViewById(R.id.recyclerView_test_qq_activity_style); mRadioGroup = findViewById(R.id.radioGroup_test_qq_activity_style_container); mRadioButtonNormal = findViewById(R.id.radioButton_test_qq_activity_style_normal); mRadioButtonActivity = findViewById(R.id.radioButton_test_qq_activity_style_activity); mRadioGroup.setOnCheckedChangeListener(this); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mRecyclerView.setHasFixedSize(true); mAdapter = new RecyclerViewAdapter(this, getLayoutInflater()); mRecyclerView.setAdapter(mAdapter); mRefreshLayout = findViewById(R.id.smoothRefreshLayout_test_qq_activity_style); mClassicHeader = new ClassicHeader(this); mClassicHeader.setLastUpdateTimeKey("header_last_update_time"); mClassicFooter = new ClassicFooter(this); mClassicFooter.setLastUpdateTimeKey("footer_last_update_time"); mRefreshLayout.setHeaderView(mClassicHeader); mRefreshLayout.setFooterView(mClassicFooter); mRefreshLayout.setEnableKeepRefreshView(true); mRefreshLayout.setDisableLoadMore(false); mRefreshLayout.setOnRefreshListener(
new RefreshingListenerAdapter() {
0
wrey75/WaveCleaner
src/main/java/com/oxande/xmlswing/components/JTextComponentUI.java
[ "public class AttributeDefinition {\r\n\t\r\n\tpublic final static Map<String, String> ALIGNS = new HashMap<String, String>();\r\n\tpublic final static Map<String, String> CLOSE_OPERATIONS = new HashMap<String, String>();\r\n\tpublic final static Map<String, String> CURSORS = new HashMap<String, String>();\r\n\tpublic final static Map<String, String> LIST_SEL_MODE = new HashMap<String, String>();\r\n\t\r\n\tstatic {\r\n\t\t\r\n\t\tCURSORS.put( \"crosshair\", \"CROSSHAIR_CURSOR\" );\r\n\t\tCURSORS.put( \"default\", \"DEFAULT_CURSOR\" );\r\n\t\tCURSORS.put( \"hand\", \"HAND_CURSOR\" );\r\n\t\tCURSORS.put( \"move\", \"MOVE_CURSOR\" );\r\n\t\t\r\n//\t\tpublic static final int \tCUSTOM_CURSOR \t-1\r\n//\t\tpublic static final int \tN_RESIZE_CURSOR \t8\r\n//\t\tpublic static final int \tNE_RESIZE_CURSOR \t7\r\n//\t\tpublic static final int \tNW_RESIZE_CURSOR \t6\r\n//\t\tpublic static final int \tS_RESIZE_CURSOR \t9\r\n//\t\tpublic static final int \tSE_RESIZE_CURSOR \t5\r\n//\t\tpublic static final int \tSW_RESIZE_CURSOR \t4\r\n//\t\tCURSORS.put( \"\", \"W_RESIZE_CURSOR\" );\r\n\t\t\r\n\t\tCURSORS.put( \"text\", \"TEXT_CURSOR\" );\r\n\t\tCURSORS.put( \"wait\", \"WAIT_CURSOR\" );\r\n\t\t\r\n\t\tCLOSE_OPERATIONS.put( \"nothing\", \"DO_NOTHING_ON_CLOSE\" );\r\n\t\tCLOSE_OPERATIONS.put( \"hide\", \"HIDE_ON_CLOSE\" );\r\n\t\tCLOSE_OPERATIONS.put( \"dispose\", \"DISPOSE_ON_CLOSE\" );\r\n\t\tCLOSE_OPERATIONS.put( \"exit\", \"EXIT_ON_CLOSE\" );\r\n\r\n\t\tString scName = SwingConstants.class.getName();\r\n\t\tALIGNS.put( \"bottom\", scName + \".BOTTOM\" );\r\n\t\tALIGNS.put( \"center\", scName + \".CENTER\" );\r\n\t\tALIGNS.put( \"east\", scName + \".EAST\" );\r\n\t\tALIGNS.put( \"leading\", scName + \".LEADING\" );\r\n\t\tALIGNS.put( \"left\", scName + \".LEFT\" );\r\n\t\tALIGNS.put( \"next\", scName + \".NEXT\" );\r\n\t\tALIGNS.put( \"north\", scName + \".NORTH\" );\r\n\t\tALIGNS.put( \"right\", scName + \".RIGHT\" );\r\n\t\tALIGNS.put( \"top\", scName + \".TOP\" );\r\n\t\tALIGNS.put( \"trailing\", scName + \".TRAILING\" );\r\n\t\tALIGNS.put( \"west\", scName + \".WEST\" );\r\n\t\t\r\n\t\t\r\n\t\tLIST_SEL_MODE.put(\"single\", \"javax.swing.ListSelectionModel.SINGLE_SELECTION\" ); \r\n\t\tLIST_SEL_MODE.put(\"interval\", \"javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION\" );\r\n\t\tLIST_SEL_MODE.put(\"any\", \"javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION\" );\r\n\t}\r\n\t\r\n\t/**\r\n\t * Values for automatic affectation of the correct\r\n\t * parameters for the methods. \r\n\t *\r\n\t */\r\n\tpublic enum ClassType {\r\n\t\tTEXT,\r\n\t\tSTRING,\r\n\t\tCHAR,\r\n\t\tINTEGER,\r\n\t\tBOOLEAN,\r\n\t\tPERCENT,\r\n\t\tCOLOR,\r\n\t\tALIGNMENT,\r\n\t\tDIMENSION,\r\n\t\tINSETS,\r\n\t\tKEYSTROKE,\r\n\t\tVERTICAL_OR_HORIZONTAL, // Not yet implemented\r\n\t\tJSPLITPANE_ORIENTATION,\r\n\t\tJLIST_ORIENTATION,\r\n\t\tICON,\r\n\t\tCURSOR,\r\n\t\tCOMPONENT,\r\n\t\tJTABLE_AUTO_RESIZE, // For JTable implementation\r\n\t\tJLIST_SELECT_MODE,\r\n\t};\r\n\t\r\n\tprivate String attrName;\r\n\tprivate String methodName;\r\n\tprivate String defaultValue = null;\r\n\tprivate ClassType type;\r\n\t\r\n\t/**\r\n\t * Create the attribute.\r\n\t * \r\n\t * @param attributeName the attribute name.\r\n\t * @param methodName the method name (if <code>null</code> then\r\n\t * \t\t\tthe method name is created implicitly based on\r\n\t * \t\t\tthe attribute name with the first character capitalized\r\n\t * \t\t\tand prefixed by \"set\".\r\n\t * @param type the type of the expected variable.\r\n\t * @param defaultValue the default value if exists (usually not provided).\r\n\t * \t\t\tThis default value is used only for some attribute types.\r\n\t */\r\n\tpublic AttributeDefinition( String attributeName, String methodName, ClassType type, String defaultValue ){\r\n\t\tthis.attrName = attributeName;\r\n\t\tif( methodName == null ){\r\n\t\t\tthis.methodName = \"set\" + UIParser.capitalizeFirst(attributeName);\r\n\t\t}\r\n\t\telse {\r\n\t\t\tthis.methodName = methodName;\r\n\t\t}\r\n\t\tthis.type = type;\r\n\t\tthis.defaultValue = defaultValue;\r\n\t}\r\n\r\n\tpublic AttributeDefinition( String attributeName, String methodName, ClassType type ){\r\n\t\tthis( attributeName, methodName, type, null );\r\n\t}\r\n\r\n\tpublic String getParameterIfExist( Element e ) throws UnexpectedTag{\r\n\t\tString[] params = getParameters(e);\r\n\t\treturn( params == null ? null : params[0]);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Get the parameters for this element.\r\n\t * \r\n\t * @param e the element.\r\n\t * @return the list of the arguments or <code>null</code>\r\n\t * \t\tif there is no attribute for this definition.\r\n\t * @throws UnexpectedTag \r\n\t */\r\n\tpublic String[] getParameters( Element e ) throws UnexpectedTag{\r\n\t\tString[] params = null;\r\n\t\t\r\n\t\tswitch( type ){\r\n\t\tcase TEXT :\r\n\t\t\tString txt = Parser.getTextContents(e).trim();\r\n\t\t\tif( txt.trim().length() == 0 ){\r\n\t\t\t\ttxt = Parser.getAttribute(e, \"text\");\r\n\t\t\t}\r\n\t\t\tif( txt != null ){\r\n\t\t\t\tparams = new String[] { JavaCode.toParam(txt) };\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tcase BOOLEAN :\r\n\t\t\tBoolean b = Parser.getBooleanAttribute(e, attrName);\r\n\t\t\tif( b != null ){\r\n\t\t\t\tparams = new String[] { JavaCode.toParam(b) };\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase INTEGER :\r\n\t\t\tInteger i = Parser.getIntegerAttribute(e, attrName);\r\n\t\t\tif( i != null ){\r\n\t\t\t\tparams = new String[] { JavaCode.toParam( i ) };\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase PERCENT :\r\n\t\t\tDouble percent = Parser.getPercentageAttribute(e, attrName);\r\n\t\t\tif( percent != null ){\r\n\t\t\t\tparams = new String[] { JavaCode.toParam( percent.doubleValue() ) };\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase STRING :\r\n\t\t\tString s = Parser.getStringAttribute(e, attrName, defaultValue );\r\n\t\t\tif( s != null ){\r\n\t\t\t\tparams = new String[] { JavaCode.toParam( s ) };\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase CHAR :\r\n\t\t\tString chars = Parser.getAttribute(e, attrName);\r\n\t\t\tif( chars != null ){\r\n\t\t\t\tparams = new String[] { JavaCode.toParam( chars.charAt(0) ) };\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase COLOR :\r\n\t\t\tColor color = Parser.getColorAttribute(e, attrName);\r\n\t\t\tif( color != null ){\r\n\t\t\t\tparams = new String[] { JavaCode.toParam( color ) };\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase ALIGNMENT :\r\n\t\t\tString align = Parser.getAttribute(e, attrName);\r\n\t\t\tif( align != null ){\r\n\t\t\t\tString constant = null;\r\n\t\t\t\tconstant = ALIGNS.get( align.trim().toLowerCase() );\r\n\t\t\t\tif( constant != null ){\r\n\t\t\t\t\tparams = new String[] { constant };\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase ICON :\r\n\t\t\tString iconName = Parser.getAttribute(e, attrName);\r\n\t\t\tif( iconName != null ){\r\n\t\t\t\tString icon;\r\n\t\t\t\tif( iconName.startsWith(\"http:\" ) || iconName.startsWith(\"ftp:\" ) ){\r\n\t\t\t\t\ticon = \"new \" + ImageIcon.class.getName() + \"( new \" + URL.class.getName() + \"( \" + iconName + \") )\";\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\ticon = \"(new javax.swing.ImageIcon(getClass().getResource(\" + JavaClass.toParam(iconName) + \")))\";\r\n\t\t\t\t}\r\n\t\t\t\tparams = new String[] { icon };\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase CURSOR :\r\n\t\t\tString cursorName = Parser.getAttribute(e, attrName);\r\n\t\t\tif( cursorName != null ){\r\n\t\t\t\tString cursor = Cursor.class.getName() + \"getPredefinedCursor( \" + Cursor.class.getName() + cursorName + \") )\";\r\n\t\t\t\tparams = new String[] { cursor };\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase JSPLITPANE_ORIENTATION :\r\n\t\t\tString orientation = Parser.getAttribute(e, attrName);\r\n\t\t\tif( orientation != null ){\r\n\t\t\t\tif( orientation.equalsIgnoreCase(\"horizontal\") ){\r\n\t\t\t\t\tparams = new String[] { \"JSplitPane.HORIZONTAL_SPLIT\" };\r\n\t\t\t\t}\r\n\t\t\t\telse if( orientation.equalsIgnoreCase(\"vertical\") ){\r\n\t\t\t\t\tparams = new String[] { \"JSplitPane.VERTICAL_SPLIT\" };\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tthrow new IllegalArgumentException(\"horizontal or vertical expected for this tag.\" );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase JLIST_ORIENTATION :\r\n\t\t\torientation = Parser.getAttribute(e, attrName);\r\n\t\t\tif( orientation != null ){\r\n\t\t\t\tif( orientation.equalsIgnoreCase(\"hwrap\") ){\r\n\t\t\t\t\tparams = new String[] { \"JList.HORIZONTAL_WRAP\" };\r\n\t\t\t\t}\r\n\t\t\t\telse if( orientation.equalsIgnoreCase(\"vwrap\") ){\r\n\t\t\t\t\tparams = new String[] { \"JSplitPane.VERTICAL_WRAP\" };\r\n\t\t\t\t}\r\n\t\t\t\telse if( orientation.equalsIgnoreCase(\"vertical\") ){\r\n\t\t\t\t\tparams = new String[] { \"JSplitPane.VERTICAL\" };\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tthrow new IllegalArgumentException(\"hwrap, vwrap or vertical expected for this tag.\" );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase DIMENSION :\r\n\t\t\tString dim = Parser.getAttribute(e, attrName);\r\n\t\t\tif( dim != null ){\r\n\t\t\t\tString[] vector = dim.split(\",\");\r\n\t\t\t\tif( vector.length < 2 ){\r\n\t\t\t\t\tthrow new UnexpectedTag(\"attribute \\\"\" + attrName + \"\\\" expects 2 comma separated values.\" );\r\n\t\t\t\t}\r\n\t\t\t\ttry {\r\n\t\t\t\t\tint width = Integer.parseInt( vector[0].trim() );\r\n\t\t\t\t\tint height = Integer.parseInt( vector[1].trim() );\r\n\t\t\t\t\tparams = new String[] { \"new java.awt.Dimension(\" + width + \",\" + height +\")\" };\r\n\t\t\t\t}\r\n\t\t\t\tcatch( NumberFormatException ex ){\r\n\t\t\t\t\tthrow new UnexpectedTag(\"attribute \\\"\" + attrName + \"\\\" expects numeric values.\" );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase INSETS :\r\n\t\t\tString insets = Parser.getAttribute(e, attrName);\r\n\t\t\tif( insets != null ){\r\n\t\t\t\tString[] vector = insets.split(\",\");\r\n\t\t\t\ttry {\r\n\t\t\t\t\tint top = 0, left = 0, bottom = 0, right = 0;\r\n\t\t\t\t\t// if only one value, the inset is assumed for others.\r\n\t\t\t\t\tswitch( vector.length ){\r\n\t\t\t\t\tcase 1 :\r\n\t\t\t\t\t\ttop = Integer.parseInt( vector[0].trim() );\r\n\t\t\t\t\t\tleft = bottom = right = top;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase 2 :\r\n\t\t\t\t\t\tbottom = top = Integer.parseInt( vector[0].trim() );\r\n\t\t\t\t\t\tright = left = Integer.parseInt( vector[1].trim() );\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase 4 :\r\n\t\t\t\t\t\ttop = Integer.parseInt( vector[0].trim() );\r\n\t\t\t\t\t\tleft = Integer.parseInt( vector[1].trim() );\r\n\t\t\t\t\t\tbottom = Integer.parseInt( vector[2].trim() );\r\n\t\t\t\t\t\tright = Integer.parseInt( vector[3].trim() );\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tdefault :\r\n\t\t\t\t\t\tthrow new UnexpectedTag(\"attribute \\\"\" + attrName + \"\\\" expects only 1, 2 or 4 numeric values.\" );\t\t\t\t\t\r\n\t\t\t\t\t}\r\n\t\t\t\t\tparams = new String[] { \"new java.awt.Insets(\" + top + \",\" + left + \",\" + bottom + \",\" + right + \")\" };\r\n\t\t\t\t}\r\n\t\t\t\tcatch( NumberFormatException ex ){\r\n\t\t\t\t\tthrow new UnexpectedTag(\"attribute \\\"\" + attrName + \"\\\" expects numeric values.\" );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase KEYSTROKE :\r\n\t\t\tString keystroke = Parser.getAttribute(e, attrName);\r\n\t\t\tif( keystroke != null ){\r\n\t\t\t\tKeyStroke ks = KeyStroke.getKeyStroke(keystroke);\r\n\t\t\t\tif( ks == null ){\r\n\t\t\t\t\tthrow new UnexpectedTag(\"Keystroke \\\"\" + keystroke + \"\\\" invalid\" );\r\n\t\t\t\t}\r\n\t\t\t\tparams = new String[] { \"javax.swing.KeyStroke.getKeyStroke(\" + JavaClass.toParam(keystroke) + \")\" };\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tcase JTABLE_AUTO_RESIZE :\r\n\t\t\tString autoResizeMode = Parser.getStringAttribute(e, attrName, defaultValue);\r\n\t\t\tif( autoResizeMode != null ){\r\n\t\t\t\tif( autoResizeMode.equalsIgnoreCase(\"off\")){\r\n\t\t\t\t\tparams = new String[] { \"JTable.AUTO_RESIZE_OFF\" };\r\n\t\t\t\t}\r\n\t\t\t\telse if( autoResizeMode.equalsIgnoreCase(\"next\")){\r\n\t\t\t\t\tparams = new String[] { \"JTable.AUTO_RESIZE_NEXT_COLUMN\" };\r\n\t\t\t\t}\r\n\t\t\t\telse if( autoResizeMode.equalsIgnoreCase(\"subsequent\")){\r\n\t\t\t\t\tparams = new String[] { \"JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS\" };\r\n\t\t\t\t}\r\n\t\t\t\telse if( autoResizeMode.equalsIgnoreCase(\"last\")){\r\n\t\t\t\t\tparams = new String[] { \"JTable.AUTO_RESIZE_LAST_COLUMN\" };\r\n\t\t\t\t}\r\n\t\t\t\telse if( autoResizeMode.equalsIgnoreCase(\"all\")){\r\n\t\t\t\t\tparams = new String[] { \"JTable.AUTO_RESIZE_ALL_COLUMNS\" };\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tthrow new UnexpectedTag(\"JTable \\\"autoResizeMode\\\" attribute not valid.\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase JLIST_SELECT_MODE :\r\n\t\t\tString selectMode = Parser.getStringAttribute(e, attrName, defaultValue);\r\n\t\t\tif( selectMode != null ){\r\n\t\t\t\tString constant = null;\r\n\t\t\t\tconstant = LIST_SEL_MODE.get( selectMode.toLowerCase() );\r\n\t\t\t\tif( constant != null ){\r\n\t\t\t\t\tparams = new String[] { constant };\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tthrow new UnexpectedTag(\"value \\\"\" + selectMode + \"\\\" for attribute \" + attrName + \" is not valid.\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tcase VERTICAL_OR_HORIZONTAL :\r\n\t\t\torientation = Parser.getAttribute(e, attrName);\r\n\t\t\tif( orientation != null ){\r\n\t\t\t\tif( orientation.equalsIgnoreCase(\"horizontal\") ){\r\n\t\t\t\t\tparams = new String[] { \"JSlider.HORIZONTAL\" };\r\n\t\t\t\t}\r\n\t\t\t\telse if( orientation.equalsIgnoreCase(\"vertical\") ){\r\n\t\t\t\t\tparams = new String[] { \"JSlider.VERTICAL\" };\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tthrow new IllegalArgumentException(\"horizontal or vertical expected for this tag ('\" + orientation + \"') provided.\" );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tdefault :\r\n\t\t\tif( Parser.getAttribute(e, attrName) != null ){\r\n\t\t\t\tthrow new IllegalArgumentException(\"Type \" + type + \" not yet supported.\" );\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn params;\r\n\t}\r\n\t\r\n\tpublic void addToMethod( JavaMethod jmethod, Element e, String varName ) throws UnexpectedTag{\r\n\t\tString[] params = getParameters(e);\r\n\t\tif( params != null ){\r\n\t\t\tjmethod.addCall( varName + \".\" + methodName, params );\r\n\t\t}\r\n\t}\r\n\t\r\n\r\n}\r", "public class AttributesController {\r\n\tList<AttributeDefinition> list = new ArrayList<AttributeDefinition>();\r\n\tAttributesController parent = null;\r\n\r\n\tpublic AttributesController( AttributesController parent, AttributeDefinition[] arr ){\r\n\t\tthis.parent = parent;\r\n\t\tthis.list.addAll( Arrays.asList(arr) );\r\n\t}\r\n\r\n\tpublic AttributesController( AttributeDefinition[] arr ){\r\n\t\tthis(null,arr);\r\n\t}\r\n\r\n\t/**\r\n\t * @return the parent\r\n\t */\r\n\tpublic AttributesController getParent() {\r\n\t\treturn parent;\r\n\t}\r\n\r\n\t/**\r\n\t * @param parent the parent to set\r\n\t */\r\n\tpublic void setParent(AttributesController parent) {\r\n\t\tthis.parent = parent;\r\n\t}\r\n\r\n\tpublic void addToMethod( JavaMethod jmethod, Element e, String varName ) throws UnexpectedTag{\r\n\t\tif( parent != null ){\r\n\t\t\tparent.addToMethod(jmethod, e, varName);\r\n\t\t}\r\n\t\tfor( AttributeDefinition def : list ){\r\n\t\t\tdef.addToMethod(jmethod, e, varName);\r\n\t\t}\r\n\t}\r\n\t\r\n}\r", "public final class Parser {\r\n\tpublic static final Map<String, Color> COLORS = new HashMap<String, Color>();\r\n\t\r\n\tstatic {\r\n\t\tCOLORS.put( \"black\", Color.BLACK );\r\n\t\tCOLORS.put( \"blue\", Color.BLUE );\r\n\t\tCOLORS.put( \"cyan\", Color.CYAN );\r\n\t\tCOLORS.put( \"darkgray\", Color.DARK_GRAY );\r\n\t\tCOLORS.put( \"gray\", Color.GRAY );\r\n\t\tCOLORS.put( \"green\", Color.GREEN );\r\n\t\tCOLORS.put( \"lightgray\", Color.LIGHT_GRAY );\r\n\t\tCOLORS.put( \"magenta\", Color.MAGENTA );\r\n\t\tCOLORS.put( \"orange\", Color.ORANGE );\r\n\t\tCOLORS.put( \"pink\", Color.PINK );\r\n\t\tCOLORS.put( \"red\", Color.RED );\r\n\t\tCOLORS.put( \"white\", Color.WHITE );\r\n\t\tCOLORS.put( \"yellow\", Color.YELLOW );\r\n\t}\r\n\t\r\n\t/**\r\n\t * The attribute for the variable name of the component.\r\n\t */\r\n\tpublic static final String ID_ATTRIBUTE = \"id\";\r\n\t\r\n\t/**\r\n\t * The attribute for the class name of the component. Usually,\r\n\t * the class name is a predefined class, but if the developper\r\n\t * wants to used an extended class rather than the normal class,\r\n\t * he can do it by changing this attribute. This attribute is available\r\n\t * for any component.\r\n\t * \r\n\t */\r\n\tpublic static final String CLASS_ATTRIBUTE = \"class\";\r\n\t\r\n\tprivate static Map<String, Integer> ids = new HashMap<String, Integer>();\r\n\r\n\t/**\r\n\t * Clear the IDs created before.\r\n\t */\r\n\tpublic static void clearIds(){\r\n\t\tids.clear();\r\n\t}\r\n\t\r\n\tpublic static synchronized String getUniqueId( String root ){\r\n\t\tInteger id = null;\r\n\t\tsynchronized( ids ){\r\n\t\t\tid = ids.get(root);\r\n\t\t\tif( id == null ){\r\n\t\t\t\tid = new Integer(1);\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tid = new Integer( id.intValue() + 1 );\r\n\t\t\t}\r\n\t\t\tids.put(root, id); // Store the new value\r\n\t\t}\r\n\t\treturn root + id.toString();\r\n\t}\r\n\r\n\tpublic static Element getChildElement( Element root, String tagName ) {\r\n\t\tList<Element> list = getChildElements(root,tagName);\r\n\t\tswitch( list.size() ){\r\n\t\t\tcase 0:\r\n\t\t\t\treturn null;\r\n\t\t\t\t\r\n\t\t\tcase 1: \r\n\t\t\t\treturn list.get(0);\r\n\t\t\t\t\r\n\t\t\tdefault :\r\n\t\t\t\tthrow new IllegalArgumentException( \"Multiple <\" + tagName + \"> found. Only one expected.\" ); \r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static List<Element> getChildElements( Element root, String tagName ){\r\n\t\tList<Element> selected = new LinkedList<Element>();\r\n\t\tList<Element> childs = getChildElements(root);\r\n\t\tfor( Element e : childs ){\r\n\t\t\tif( e.getTagName().equals(tagName) ){\r\n\t\t\t\tselected.add(e);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn selected;\r\n\t}\r\n\r\n\t/**\r\n\t * Retrieve the elements contained in the parent element.\r\n\t * \r\n\t * @param e the parent element\r\n\t * @return the child elements.\r\n\t */\r\n\tpublic static List<Element> getChildElements( Element e ){\r\n\t\tNodeList nodes = e.getChildNodes();\r\n\t\tint len = nodes.getLength();\r\n\t\tList<Element> elements = new ArrayList<Element>( len );\r\n\t\tfor(int i = 0; i < len; i++ ){\r\n\t\t\tNode node = nodes.item(i);\r\n\t\t\tif( node.getNodeType() == Node.ELEMENT_NODE ){\r\n\t\t\t\telements.add( (Element)node );\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn elements;\r\n\t}\r\n\t\r\n\tpublic static List<Element> getChildElementsExcept( Element e, String ... list ){\r\n\t\tNodeList nodes = e.getChildNodes();\r\n\t\tint len = nodes.getLength();\r\n\t\tList<Element> elements = new ArrayList<Element>( len );\r\n\t\tfor(int i = 0; i < len; i++ ){\r\n\t\t\tNode node = nodes.item(i);\r\n\t\t\tif( node.getNodeType() == Node.ELEMENT_NODE ){\r\n\t\t\t\tString nodeName = node.getNodeName();\r\n\t\t\t\tboolean toBeAdded = true;\r\n\t\t\t\tfor(int j = 0; j < list.length; j++){\r\n\t\t\t\t\tif( nodeName.equalsIgnoreCase(list[j]) ){\r\n\t\t\t\t\t\ttoBeAdded = false;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif( toBeAdded ) elements.add( (Element)node );\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn elements;\r\n\t}\r\n\r\n\t/**\r\n\t * The attribute as a string.\r\n\t * \r\n\t * @param e the XML element.\r\n\t * @param attributeName the attribute.\r\n\t * @param mandatory if the attribute is mandatory (if the attribute is\r\n\t * \t\tmandatory and not found or is empty, a {@link NullPointerException}\r\n\t * \t\tis thrown).\r\n\t * @return the string value or <code>null</code> if not exists or is\r\n\t * \t\tempty.\r\n\t */\r\n\tpublic static String getAttribute( Element e, String attributeName, boolean mandatory ){\r\n\t\tString value = normalized( e.getAttribute(attributeName) );\r\n\t\tif( mandatory && value == null ){\r\n\t\t\tthrow new NullPointerException( \"<\" + e.getNodeName() + \">: attribute \\\"\" + attributeName + \"\\\" expected.\");\r\n\t\t}\r\n\t\treturn value;\r\n\t}\r\n\r\n\tpublic static String getStringAttribute( Element e, String attributeName, String defaultValue ){\r\n\t\tString value = normalized( e.getAttribute(attributeName) );\r\n\t\treturn (value == null ? defaultValue : value );\r\n\t}\r\n\r\n\tpublic static String getAttribute( Element e, String attributeName ){\r\n\t\treturn getAttribute(e, attributeName, false);\r\n\t}\r\n\r\n\t/**\r\n\t * Get the color attribute. The attribute returned is a \r\n\t * {@link Color} instance (or <code>null</code> if it is not\r\n\t * possible to decode).\r\n\t * \r\n\t * <p>\r\n\t * A color is analysed based on the color's name (yellow, cyan,\r\n\t * dark, etc.) or by the \"<code>#</code>\" character followed\r\n\t * by the color expressed in hexadecimal using the form RRGGBB.\r\n\t * For example, \"<code>#00ff00</code>\" is used for the green color.\r\n\t * </p>\r\n\t * \r\n\t * @param e the XML element.\r\n\t * @param attributeName the attribute name for the color.\r\n\t * @return <code>null</code> is the attribute is empty or\r\n\t * \t\tdoes not exist or we are not able to decode the color,\r\n\t * \t\tthe color value.\r\n\t */\r\n\tpublic static Color getColorAttribute( Element e, String attributeName ){\r\n\t\tColor color = null;\r\n\t\tString s = getAttribute(e, attributeName, false);\r\n\t\tif( s != null && s.length() > 0 ){\r\n\t\t\tif( s.charAt(0) == '#' ){\r\n\t\t\t\t// RVB color...\r\n\t\t\t\ttry {\r\n\t\t\t\t\tint rgb = Integer.parseInt( s.substring(1).trim(), 16 );\r\n\t\t\t\t\tcolor = new Color(rgb);\r\n\t\t\t\t}\r\n\t\t\t\tcatch( NumberFormatException ex ){\r\n\t\t\t\t\t// Error displayed below.\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\t// Use the color array.\r\n\t\t\t\tcolor = COLORS.get(s.toLowerCase());\r\n\t\t\t\tif( color == null ){\r\n\t\t\t\t\t// Last hope before we cancel!\r\n\t\t\t\t\tcolor = Color.getColor(s);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif( color == null ){\r\n\t\t\t\tSystem.err.println(\"<\" + e.getTagName() + \" \" + attributeName + \"= \" + JavaCode.toParam(s) + \">: can not convert to a color.\");\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn color;\r\n\t}\r\n\r\n\t\r\n\t/**\r\n\t * Retrieve the class name for the tag or the defaulted one.\r\n\t * When an object is instantied, we use a default class \r\n\t * (a &lt;label&gt; will create a <code>JLabel</code> obejct)\r\n\t * but you can override the class with the \"class\" attribute\r\n\t * in the tag. This is a solution to provide more power\r\n\t * to an object.\r\n\t * \r\n\t * @param e the tag.\r\n\t * @param clazz the default class to use.\r\n\t * @return the class to be declared in the JAVA code.\r\n\t * \r\n\t */\r\n\tpublic static String getClassName( Element e, Class<?> clazz ){\r\n\t\tString className = getAttribute(e, CLASS_ATTRIBUTE);\r\n\t\treturn( className == null ? clazz.getName() : className );\t\t\r\n\t}\r\n\r\n\t/**\r\n\t * Get the name of the the object. When a tag declares a\r\n\t * new object, this object can have a name (in this case, it\r\n\t * can be accessed by a derived class) or anonymous (the name\r\n\t * is created based on the <i>rootName</> parameter). In many\r\n\t * case, it is not necessary to declare a name except you have\r\n\t * to access the object in the derived class.\r\n\t * \r\n\t * @param e the tag.\r\n\t * @param rootName the default root naming in case the name is\r\n\t * \t\tcreated as an anomymous.\r\n\t * @return the name of the object.\r\n\t * @deprecated do not use anymore because you do not know if \r\n\t * \t\tthe variable is anonymous or not!\r\n\t * @see #addDeclaration(JavaClass, Element, Class) as replacement.\r\n\t */\r\n\tpublic static String getVariableName( Element e, String rootName ){\r\n\t\tString varName = getAttribute(e, ID_ATTRIBUTE);\r\n\t\tif( varName == null ){\r\n\t\t\tvarName = Parser.getUniqueId(rootName);\r\n\t\t}\r\n\t\treturn varName;\t\t\r\n\t}\r\n\r\n\tpublic static String normalized( String s ){\r\n\t\tif( s == null ) return null;\r\n\t\ts = s.trim();\r\n\t\treturn ( s.length() == 0 ? null : s );\r\n\t}\r\n\t\r\n\tprivate static String cleanOf( String source ){\r\n\t\tint len = source.length();\r\n\t\tStringBuilder buf = new StringBuilder(len);\r\n\t\tboolean lastCharIsSpace = true;\r\n\t\tfor( int i = 0; i < len; i++ ){\r\n\t\t\tchar c = source.charAt(i);\r\n\t\t\tboolean isSpace = Character.isWhitespace(c);\r\n\t\t\tif( !isSpace ){\r\n\t\t\t\tlastCharIsSpace = false;\r\n\t\t\t\tbuf.append(c);\r\n\t\t\t}\r\n\t\t\telse if(!lastCharIsSpace){\r\n\t\t\t\tbuf.append(' ');\r\n\t\t\t\tlastCharIsSpace = true;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn buf.toString().trim();\r\n\t}\r\n\r\n\t/**\r\n\t * Get the text contents for a tag. Retrieve the text\r\n\t * enclosed between the beginning and the end of the\r\n\t * tag <i>excluding</i> the text of inner tags.\r\n\t * \r\n\t * <p>\r\n\t * &lt;p&gt;This is an &lt;emph>emphazed&lt;/p&gt; text.&lt;/code&gt;\r\n\t * will return \"This is an text.\"\r\n\t * </p>\r\n\t * \r\n\t * @param e the tag.\r\n\t * @return the text stored in the tag.\r\n\t */\r\n\tpublic static String getTextContents( Element e){\r\n\t\tif(e.hasAttribute(\"_text\")){\r\n\t\t\treturn e.getAttribute(\"_text\");\r\n\t\t}\r\n\r\n\t\t// Look in children\r\n\t\tStringBuilder buf = new StringBuilder();\r\n\t\tNodeList list = e.getChildNodes();\r\n\t\tfor( int i = 0; i < list.getLength(); i++ ){\r\n\t\t\tNode node = list.item(i);\r\n\t\t\tswitch( node.getNodeType() ){\r\n\t\t\t\tcase Node.TEXT_NODE :\r\n\t\t\t\t\tbuf.append( cleanOf( node.getNodeValue() ) );\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase Node.CDATA_SECTION_NODE :\r\n\t\t\t\t\tbuf.append( node.getNodeValue() );\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase Node.ELEMENT_NODE :\r\n\t\t\t\t\tElement elem = (Element)node;\r\n\t\t\t\t\tif( elem.getNodeName().equalsIgnoreCase(\"br\") ){\r\n\t\t\t\t\t\tbuf.append(\"\\n\");\r\n\t\t\t\t\t}\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tdefault:\r\n\t\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn buf.toString();\r\n\t}\r\n\r\n\t/**\r\n\t * Get the boolean attribute.\r\n\t * \r\n\t * @param e the XML element.\r\n\t * @param attributeName the attribute name.\r\n\t * @param defaultValue the default value returned if the attribute does not\r\n\t * \t\texists or is not set to <code>true</code> or <code>false</code>.\r\n\t * @return the value of the attribute or the default value.\r\n\t */\r\n\tpublic static boolean getBooleanAttribute( Element e, String attributeName, boolean defaultValue ){\r\n\t\tBoolean b = getBooleanAttribute(e, attributeName);\r\n\t\tif( b == null ){\r\n\t\t\treturn defaultValue;\r\n\t\t}\r\n\t\treturn b.booleanValue();\r\n\t}\r\n\r\n\tpublic static Boolean getBooleanAttribute( Element e, String attributeName ){\r\n\t\tString s = Parser.getAttribute(e, attributeName);\r\n\t\tif( s == null ) return null;\r\n\t\tif( s.equalsIgnoreCase(Boolean.toString(true)) ) return true;\r\n\t\tif( s.equalsIgnoreCase(Boolean.toString(false)) ) return false;\r\n\t\tSystem.out.println( \"<\" + e.getNodeName() + \"> is expected to have true/false for the attribute \\\"\" + attributeName + \"\\\" instead of \\\"\" + s + \"\\\"\" );\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\tpublic static Integer getIntegerAttribute( Element e, String attributeName ){\r\n\t\tInteger ret = null;\r\n\t\tString s = Parser.getAttribute(e, attributeName);\r\n\t\tif( s == null ) return null;\r\n\t\ttry {\r\n\t\t\tret = Integer.parseInt(s);\r\n\t\t}\r\n\t\tcatch( NumberFormatException ex ){\r\n\t\t\tSystem.out.println(\"<\" + e.getTagName() + \" \" + attributeName + \"= \" + JavaCode.toParam(s) + \">: can not convert to an integer.\");\r\n\t\t}\r\n\t\treturn ret;\r\n\t}\r\n\r\n\tpublic static int getIntegerAttribute( Element e, String attributeName, int defaultValue ){\r\n\t\tInteger ret = getIntegerAttribute(e,attributeName);\r\n\t\treturn( ret == null ? defaultValue : ret.intValue() );\r\n\t}\r\n\r\n\t/**\r\n\t * Get the percentage value. The percentage value can be expressed\r\n\t * directly (with 0.250 for example) or with the percentage\r\n\t * character (25%) at your convenience.\r\n\t * \r\n\t * @param e the XML element.\r\n\t * @param attributeName the attribute to extract.\r\n\t * @return the value expressed as a double (a range from\r\n\t * \t\t0.0 to 1.0� or <code>null</code> if no data available.\r\n\t * \r\n\t */\r\n\tpublic static Double getPercentageAttribute( Element e, String attributeName ){\r\n\t\tdouble factor = 1;\r\n\t\tDouble ret = null;\r\n\t\tString s = Parser.getAttribute(e, attributeName);\r\n\t\tif( s == null ) return null;\r\n\t\ttry {\r\n\t\t\tif( s.endsWith(\"%\") ){\r\n\t\t\t\tfactor = 0.01;\r\n\t\t\t\ts = s.substring(0, s.indexOf(\"%\") ).trim();\r\n\t\t\t}\r\n\t\t\tret = new Double( Double.parseDouble(s) * factor);\r\n\t\t}\r\n\t\tcatch( NumberFormatException ex ){\r\n\t\t\tSystem.out.println(\"<\" + e.getTagName() + \" \" + attributeName + \"= \" + JavaCode.toParam(s) + \">: can not convert to an integer.\");\r\n\t\t}\r\n\t\treturn ret;\r\n\t}\r\n\r\n\tpublic static String addDeclaration( JavaClass jclass, Element e, Class<?> clazz ){\r\n\t\tString className = getClassName( e, clazz, jclass );\r\n\t\treturn addDeclaration(jclass, e, className, ID_ATTRIBUTE );\r\n\t}\r\n\t\r\n\tpublic static String getSimpleName( String fullName ){\r\n\t\tint pos = fullName.lastIndexOf(\".\");\r\n\t\tif( pos > 0 ){\r\n\t\t\treturn fullName.substring(pos+1);\r\n\t\t}\r\n\t\treturn fullName;\r\n\t}\r\n\r\n\tpublic static String addDeclaration( JavaClass jclass, Element e, String className, String attributeName ){\r\n\t\tString modifier = \"protected\";\r\n\t\t\r\n\t\tString varName = (e == null ? null : getAttribute(e, attributeName));\r\n\t\tif( varName == null ){\r\n\t\t\tvarName = Parser.getUniqueId( getSimpleName(className).toLowerCase() );\r\n\t\t\tmodifier = \"private\";\r\n\t\t}\r\n\r\n\t\tjclass.addAnonymousDeclaration( modifier + \" \" + className + \" \" + varName + \" = new \" + className + \"();\" );\r\n\t\tjclass.register( varName, className );\r\n\t\treturn varName;\r\n\t}\r\n\r\n\t/**\r\n\t * Get the class name.\r\n\t * \r\n\t * @param e the element.\r\n\t * @param clazz the default class, this value is overrided if\r\n\t * a attribute {@link #CLASS_ATTRIBUTE} is found.\r\n\t * @param jclass the class on which we declare the import. \r\n\t * @return the name of the class to use to initialize the variables\r\n\t * \t\tin the sepcified class.\r\n\t */\r\n\tpublic static String getClassName( Element e, Class<?> clazz, JavaClass jclass ){\r\n\t\tString className = (e == null ? null : Parser.getAttribute(e, CLASS_ATTRIBUTE));\r\n\t\tif( className == null ){\r\n\t\t\t// Only import standard classes. For classes defined by the user,\r\n\t\t\t// we must avoid use the import process to avoid issues on names.\r\n\t\t\tjclass.addImport(clazz);\r\n\t\t\tclassName = clazz.getSimpleName();\t\t\r\n\t\t}\r\n\t\treturn className;\r\n\t}\r\n\r\n\tpublic static void setDefaultAttributeValue( Element e, String attributeName, String defaultValue ){\r\n\t\tString value = getAttribute(e, attributeName);\r\n\t\tif( value == null ){\r\n\t\t\te.setAttribute(attributeName, defaultValue);\r\n\t\t}\r\n\t}\r\n}\r", "public enum ClassType {\r\n\tTEXT,\r\n\tSTRING,\r\n\tCHAR,\r\n\tINTEGER,\r\n\tBOOLEAN,\r\n\tPERCENT,\r\n\tCOLOR,\r\n\tALIGNMENT,\r\n\tDIMENSION,\r\n\tINSETS,\r\n\tKEYSTROKE,\r\n\tVERTICAL_OR_HORIZONTAL, // Not yet implemented\r\n\tJSPLITPANE_ORIENTATION,\r\n\tJLIST_ORIENTATION,\r\n\tICON,\r\n\tCURSOR,\r\n\tCOMPONENT,\r\n\tJTABLE_AUTO_RESIZE, // For JTable implementation\r\n\tJLIST_SELECT_MODE,\r\n};\r", "@SuppressWarnings(\"serial\")\r\npublic class UnexpectedTag extends SAXException {\r\n\tpublic UnexpectedTag( Element e ){\r\n\t\tsuper(\"Tag <\" + e.getTagName() + \"> unexpected. XPath = \" + xpath(e) );\r\n\t}\r\n\r\n\tpublic UnexpectedTag( String text ){\r\n\t\tsuper(text);\r\n\t}\r\n\t\r\n\tpublic UnexpectedTag( Element e, String text ){\r\n\t\tsuper(\"XPath = \" + xpath(e) + \": \" + text );\r\n\t}\r\n\r\n\tpublic static String xpath(Element root ){\r\n\t\tString ret = \"\";\r\n\t\tNode e = root;\r\n\t\twhile( e != null ) {\r\n\t\t\tret = \"/\" + e.getNodeName() + ret;\r\n\t\t\te = e.getParentNode();\r\n\t\t}\r\n\t\treturn ret;\r\n\t}\r\n}\r", "public class JavaClass extends JavaCode {\r\n\tprivate String fullClassName = null;\r\n\tprivate String extClassName = null;\r\n\tprivate Set<String> implementInterfaces = new HashSet<String>(); \r\n\tprivate JavaType javaType = new JavaType();\r\n\tprivate JavaComments comments = null;\r\n\tprivate LinesOfCode declarations = new LinesOfCode();\r\n\tprivate Set<String> importSet = new HashSet<String>(); \r\n\tprivate Map<String, JavaMethod> methods = new HashMap<String, JavaMethod>();\r\n\tprivate LinesOfCode staticCode = new LinesOfCode();\r\n\tprivate Map<String,JavaClass> innerClasses = new HashMap<String, JavaClass>();\r\n\tprivate Properties props = new Properties();\r\n\tprivate Map<String,String> registered = new HashMap<String, String>();\r\n\r\n\tpublic void addStatic( JavaCode code ){\r\n\t\tstaticCode.addCode(code);\r\n\t}\r\n\r\n\tpublic void addStatic( String line ){\r\n\t\tstaticCode.addCode( new LineOfCode(line) );\r\n\t}\r\n\r\n\t/**\r\n\t * Add the interface. Note once the class implements\r\n\t * an interface, this interface is imported.\r\n\t * \r\n\t * @param iClass the interface class. \r\n\t */\r\n\tpublic void addInterface( Class<?> iClass ){\r\n\t\taddImport(iClass);\r\n\t\timplementInterfaces.add(iClass.getSimpleName());\r\n\t}\r\n\r\n\tpublic void addInterface( String iClass ){\r\n\t\timplementInterfaces.add(iClass);\r\n\t}\r\n\r\n\t/**\r\n\t * @return the comments\r\n\t */\r\n\tpublic JavaComments getComments() {\r\n\t\treturn comments;\r\n\t}\r\n\r\n\t/**\r\n\t * @param comments the comments to set\r\n\t */\r\n\tpublic void setComments(JavaComments comments) {\r\n\t\tthis.comments = comments;\r\n\t}\r\n\r\n\t/**\r\n\t * Retrieve a method based on its name. Note if\r\n\t * several methods having the same name\r\n\t * have been added to this class,\r\n\t * only the first one is returned.\r\n\t * \r\n\t * @param name the method name.\r\n\t * @return the method if one exists with the specified\r\n\t * \t\tname, if not return <code>null</code>.\r\n\t */\r\n\tpublic JavaMethod getMethod( String name ){\r\n\t\treturn methods.get(name);\r\n\t}\r\n\r\n\tpublic String addMethodIfNotExists( JavaMethod m ){\r\n\t\tif( getMethod( m.getName()) == null ){\r\n\t\t\treturn addMethod(m);\r\n\t\t}\r\n\t\treturn m.getName();\r\n\t}\r\n\r\n\tpublic String addMethod( JavaMethod m ){\r\n\t\tString root = m.getName();\r\n\t\tif( methods.containsKey(root) ){\r\n\t\t\tint i = 1;\r\n\t\t\twhile( methods.containsKey(m.getName()+\".\"+i) ){\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t\troot = m.getName() + \".\" + i;\r\n\t\t}\r\n\t\tmethods.put( root, m);\r\n\t\treturn root;\r\n\t}\r\n\r\n\r\n\t/**\r\n\t * Add an anonymous declaration. It means you have to\r\n\t * give all the declaration but the variable is not registred.\r\n\t * \r\n\t * @param lineOfCode the line of code to add in the \r\n\t * \t\tdeclaration part of the class.\r\n\t * @see #register(String, Class) for registring the\r\n\t * \t\tvariable (if necessary).\r\n\t */\r\n\tpublic void addAnonymousDeclaration( CharSequence lineOfCode ) {\r\n\t\tdeclarations.addCode(lineOfCode);\r\n\t}\r\n\r\n\t/**\r\n\t * Add a declaration. \r\n\t * \r\n\t * @param varName the variable name;\r\n\t * @param type the Java type.\r\n\t * @param params the parameters for the initialization. If\r\n\t * \t\t<code>null</code>, there is no initialisation. A\r\n\t * \t\t<code>null</code> array (or no parameter) means\r\n\t * \t\tthe variable is created empty.\r\n\t */\r\n\tpublic void addDeclaration( String varName, JavaType type, String[] params ) {\r\n\t\t// jclass.addDeclaration( modifier + \" \" + className + \" \" + varName + \" = new \" + className + \"();\" );\r\n\t\tStringBuilder buf = new StringBuilder();\r\n\t\tbuf.append( type ).append(\" \").append(varName);\r\n\t\tif( params != null ){\r\n\t\t\tbuf.append( \" = new \" ).append( type.getClassName() ).append(\"(\");\r\n\t\t\tfor( int i = 0; i < params.length; i++ ){\r\n\t\t\t\tif( i > 1 ) buf.append(\", \");\r\n\t\t\t\tbuf.append( params[i] );\r\n\t\t\t}\r\n\t\t\tbuf.append(\")\");\r\n\t\t}\r\n\t\tbuf.append(\";\");\r\n\t\tdeclarations.addCode(buf.toString());\r\n\t}\r\n\t\r\n\t/**\r\n\t * Add the class specified as an import of\r\n\t * the current class. It simplifies the code\r\n\t * created.\r\n\t * \r\n\t * @param className the class name.\r\n\t * @see #addImport(Class)\r\n\t */\r\n\tpublic void addImport( String className ){\r\n\t\timportSet.add(className);\r\n\t}\r\n\r\n\t/**\r\n\t * Import a new class in the class. The class can\r\n\t * be referenced with its simple name. For example,\r\n\t * if you import the <code>java.util.List</code> class,\r\n\t * you will be able to refer to it with <code>List</code>\r\n\t * only.\r\n\t * \r\n\t * <p>You can import the same class multiple times:\r\n\t * the class name imported is registred to avoid\r\n\t * duplicate lines in the final code.\r\n\t * </p>\r\n\t * \r\n\t * @param clazz the class to import.\r\n\t */\r\n\tpublic void addImport( Class<?> clazz ){\r\n\t\taddImport( clazz.getName() );\r\n\t}\r\n\r\n\t/**\r\n\t * Creates the class.\r\n\t * \r\n\t * @param name the class name (a full name including\r\n\t * \t\tthe package; if not the class will be created\r\n\t * \t\tin the default package).\r\n\t */\r\n\tpublic JavaClass( String name ){\r\n\t\tthis.fullClassName = name;\r\n\t}\r\n\t\r\n\tpublic JavaMethod getConstructor( JavaParam ... params ){\r\n\t\tJavaMethod constructor = new JavaMethod( this.getClassName() );\r\n\t\tconstructor.setReturnType(new JavaType(\"\"));\r\n\t\tconstructor.setParams(params);\r\n\t\taddMethod(constructor);\r\n\t\treturn constructor;\r\n\t}\r\n\t\r\n\tpublic String getClassName(){\r\n\t\tint pos = fullClassName.lastIndexOf(\".\");\r\n\t\treturn (pos < 0 ? fullClassName : fullClassName.substring(pos+1) );\r\n\t}\r\n\r\n\t/**\r\n\t * Checks if a class has been imported.\r\n\t * \r\n\t * @param clazz the class to import.\r\n\t * @return <code>true</code> if the class already\r\n\t * \t\texists in the import list, <code>false</code>\r\n\t * \t\tin the other cases.\r\n\t */\r\n\tpublic boolean isImported( Class<?> clazz ){\r\n\t\treturn importSet.contains(clazz.getName());\r\n\t}\r\n\t\r\n\tpublic void setExtend( Class<?> clazz ){\r\n\t\textClassName = (isImported( clazz ) ? clazz.getSimpleName() : clazz.getName());\r\n\t}\r\n\r\n\tpublic void setExtend( String clazzName ){\r\n\t\textClassName = clazzName;\r\n\t}\r\n\t\r\n\tpublic static String name2file( String s ){\r\n\t\tStringBuilder buf = new StringBuilder();\r\n\t\tfor(int i = 0; i < s.length(); i++ ){\r\n\t\t\tchar c = s.charAt(i);\r\n\t\t\tswitch( c ){\r\n\t\t\tcase '.' : buf.append( File.separator ); break;\r\n\t\t\tdefault : buf.append(c); break;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn buf.toString();\r\n\t}\r\n\r\n\t/**\r\n\t * Get the package name for this class.\r\n\t * \r\n\t * @return the package name\r\n\t */\r\n\tpublic String getPackageName(){\r\n\t\tint pos = fullClassName.lastIndexOf(\".\");\r\n\t\treturn (pos < 0 ? null : fullClassName.substring(0,pos) );\r\n\t}\r\n\r\n\tpublic void newAnonymousClass( String className, JavaClass clazz, String params ) throws IOException {\r\n\t\t\r\n\t}\r\n\r\n\t/**\r\n\t * Write the class on the disk.\r\n\t * \r\n\t * @param rootDir the root directory for the JAVA source\r\n\t * \t\tcode.\r\n\t * @return the path of the JAVA class. \r\n\t * @throws IOException if an i/O error occurred.\r\n\t */\r\n\tpublic String writeClass( String rootDir ) throws IOException {\r\n\t\tString packageName = getPackageName();\r\n\t\tString className = getClassName();\r\n\t\t\r\n\t\tString packageDir = \"\";\r\n\t\tif( packageName != null ){\r\n\t\t\tpackageDir = File.separator + name2file( packageName );\r\n\t\t}\r\n\t\tString fileName = rootDir + packageDir + File.separator + className + \".java\";\r\n\t\t\r\n\t\tWriter w = new OutputStreamWriter( new FileOutputStream(fileName) );\r\n\t\tif( packageName != null ){\r\n\t\t\tprintln( w, \"package \" + packageName + \";\" );\r\n\t\t}\r\n\t\t\r\n\t\t// Import classes\r\n\t\tString[] importArray = importSet.toArray(new String[0]);\r\n\t\tArrays.sort(importArray);\r\n\t\tString rootName = \"\";\r\n\t\tfor( String importLibraryName : importArray ){\r\n\t\t\tString[] subNames = importLibraryName.split(\"\\\\.\");\r\n\t\t\tif( !subNames[0].equals(rootName) ){\r\n\t\t\t\tprintln(w);\r\n\t\t\t\trootName = subNames[0];\r\n\t\t\t}\r\n\t\t\tprintln( w, \"import \" + importLibraryName + \";\" );\r\n\t\t}\r\n\t\tprintln(w);\r\n\r\n\t\twriteCode(w, 0,false);\r\n\t\tw.close();\r\n\t\treturn fileName;\r\n\t}\r\n\r\n\t@Override\r\n\tprotected void writeCode(Writer w, int tabs) throws IOException {\r\n\t\twriteCode(w, tabs,false);\r\n\t}\r\n\r\n\tpublic void writeAnonymous(Writer w, int tabs) throws IOException {\r\n\t\twriteCode(w, tabs, true);\r\n\t}\r\n\r\n\tpublic String toParam() {\r\n\t\ttry {\r\n\t\t\tStringWriter w = new StringWriter(); \r\n\t\t\twriteCode(w, 0, true);\r\n\t\t\tw.close();\r\n\t\t\treturn w.getBuffer().toString();\r\n\t\t}\r\n\t\tcatch(IOException ex ){\r\n\t\t\tthrow new OutOfMemoryError(\"I/O Error:\" + ex.getMessage());\r\n\t\t}\r\n\t}\r\n\r\n\tprotected void writeCode(Writer w, int tabs, boolean anonymous) throws IOException {\r\n\t\t\r\n\t\tif( anonymous ){\r\n\t\t\tw.write(\"new \" + getClassName() + \"() \" );\r\n\t\t}\r\n\t\telse {\r\n\t\t\t// Comments\r\n\t\t\tif( comments != null ) comments.writeCode(w, tabs);\r\n\t\t\r\n\t\t\t// Class declaration\r\n\t\t\tjavaType.setClassName(\"class\");\r\n\t\t\tw.write( javaType + \" \" + getClassName() );\r\n\t\t\tif( extClassName != null ) {\r\n\t\t\t\tString extend = \"extends\";\r\n\t\t\t\ttry {\r\n\t\t\t\t\tClass<?> clazz = Class.forName(extClassName);\r\n\t\t\t\t\tif( clazz.isInterface() ){\r\n\t\t\t\t\t\textend = \"implements\";\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tcatch(ClassNotFoundException ex){\r\n\t\t\t\t\t// Simply ignore in case we not found the class\r\n\t\t\t\t}\r\n\t\t\t\tw.write( \" \" + extend + \" \" + extClassName );\r\n\t\t\t}\r\n\r\n\t\t\tif( this.implementInterfaces.size() > 0 ){\r\n\t\t\t\t// Interfaces implemented.\r\n\t\t\t\tboolean first = true;\r\n\t\t\t\tfor(String className : this.implementInterfaces){\r\n\t\t\t\t\tw.write( first ? \" implements \" : \", \" );\r\n\t\t\t\t\tw.write(className);\r\n\t\t\t\t\tfirst = false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tw.write( \" {\" + JavaCode.CRLF );\r\n\t\t\r\n\t\tdeclarations.writeCode(w, tabs + 1);\r\n\t\t\r\n\t\tif( staticCode.size() > 0 ){\r\n\t\t\tString prefix = (anonymous ? \"\" : \"static \");\r\n\t\t\tw.write( getTabulations(tabs+1) + prefix + \"{\" + JavaCode.CRLF );\r\n\t\t\tstaticCode.writeCode(w, tabs+2);\r\n\t\t\tw.write( getTabulations(tabs+1) + \"}\" + JavaCode.CRLF );\r\n\t\t}\r\n\r\n\t\tfor( JavaClass c : innerClasses.values() ){\r\n\t\t\tc.writeCode(w, tabs+1, false);\r\n\t\t}\r\n\r\n\t\t// Methods...\r\n\t\tfor( JavaMethod m : methods.values() ){\r\n\t\t\tprintln(w);\r\n\t\t\tm.writeCode(w, tabs+1);\r\n\t\t}\r\n\t\t\r\n\t\t// Class ending\r\n\t\tw.write( \"}\" + JavaCode.CRLF + JavaCode.CRLF );\r\n\t}\r\n\t\r\n\t/**\r\n\t * Register an object. The registration of an object\r\n\t * is a simple way to mark the object to be owned\r\n\t * by the class. It is just a flag (no code is\r\n\t * associated). The registration is used to\r\n\t * register a group or some similar stuff.\r\n\t * \r\n\t * @param obj the name of the object to register.\r\n\t * @param clazz the class of the object.\r\n\t */\r\n\tpublic void register( String obj, Class<?> clazz ){\r\n\t\tregistered.put(obj, clazz.getName());\r\n\t}\r\n\r\n\tpublic void register( String obj, String className ){\r\n\t\tregistered.put(obj, className );\r\n\t}\r\n\r\n\tpublic boolean isRegistered( String obj ){\r\n\t\tString className = registered.get(obj);\r\n\t\treturn (className != null);\r\n\t}\r\n\t\r\n\tpublic void addInnerClass( JavaClass jclass ){\r\n\t\tinnerClasses.put( jclass.getClassName(), jclass );\r\n\t\t\r\n\t}\r\n\t\r\n\t/**\r\n\t * Dummy method: returns 0x0104 for the release\r\n\t * 1.5 of the JAVA classes.\r\n\t * \r\n\t * @return the version of the java classes.\r\n\t * \r\n\t */\r\n\tpublic int getVersion() {\r\n\t\treturn 0x0105;\r\n\t}\r\n\r\n /**\r\n * Set a property to this class. A proprty has no meaning and is\r\n * not used to construct the class. Nevertheless, it can be helpful\r\n * to store some global information during the construction of the\r\n * class. \r\n *\r\n * @param key the key to be placed into this property list.\r\n * @param value the value corresponding to <tt>key</tt>.\r\n * @see #getProperty\r\n */\r\n\tpublic void setProperty(String key, String value){\r\n\t\tprops.setProperty(key, value);\r\n\t}\r\n\r\n /**\r\n * Searches for the property with the specified key in this property list.\r\n * If the key is not found in this property list, the method returns\r\n * <code>null</code>.\r\n *\r\n * @param key the property key.\r\n * @return the value in this property list with the specified key value.\r\n * @see #setProperty\r\n */\r\n\tpublic String getProperty(String key){\r\n\t\treturn props.getProperty(key);\r\n\t}\r\n\t\r\n\tpublic void setModifiers( int modifiers ){\r\n\t\tjavaType.setAccess(modifiers);\r\n\t}\r\n}\r", "public class JavaMethod extends JavaBlock {\r\n\t// JavaBlock contents = new JavaBlock();\r\n\tJavaComments comments = new JavaComments();\r\n\tString name;\r\n\tJavaType returnType = new JavaType( \"void\" );\r\n\t\r\n\t/**\r\n\t * @return the returnType\r\n\t */\r\n\tpublic JavaType getReturnType() {\r\n\t\treturn returnType;\r\n\t}\r\n\r\n\t/**\r\n\t * @param returnType the returnType to set\r\n\t */\r\n\tpublic void setReturnType(JavaType returnType) {\r\n\t\tthis.returnType = returnType;\r\n\t}\r\n\r\n\tList<JavaParam> params = new ArrayList<JavaParam>();\r\n\t/**\r\n\t * @return the params\r\n\t */\r\n\tpublic JavaParam[] getParams() {\r\n\t\treturn params.toArray(new JavaParam[0]);\r\n\t}\r\n\r\n\tpublic JavaComments getComments(){\r\n\t\treturn this.comments;\r\n\t}\r\n\r\n\tpublic void setComments( JavaComments comments ){\r\n\t\tthis.comments = comments;\r\n\t}\r\n\r\n\tpublic void setComments( String comments ){\r\n\t\tthis.comments = new JavaComments(comments);\r\n\t}\r\n\r\n\t/**\r\n\t * @param params the params to set\r\n\t */\r\n\tpublic void setParams(JavaParam ... params) {\r\n\t\tthis.params = Arrays.asList( params );\r\n\t}\r\n\r\n\t\r\n\tpublic JavaMethod(){\r\n\t}\r\n\r\n\tpublic JavaMethod( String name ){\r\n\t\tthis();\r\n\t\tthis.name = name;\r\n\t}\r\n\r\n\tpublic JavaMethod( String name, JavaParam ... params ){\r\n\t\tthis(name);\r\n\t\tsetParams(params);\r\n\t}\r\n\r\n\r\n\r\n//\tpublic void addCode( JavaCode code ){\r\n//\t\tcontents.addCode(code);\r\n//\t}\r\n\r\n\t/**\r\n\t * @return the name\r\n\t */\r\n\tpublic String getName() {\r\n\t\treturn name;\r\n\t}\r\n\r\n\t/**\r\n\t * @param name the name to set\r\n\t */\r\n\tpublic void setName(String name) {\r\n\t\tthis.name = name;\r\n\t}\r\n\r\n\r\n\t@Override\r\n\tprotected void writeCode(Writer writer, int tabs) throws IOException {\r\n\t\tString tab = getTabulations(tabs);\r\n\t\tif( comments != null) comments.writeCode(writer, tabs);\r\n\t\twriter.write( tab + returnType + \" \" + getName() + \"(\" );\r\n\t\tboolean firstParam = true;\r\n\t\tfor( JavaParam param : params ){\r\n\t\t\tif( !firstParam ){\r\n\t\t\t\twriter.write(\", \");\r\n\t\t\t}\r\n\t\t\twriter.write( param.toString() );\r\n\t\t\tfirstParam = false;\r\n\t\t}\r\n\t\twriter.write( \")\" + CRLF );\r\n\t\tsuper.writeCode(writer, tabs);\r\n\t}\r\n\r\n\t/**\r\n\t * Add a line comment in the method. The\r\n\t * comment starts with \"//\" and it is added\r\n\t * at the end of the current code. \r\n\t * \r\n\t * @param comment the comment line to add.\r\n\t * @see #setComments(JavaComments) to set\r\n\t * \t\tthe comments of the method. \r\n\t */\r\n\tpublic void addLineComment( String comment ){\r\n\t\tJavaComments cmt = new JavaComments();\r\n\t\tcmt.setJavaDoc(false);\r\n\t\tcmt.add(comment);\r\n\t\taddCode(cmt);\r\n\t}\r\n\r\n}\r" ]
import javax.swing.text.JTextComponent; import org.w3c.dom.Element; import com.oxande.xmlswing.AttributeDefinition; import com.oxande.xmlswing.AttributesController; import com.oxande.xmlswing.Parser; import com.oxande.xmlswing.AttributeDefinition.ClassType; import com.oxande.xmlswing.UnexpectedTag; import com.oxande.xmlswing.jcode.JavaClass; import com.oxande.xmlswing.jcode.JavaMethod;
package com.oxande.xmlswing.components; /** * The JTextComponent implementation. * * @author wrey75 * @version $Rev: 85 $ * */ public class JTextComponentUI extends JComponentUI { public static final AttributeDefinition[] PROPERTIES = { new AttributeDefinition( "caretColor", "setCaretColor", ClassType.COLOR ), new AttributeDefinition( "disabledTextColor", "setDisabledTextColor", ClassType.COLOR ), new AttributeDefinition( "selectionColor", "setSelectionColor", ClassType.COLOR ), DRAGGABLE_ATTRIBUTE_DEF, new AttributeDefinition( "editable", "setEditable", ClassType.BOOLEAN ), new AttributeDefinition( "*", "setText", ClassType.TEXT ), }; public static final AttributesController CONTROLLER = new AttributesController( JComponentUI.CONTROLLER, PROPERTIES );
public String parse(JavaClass jclass, JavaMethod initMethod, Element root ) throws UnexpectedTag{
5
Samourai-Wallet/sentinel-android
app/src/main/java/com/samourai/sentinel/Network.java
[ "public class WebSocketService extends Service {\n\n private Context context = null;\n\n private Timer timer = new Timer();\n private static final long checkIfNotConnectedDelay = 15000L;\n private WebSocketHandler webSocketHandler = null;\n private final Handler handler = new Handler();\n private String[] addrs = null;\n\n public static List<String> addrSubs = null;\n\n @Override\n public void onCreate() {\n\n super.onCreate();\n\n //\n context = this.getApplicationContext();\n\n List<String> addrSubs = SamouraiSentinel.getInstance(WebSocketService.this).getAllAddrsSorted();\n addrs = addrSubs.toArray(new String[addrSubs.size()]);\n\n if(addrs.length == 0) {\n return;\n }\n\n webSocketHandler = new WebSocketHandler(WebSocketService.this, addrs);\n connectToWebsocketIfNotConnected();\n\n timer.scheduleAtFixedRate(new TimerTask() {\n @Override\n public void run() {\n handler.post(new Runnable() {\n @Override\n public void run() {\n connectToWebsocketIfNotConnected();\n }\n });\n }\n }, 5000, checkIfNotConnectedDelay);\n\n }\n\n @Override\n public int onStartCommand(Intent intent, int flags, int startId) {\n return START_STICKY;\n }\n\n @Override\n public IBinder onBind(Intent intent) {\n return null;\n }\n\n public void connectToWebsocketIfNotConnected()\n {\n try {\n if(!webSocketHandler.isConnected()) {\n webSocketHandler.start();\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n public void stop() {\n try {\n if(webSocketHandler != null) {\n webSocketHandler.stop();\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n @Override\n public void onDestroy()\n {\n stop();\n super.onDestroy();\n }\n\n}", "public class TorManager {\n private static final String TAG = \"TorManager\";\n private boolean changingIdentity = false;\n\n public boolean newIDentity() {\n return this.onionProxyManager.newIdentity();\n }\n\n public enum CONNECTION_STATES {\n IDLE,\n CONNECTED,\n DISCONNECTED,\n CONNECTING\n }\n\n static TorManager instance;\n private int currentPort = 0;\n\n private Proxy proxy = null;\n public CONNECTION_STATES state = CONNECTION_STATES.IDLE;\n public Subject<CONNECTION_STATES> torStatus = PublishSubject.create();\n private OnionProxyManager onionProxyManager;\n public boolean isProcessRunning = false;\n String fileStorageLocation = \"torfiles\";\n\n private static Context context = null;\n\n public static TorManager getInstance(Context ctx) {\n\n context = ctx;\n\n if (instance == null) {\n instance = new TorManager(context);\n }\n return instance;\n }\n\n private TorManager(Context context) {\n\n torStatus.onNext(CONNECTION_STATES.DISCONNECTED);\n onionProxyManager = new AndroidOnionProxyManager(context, fileStorageLocation);\n }\n\n public Observable<Proxy> startTor() {\n Log.i(TAG, \"startTor: \");\n return Observable.fromCallable(() -> {\n state = CONNECTION_STATES.CONNECTING;\n torStatus.onNext(CONNECTION_STATES.CONNECTING);\n\n int totalSecondsPerTorStartup = 4 * 60;\n int totalTriesPerTorStartup = 5;\n try {\n boolean ok = onionProxyManager.startWithRepeat(totalSecondsPerTorStartup, totalTriesPerTorStartup);\n if (!ok) {\n System.out.println(\"Couldn't start tor\");\n throw new RuntimeException(\"Couldn't start tor\");\n }\n while (!onionProxyManager.isRunning())\n Thread.sleep(90);\n proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(\"127.0.0.1\", onionProxyManager.getIPv4LocalHostSocksPort()));\n currentPort = onionProxyManager.getIPv4LocalHostSocksPort();\n if (torStatus.hasObservers()) {\n torStatus.onNext(CONNECTION_STATES.CONNECTED);\n }\n isProcessRunning = true;\n state = CONNECTION_STATES.CONNECTED;\n\n return proxy;\n } catch (Exception e) {\n e.printStackTrace();\n\n if (!onionProxyManager.isRunning()) {\n state = CONNECTION_STATES.DISCONNECTED;\n if (torStatus.hasObservers()) {\n torStatus.onNext(CONNECTION_STATES.DISCONNECTED);\n }\n }\n e.printStackTrace();\n return proxy;\n }\n });\n\n }\n\n public String getLatestLogs() {\n try {\n if (onionProxyManager != null && onionProxyManager.isRunning()) {\n String log = onionProxyManager.getLastLog();\n try {\n if (!TorManager.isPortOpen(\"127.0.0.1\", onionProxyManager.getIPv4LocalHostSocksPort(), 4000)) {\n this.state = CONNECTION_STATES.DISCONNECTED;\n if (torStatus.hasObservers()) {\n torStatus.onNext(CONNECTION_STATES.DISCONNECTED);\n }\n }\n int port = onionProxyManager.getIPv4LocalHostSocksPort();\n if (currentPort != port) {\n setProxy(port);\n }\n\n } catch (Exception e) {\n Log.i(TAG, \"getLatestLogs: LOG\");\n e.printStackTrace();\n }\n return log;\n } else {\n return \"Disconnected state\";\n }\n } catch (IOException e) {\n e.printStackTrace();\n return \"\";\n }\n }\n\n private void setProxy(int port) {\n this.proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(\"127.0.0.1\", port));\n }\n\n public boolean isRequired() {\n Log.i(TAG, \"isRequired: \".concat(String.valueOf(PrefsUtil.getInstance(context).getValue(PrefsUtil.ENABLE_TOR, false))));\n return PrefsUtil.getInstance(context).getValue(PrefsUtil.ENABLE_TOR, false);\n }\n\n public boolean isConnected() {\n Log.i(TAG, \"isConnected: \");\n return this.state == CONNECTION_STATES.CONNECTED;\n }\n\n public Proxy getProxy() {\n return proxy;\n }\n\n public Observable<Boolean> stopTor() {\n Log.i(TAG, \"stopTor: \");\n if (torStatus.hasObservers()) {\n torStatus.onNext(CONNECTION_STATES.DISCONNECTED);\n state = CONNECTION_STATES.DISCONNECTED;\n }\n return Observable.fromCallable(() -> {\n try {\n this.state = CONNECTION_STATES.DISCONNECTED;\n if (torStatus.hasObservers()) {\n torStatus.onNext(CONNECTION_STATES.DISCONNECTED);\n }\n isProcessRunning = false;\n } catch (Exception ex) {\n ex.printStackTrace();\n this.state = CONNECTION_STATES.DISCONNECTED;\n if (torStatus.hasObservers()) {\n torStatus.onNext(CONNECTION_STATES.DISCONNECTED);\n }\n isProcessRunning = false;\n return false;\n }\n\n return true;\n });\n\n }\n\n public Subject<CONNECTION_STATES> getTorStatus() {\n return torStatus;\n }\n\n\n public void setTorState(CONNECTION_STATES state) {\n this.state = state;\n if (torStatus.hasObservers()) {\n torStatus.onNext(state);\n }\n }\n\n public static boolean isPortOpen(final String ip, final int port, final int timeout) {\n\n try {\n Socket socket = new Socket();\n socket.connect(new InetSocketAddress(ip, port), timeout);\n socket.close();\n return true;\n } catch (ConnectException ce) {\n ce.printStackTrace();\n return false;\n } catch (Exception ex) {\n ex.printStackTrace();\n return false;\n }\n }\n\n public JSONObject toJSON() {\n\n JSONObject jsonPayload = new JSONObject();\n\n try {\n\n jsonPayload.put(\"active\", PrefsUtil.getInstance(context).getValue(PrefsUtil.ENABLE_TOR, false));\n\n }\n catch(JSONException je) {\n ;\n }\n\n return jsonPayload;\n }\n\n public void fromJSON(JSONObject jsonPayload) {\n\n try {\n\n if(jsonPayload.has(\"active\")) {\n PrefsUtil.getInstance(context).setValue(PrefsUtil.ENABLE_TOR, jsonPayload.getBoolean(\"active\"));\n }\n\n }\n catch(JSONException ex) {\n throw new RuntimeException(ex);\n }\n\n }\n\n\n}", "public class TorService extends Service {\n\n public static String START_SERVICE = \"START_SERVICE\";\n public static String STOP_SERVICE = \"STOP_SERVICE\";\n public static String RESTART_SERVICE = \"RESTART_SERVICE\";\n public static String RENEW_IDENTITY = \"RENEW_IDENTITY\";\n public static int TOR_SERVICE_NOTIFICATION_ID = 95;\n private static final String TAG = \"TorService\";\n private CompositeDisposable compositeDisposable = new CompositeDisposable();\n private String title = \"TOR\";\n private Disposable torDisposable;\n private boolean identityChanging;\n\n @Override\n\n public void onCreate() {\n super.onCreate();\n Notification notification = new NotificationCompat.Builder(this, TOR_CHANNEL_ID)\n .setContentTitle(title)\n .setContentText(\"Waiting...\")\n .setOngoing(true)\n .setSound(null)\n .setGroupAlertBehavior(GROUP_ALERT_SUMMARY)\n .setGroup(\"Tor\")\n .setCategory(NotificationCompat.CATEGORY_PROGRESS)\n .setGroupSummary(false)\n .setSmallIcon(R.drawable.ic_tor_notification)\n .build();\n\n startForeground(TOR_SERVICE_NOTIFICATION_ID, notification);\n\n }\n\n\n private NotificationCompat.Action getStopAction(String message) {\n\n Intent broadcastIntent = new Intent(this, TorBroadCastReceiver.class);\n broadcastIntent.setAction(STOP_SERVICE);\n\n PendingIntent actionIntent = PendingIntent.getBroadcast(this,\n 0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);\n\n return new NotificationCompat.Action(R.drawable.ic_tor_notification, message, actionIntent);\n }\n\n\n private NotificationCompat.Action getRestartAction() {\n\n Intent broadcastIntent = new Intent(this, TorBroadCastReceiver.class);\n broadcastIntent.setAction(RENEW_IDENTITY);\n\n PendingIntent actionIntent = PendingIntent.getBroadcast(this,\n 0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);\n\n return new NotificationCompat.Action(R.drawable.ic_tor_notification, \"New identity\", actionIntent);\n }\n\n @Override\n public int onStartCommand(Intent intent, int flags, int startId) {\n\n if (Objects.requireNonNull(intent.getAction()).equals(TorService.STOP_SERVICE)) {\n//\n// if (DojoUtil.getInstance(getApplicationContext()).getDojoParams() != null && !intent.hasExtra(\"KILL_TOR\")) {\n// Toast.makeText(getApplicationContext(), \"You cannot stop Tor service when dojo is connected\", Toast.LENGTH_SHORT).show();\n// return START_STICKY;\n// }\n\n Disposable disposable = TorManager.getInstance(getApplicationContext())\n .stopTor()\n .subscribe(stat -> {\n compositeDisposable.dispose();\n stopSelf();\n }, error -> {\n//\n });\n compositeDisposable.add(disposable);\n\n } else if (intent.getAction().equals(TorService.RENEW_IDENTITY)) {\n LogUtil.info(TAG, \"onStartCommand: RENEW_IDENTITY\");\n renewIdentity();\n return START_STICKY;\n } else if (Objects.requireNonNull(intent.getAction()).equals(TorService.START_SERVICE)) {\n if (!TorManager.getInstance(getApplicationContext()).isProcessRunning) {\n startTor();\n }\n }\n\n return START_STICKY;\n\n }\n\n private void renewIdentity() {\n if (identityChanging) {\n return;\n }\n identityChanging = true;\n updateNotification(\"Renewing Tor identity...\");\n Disposable disposable = Observable.fromCallable(() -> TorManager.getInstance(getApplicationContext()).newIDentity()).subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribe(t -> {\n Log.i(TAG, \"renewIdentity: \".concat(String.valueOf(t)));\n Disposable disposable1 = Observable.fromCallable(() -> TorManager.getInstance(getApplicationContext()).getLatestLogs()).observeOn(AndroidSchedulers.mainThread())\n .subscribeOn(Schedulers.io())\n .subscribe(s -> {\n if (s.contains(\"NEWNYM\")) {\n Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();\n\n } else {\n Toast.makeText(getApplicationContext(), \"Tor identity renewed\", Toast.LENGTH_SHORT).show();\n }\n\n }, err -> {\n err.printStackTrace();\n });\n compositeDisposable.add(disposable1);\n identityChanging = false;\n if (BuildConfig.DEBUG) {\n// Disposable disposable2 = checkIp()\n// .subscribeOn(Schedulers.io())\n// .observeOn(AndroidSchedulers.mainThread())\n// .subscribe(o -> {\n// Log.i(TAG, \"restart: \".concat(o));\n//\n// });\n//\n// compositeDisposable.add(disposable2);\n\n }\n\n }, error -> {\n Log.i(TAG, \"restart: \".concat(error.getMessage()));\n error.printStackTrace();\n });\n compositeDisposable.add(disposable);\n }\n\n// // for testing purpose\n// private Observable<String> checkIp() {\n// return Observable.fromCallable(() -> WebUtil.getInstance(getApplicationContext()).getURL(\"http://checkip.amazonaws.com\"));\n//\n// }\n\n private void startTor() {\n title = \"Tor: Waiting\";\n updateNotification(\"Connecting....\");\n if (torDisposable != null) {\n compositeDisposable.delete(torDisposable);\n Log.i(TAG, \"startTOR: \".concat(String.valueOf(torDisposable.isDisposed())));\n }\n\n torDisposable = TorManager\n .getInstance(getApplicationContext())\n .startTor()\n .debounce(100, TimeUnit.MILLISECONDS)\n .subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribe(proxy -> {\n title = \"Tor: Running\";\n updateNotification(\"Running....\");\n }, Throwable::printStackTrace);\n compositeDisposable.add(torDisposable);\n\n\n Disposable statusDisposable = TorManager.getInstance(this)\n .torStatus\n .subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribe(state -> {\n });\n logger();\n compositeDisposable.add(statusDisposable);\n }\n\n private void logger() {\n Disposable logger = Observable.interval(2, TimeUnit.SECONDS, Schedulers.io())\n .map(tick -> TorManager.getInstance(getApplicationContext()).getLatestLogs())\n .observeOn(AndroidSchedulers.mainThread())\n .retryWhen(errors -> errors.zipWith(Observable.range(1, 3), (n, i) -> i))\n .subscribe(this::updateNotification, error -> {\n error.printStackTrace();\n if (!TorManager.getInstance(getApplicationContext()).isConnected())\n updateNotification(\"Disconnected\");\n });\n compositeDisposable.add(logger);\n\n }\n\n @Override\n public void onDestroy() {\n compositeDisposable.dispose();\n super.onDestroy();\n }\n\n private void updateNotification(String content) {\n// Log.i(TAG, \"Tor Log: \".concat(content));\n if (content.isEmpty()) {\n content = \"Bootstrapping...\";\n }\n if (TorManager.getInstance(this).state == TorManager.CONNECTION_STATES.CONNECTED) {\n title = \"Tor: Connected\";\n }\n\n if (TorManager.getInstance(this).state == TorManager.CONNECTION_STATES.DISCONNECTED) {\n title = \"Tor: Disconnected\";\n }\n\n NotificationCompat.Builder notification = new NotificationCompat.Builder(this, TOR_CHANNEL_ID)\n .setContentTitle(title)\n .setContentText(content)\n .setOngoing(true)\n .setGroupAlertBehavior(GROUP_ALERT_SUMMARY)\n .setGroup(\"Tor\")\n .setCategory(NotificationCompat.CATEGORY_PROGRESS)\n .setGroupSummary(false)\n .setSmallIcon(R.drawable.ic_tor_notification);\n\n switch (TorManager.getInstance(getApplicationContext()).state) {\n case CONNECTED: {\n notification.setColorized(true);\n notification.addAction(getStopAction(\"Stop\"));\n notification.addAction(getRestartAction());\n notification.setColor(ContextCompat.getColor(this, R.color.success_green));\n break;\n }\n case CONNECTING: {\n break;\n }\n case DISCONNECTED: {\n notification.addAction(getStopAction(\"Stop\"));\n notification.setColor(ContextCompat.getColor(this, R.color.red));\n break;\n }\n }\n NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);\n if (mNotificationManager != null) {\n mNotificationManager.notify(TOR_SERVICE_NOTIFICATION_ID, notification.build());\n }\n\n }\n\n private void restartTorProcess() {\n if (TorManager.getInstance(getApplicationContext()).isProcessRunning) {\n Disposable disposable = TorManager.getInstance(this)\n .stopTor()\n .subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribe(stat -> {\n compositeDisposable.dispose();\n TorManager.getInstance(this).setTorState(TorManager.CONNECTION_STATES.DISCONNECTED);\n updateNotification(\"Restarting...\");\n startTor();\n }, error -> {\n error.printStackTrace();\n compositeDisposable.dispose();\n updateNotification(\"Restarting...\");\n startTor();\n });\n compositeDisposable.add(disposable);\n } else {\n startTor();\n }\n }\n\n private void stopTor() {\n if (TorManager.getInstance(getApplicationContext()).isProcessRunning) {\n\n //\n Disposable disposable = TorManager.getInstance(this)\n .stopTor()\n .subscribe(state -> {\n\n\n }, Throwable::printStackTrace);\n compositeDisposable.add(disposable);\n }\n }\n\n\n @Override\n public IBinder onBind(Intent intent) {\n return null;\n }\n\n\n}", "public class AppUtil {\n\n private ProgressDialog progress = null;\n\n public static final int MIN_BACKUP_PW_LENGTH = 6;\n public static final int MAX_BACKUP_PW_LENGTH = 255;\n\n private boolean isInForeground = false;\n\t\n\tprivate static AppUtil instance = null;\n\tprivate static Context context = null;\n\n private static String strReceiveQRFilename = null;\n\t\n\tprivate AppUtil() { ; }\n\n\tpublic static AppUtil getInstance(Context ctx) {\n\t\t\n\t\tcontext = ctx;\n\t\t\n\t\tif(instance == null) {\n strReceiveQRFilename = context.getExternalCacheDir() + File.separator + \"qr.png\";\n\t\t\tinstance = new AppUtil();\n\t\t}\n\t\t\n\t\treturn instance;\n\t}\n\n public void restartApp() {\n Intent intent = new Intent(context, MainActivity2.class);\n intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);\n context.startActivity(intent);\n }\n\n public void restartApp(boolean verified) {\n Intent intent = new Intent(context, MainActivity2.class);\n intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);\n intent.putExtra(\"verified\", verified);\n context.startActivity(intent);\n }\n\n public void setIsInForeground(boolean foreground) {\n isInForeground = foreground;\n }\n\n public boolean isServiceRunning(Class<?> serviceClass) {\n\n ActivityManager manager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);\n for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {\n if (serviceClass.getName().equals(service.service.getClassName())) {\n Log.d(\"AppUtil\", \"service class name:\" + serviceClass.getName() + \" is running\");\n return true;\n }\n }\n\n Log.d(\"AppUtil\", \"service class name:\" + serviceClass.getName() + \" is not running\");\n return false;\n }\n\n public String getReceiveQRFilename(){\n return strReceiveQRFilename;\n }\n\n public void deleteQR(){\n String strFileName = strReceiveQRFilename;\n File file = new File(strFileName);\n if(file.exists()) {\n file.delete();\n }\n }\n\n public void doBackup() {\n\n final EditText password = new EditText(context);\n password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);\n password.setHint(R.string.password);\n\n new AlertDialog.Builder(context)\n .setTitle(R.string.app_name)\n .setMessage(R.string.options_export2)\n .setView(password)\n .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n\n final String pw = password.getText().toString();\n if (pw != null && pw.length() >= AppUtil.MIN_BACKUP_PW_LENGTH && pw.length() <= AppUtil.MAX_BACKUP_PW_LENGTH) {\n\n final EditText password2 = new EditText(context);\n password2.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);\n password2.setHint(R.string.confirm_password);\n\n new AlertDialog.Builder(context)\n .setTitle(R.string.app_name)\n .setMessage(R.string.options_export2)\n .setView(password2)\n .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n\n final String pw2 = password2.getText().toString();\n\n if (pw2 != null && pw2.equals(pw)) {\n\n final String[] export_methods = new String[2];\n export_methods[0] = context.getString(R.string.export_to_clipboard);\n export_methods[1] = context.getString(R.string.export_to_email);\n\n new AlertDialog.Builder(context)\n .setTitle(R.string.options_export)\n .setSingleChoiceItems(export_methods, 0, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int which) {\n\n String encrypted = null;\n try {\n encrypted = AESUtil.encrypt(SamouraiSentinel.getInstance(context).toJSON().toString(), new CharSequenceX(pw), AESUtil.DefaultPBKDF2Iterations);\n } catch (Exception e) {\n Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();\n } finally {\n if (encrypted == null) {\n Toast.makeText(context, R.string.encryption_error, Toast.LENGTH_SHORT).show();\n return;\n }\n else {\n\n try {\n JSONObject jsonObj = new JSONObject();\n jsonObj.put(\"version\", 1);\n jsonObj.put(\"payload\", encrypted);\n encrypted = jsonObj.toString();\n }\n catch(JSONException je) {\n ;\n }\n\n }\n\n }\n\n if (which == 0) {\n android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context.getSystemService(android.content.Context.CLIPBOARD_SERVICE);\n android.content.ClipData clip = null;\n clip = android.content.ClipData.newPlainText(\"Wallet backup\", encrypted);\n clipboard.setPrimaryClip(clip);\n Toast.makeText(context, R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show();\n } else {\n Intent email = new Intent(Intent.ACTION_SEND);\n email.putExtra(Intent.EXTRA_SUBJECT, \"Sentinel backup\");\n email.putExtra(Intent.EXTRA_TEXT, encrypted);\n email.setType(\"message/rfc822\");\n context.startActivity(Intent.createChooser(email, context.getText(R.string.choose_email_client)));\n }\n\n dialog.dismiss();\n }\n }\n ).show();\n\n } else {\n Toast.makeText(context, R.string.error_password, Toast.LENGTH_SHORT).show();\n }\n\n }\n })\n .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n ;\n }\n }).show();\n\n } else {\n Toast.makeText(context, R.string.invalid_password, Toast.LENGTH_SHORT).show();\n }\n\n }\n })\n .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n ;\n }\n }).show();\n\n }\n\n public void doRestore() {\n\n final EditText password = new EditText(context);\n password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);\n password.setHint(R.string.password);\n\n AlertDialog.Builder dlg = new AlertDialog.Builder(context)\n .setTitle(R.string.app_name)\n .setView(password)\n .setMessage(R.string.restore_wallet_from_backup)\n .setCancelable(false)\n .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n\n final String pw = password.getText().toString();\n if (pw == null || pw.length() < 1) {\n Toast.makeText(context, R.string.invalid_password, Toast.LENGTH_SHORT).show();\n AppUtil.getInstance(context).restartApp();\n }\n\n final EditText edBackup = new EditText(context);\n edBackup.setSingleLine(false);\n edBackup.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE);\n edBackup.setLines(5);\n edBackup.setHint(R.string.encrypted_backup);\n edBackup.setGravity(Gravity.START);\n\n AlertDialog.Builder dlg = new AlertDialog.Builder(context)\n .setTitle(R.string.app_name)\n .setView(edBackup)\n .setMessage(R.string.restore_wallet_from_backup)\n .setCancelable(false)\n .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n\n String encrypted = edBackup.getText().toString();\n if (encrypted == null || encrypted.length() < 1) {\n Toast.makeText(context, R.string.decryption_error, Toast.LENGTH_SHORT).show();\n AppUtil.getInstance(context).restartApp();\n }\n\n try {\n JSONObject jsonObject = new JSONObject(encrypted);\n if(jsonObject != null && jsonObject.has(\"payload\")) {\n encrypted = jsonObject.getString(\"payload\");\n }\n }\n catch(JSONException je) {\n ;\n }\n\n String decrypted = null;\n try {\n decrypted = AESUtil.decrypt(encrypted, new CharSequenceX(pw), AESUtil.DefaultPBKDF2Iterations);\n } catch (Exception e) {\n Toast.makeText(context, R.string.decryption_error, Toast.LENGTH_SHORT).show();\n } finally {\n if (decrypted == null || decrypted.length() < 1) {\n Toast.makeText(context, R.string.decryption_error, Toast.LENGTH_SHORT).show();\n AppUtil.getInstance(context).restartApp();\n }\n }\n\n final String decryptedPayload = decrypted;\n if (progress != null && progress.isShowing()) {\n progress.dismiss();\n progress = null;\n }\n\n progress = new ProgressDialog(context);\n progress.setCancelable(false);\n progress.setTitle(R.string.app_name);\n progress.setMessage(context.getString(R.string.please_wait));\n progress.show();\n\n new Thread(new Runnable() {\n @Override\n public void run() {\n Looper.prepare();\n\n try {\n\n JSONObject json = new JSONObject(decryptedPayload);\n if(json != null && (json.has(\"xpubs\") || json.has(\"legacy\"))) {\n SamouraiSentinel.getInstance(context).parseJSON(json);\n\n try {\n SamouraiSentinel.getInstance(context).serialize(SamouraiSentinel.getInstance(context).toJSON(), null);\n } catch (IOException ioe) {\n ;\n } catch (JSONException je) {\n ;\n }\n\n AppUtil.getInstance(context).restartApp();\n }\n\n }\n catch(JSONException je) {\n je.printStackTrace();\n Toast.makeText(context, R.string.decryption_error, Toast.LENGTH_SHORT).show();\n }\n finally {\n if (progress != null && progress.isShowing()) {\n progress.dismiss();\n progress = null;\n }\n AppUtil.getInstance(context).restartApp();\n }\n\n Looper.loop();\n\n }\n }).start();\n\n }\n }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n\n AppUtil.getInstance(context).restartApp();\n\n }\n });\n\n dlg.show();\n\n }\n }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n\n AppUtil.getInstance(context).restartApp();\n\n }\n });\n\n dlg.show();\n\n }\n\n public void checkTimeOut() {\n if(TimeOutUtil.getInstance().isTimedOut()) {\n AppUtil.getInstance(context).restartApp();\n }\n else {\n TimeOutUtil.getInstance().updatePin();\n }\n }\n\n public boolean isSideLoaded() {\n List<String> validInstallers = new ArrayList<>(Arrays.asList(\"com.android.vending\", \"com.google.android.feedback\"));\n final String installer = context.getPackageManager().getInstallerPackageName(context.getPackageName());\n return installer == null || !validInstallers.contains(installer);\n }\n\n}", "public class ConnectivityStatus {\n\t\n\tConnectivityStatus() { ; }\n\t\n\tpublic static boolean hasConnectivity(Context ctx) {\n\t\tboolean ret = false;\n\t\t\n \t\tConnectivityManager cm = (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);\n if(cm != null) {\n \t\tNetworkInfo neti = cm.getActiveNetworkInfo();\n\t\t\tif(neti != null && neti.isConnectedOrConnecting()) {\n\t\t\t\tret = true;\n\t\t\t}\n \t}\n\n return ret;\n\t}\n\n\tpublic static boolean hasWiFi(Context ctx) {\n\t\tboolean ret = false;\n\t\t\n \t\tConnectivityManager cm = (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);\n if(cm != null) {\n \t if(cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected()) {\n \t ret = true;\n \t }\n \t}\n\n return ret;\n\t}\n\n}", "public class PrefsUtil {\n\n public static final String CURRENT_FIAT = \"currentFiat\";\n public static final String CURRENT_FIAT_SEL = \"currentFiatSel\";\n\tpublic static final String CURRENT_EXCHANGE = \"currentExchange\";\n\tpublic static final String CURRENT_EXCHANGE_SEL = \"currentExchangeSel\";\n public static final String BLOCK_EXPLORER = \"blockExplorer\";\n public static final String FIRST_RUN = \"1stRun\";\n public static final String SIM_IMSI = \"IMSI\";\n public static final String ENABLE_TOR = \"ENABLE_TOR\";\n public static final String PIN_HASH = \"pinHash\";\n public static final String XPUB = \"xpub\";\n public static final String SCRAMBLE_PIN = \"scramblePin\";\n\tpublic static final String HAPTIC_PIN = \"hapticPin\";\n\tpublic static final String TESTNET = \"testnet\";\n\n\tprivate static Context context = null;\n\tprivate static PrefsUtil instance = null;\n\n\tprivate PrefsUtil() { ; }\n\n\tpublic static PrefsUtil getInstance(Context ctx) {\n\n\t\tcontext = ctx;\n\t\t\n\t\tif(instance == null) {\n\t\t\tinstance = new PrefsUtil();\n\t\t}\n\t\t\n\t\treturn instance;\n\t}\n\t\n\tpublic String getValue(String name, String value) {\n\t SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n\t return prefs.getString(name, (value == null || value.length() < 1) ? \"\" : value);\n\t}\n\n\tpublic boolean setValue(String name, String value) {\n\t\tEditor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();\n\t\teditor.putString(name, (value == null || value.length() < 1) ? \"\" : value);\n\t\treturn editor.commit();\n\t}\n\n\tpublic int getValue(String name, int value) {\n\t SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n\t return prefs.getInt(name, 0);\n\t}\n\n\tpublic boolean setValue(String name, int value) {\n\t\tEditor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();\n\t\teditor.putInt(name, (value < 0) ? 0 : value);\n\t\treturn editor.commit();\n\t}\n\n\tpublic boolean getValue(String name, boolean value) {\n\t SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n\t return prefs.getBoolean(name, value);\n\t}\n\n\tpublic boolean setValue(String name, boolean value) {\n\t\tEditor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();\n\t\teditor.putBoolean(name, value);\n\t\treturn editor.commit();\n\t}\n\n\tpublic boolean removeValue(String name) {\n\t\tEditor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();\n\t\teditor.remove(name);\n\t\treturn editor.commit();\n\t}\n\n\tpublic boolean clear() {\n\t\tEditor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();\n\t\teditor.clear();\n\t\treturn editor.commit();\n\t}\n\n}" ]
import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.samourai.sentinel.service.WebSocketService; import com.samourai.sentinel.tor.TorManager; import com.samourai.sentinel.tor.TorService; import com.samourai.sentinel.util.AppUtil; import com.samourai.sentinel.util.ConnectivityStatus; import com.samourai.sentinel.util.PrefsUtil; import java.util.Objects; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers;
package com.samourai.sentinel; public class Network extends Activity { TextView torRenewBtn; TextView torConnectionStatus; Button torButton; ImageView torConnectionIcon; int activeColor, disabledColor, waiting; CompositeDisposable disposables = new CompositeDisposable(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_network); Objects.requireNonNull(getActionBar()).setDisplayHomeAsUpEnabled(true); activeColor = ContextCompat.getColor(this, R.color.green_ui_2); disabledColor = ContextCompat.getColor(this, R.color.disabledRed); waiting = ContextCompat.getColor(this, R.color.warning_yellow); torButton = findViewById(R.id.networking_tor_btn); torRenewBtn = findViewById(R.id.networking_tor_renew); torConnectionIcon = findViewById(R.id.network_tor_status_icon); torConnectionStatus = findViewById(R.id.network_tor_status); torRenewBtn.setOnClickListener(view -> { if (TorManager.getInstance(getApplicationContext()).isConnected()) { startService(new Intent(this, TorService.class).setAction(TorService.RENEW_IDENTITY)); } }); listenToTorStatus(); // torButton.setOnClickListener(view -> { if (TorManager.getInstance(getApplicationContext()).isRequired()) { // if(DojoUtil.getInstance(NetworkDashboard.this).getDojoParams() !=null ){ // Toast.makeText(this,R.string.cannot_disable_tor_dojo,Toast.LENGTH_LONG).show(); // return; // } stopTor();
PrefsUtil.getInstance(getApplicationContext()).setValue(PrefsUtil.ENABLE_TOR, false);
5
ReplayMod/jGui
src/main/java/de/johni0702/minecraft/gui/popup/GuiInfoPopup.java
[ "public interface GuiContainer<T extends GuiContainer<T>> extends ComposedGuiElement<T> {\n\n T setLayout(Layout layout);\n Layout getLayout();\n\n void convertFor(GuiElement element, Point point);\n\n /**\n * Converts the global coordinates of the point to ones relative to the element.\n * @param element The element, must be part of this container\n * @param point The point\n * @param relativeLayer Layer at which the point is relative to this element,\n * positive values are above this element\n */\n void convertFor(GuiElement element, Point point, int relativeLayer);\n\n Map<GuiElement, LayoutData> getElements();\n T addElements(LayoutData layoutData, GuiElement... elements);\n T removeElement(GuiElement element);\n T sortElements();\n T sortElements(Comparator<GuiElement> comparator);\n\n ReadableColor getBackgroundColor();\n T setBackgroundColor(ReadableColor backgroundColor);\n}", "public class GuiPanel extends AbstractGuiContainer<GuiPanel> {\n\n public GuiPanel() {\n }\n\n public GuiPanel(GuiContainer container) {\n super(container);\n }\n\n GuiPanel(Layout layout, int width , int height, Map<GuiElement, LayoutData> withElements) {\n setLayout(layout);\n if (width != 0 || height != 0) {\n setSize(width, height);\n }\n for (Map.Entry<GuiElement, LayoutData> e : withElements.entrySet()) {\n addElements(e.getValue(), e.getKey());\n }\n }\n\n public static GuiPanelBuilder builder() {\n return new GuiPanelBuilder();\n }\n\n @Override\n protected GuiPanel getThis() {\n return this;\n }\n\n public static class GuiPanelBuilder {\n private Layout layout;\n private int width;\n private int height;\n private ArrayList<GuiElement> withElements$key;\n private ArrayList<LayoutData> withElements$value;\n\n GuiPanelBuilder() {\n }\n\n public GuiPanelBuilder layout(Layout layout) {\n this.layout = layout;\n return this;\n }\n\n public GuiPanelBuilder width(int width) {\n this.width = width;\n return this;\n }\n\n public GuiPanelBuilder height(int height) {\n this.height = height;\n return this;\n }\n\n public GuiPanelBuilder with(GuiElement withKey, LayoutData withValue) {\n if (this.withElements$key == null) {\n this.withElements$key = new ArrayList<GuiElement>();\n this.withElements$value = new ArrayList<LayoutData>();\n }\n this.withElements$key.add(withKey);\n this.withElements$value.add(withValue);\n return this;\n }\n\n public GuiPanelBuilder withElements(Map<? extends GuiElement, ? extends LayoutData> withElements) {\n if (this.withElements$key == null) {\n this.withElements$key = new ArrayList<GuiElement>();\n this.withElements$value = new ArrayList<LayoutData>();\n }\n for (final Map.Entry<? extends GuiElement, ? extends LayoutData> $lombokEntry : withElements.entrySet()) {\n this.withElements$key.add($lombokEntry.getKey());\n this.withElements$value.add($lombokEntry.getValue());\n }\n return this;\n }\n\n public GuiPanelBuilder clearWithElements() {\n if (this.withElements$key != null) {\n this.withElements$key.clear();\n this.withElements$value.clear();\n }\n return this;\n }\n\n public GuiPanel build() {\n Map<GuiElement, LayoutData> withElements;\n switch (this.withElements$key == null ? 0 : this.withElements$key.size()) {\n case 0:\n withElements = java.util.Collections.emptyMap();\n break;\n case 1:\n withElements = java.util.Collections.singletonMap(this.withElements$key.get(0), this.withElements$value.get(0));\n break;\n default:\n withElements = new java.util.LinkedHashMap<GuiElement, LayoutData>(this.withElements$key.size() < 1073741824 ? 1 + this.withElements$key.size() + (this.withElements$key.size() - 3) / 3 : Integer.MAX_VALUE);\n for (int $i = 0; $i < this.withElements$key.size(); $i++)\n withElements.put(this.withElements$key.get($i), (LayoutData) this.withElements$value.get($i));\n withElements = java.util.Collections.unmodifiableMap(withElements);\n }\n\n return new GuiPanel(layout, width, height, withElements);\n }\n\n public String toString() {\n return \"GuiPanel.GuiPanelBuilder(layout=\" + this.layout + \", width=\" + this.width + \", height=\" + this.height + \", withElements$key=\" + this.withElements$key + \", withElements$value=\" + this.withElements$value + \")\";\n }\n }\n}", "public class GuiButton extends AbstractGuiButton<GuiButton> {\n public GuiButton() {\n }\n\n public GuiButton(GuiContainer container) {\n super(container);\n }\n\n @Override\n protected GuiButton getThis() {\n return this;\n }\n}", "public interface GuiElement<T extends GuiElement<T>> {\n\n MinecraftClient getMinecraft();\n\n GuiContainer getContainer();\n T setContainer(GuiContainer container);\n\n void layout(ReadableDimension size, RenderInfo renderInfo);\n void draw(GuiRenderer renderer, ReadableDimension size, RenderInfo renderInfo);\n\n ReadableDimension getMinSize();\n ReadableDimension getMaxSize();\n\n T setMaxSize(ReadableDimension maxSize);\n\n boolean isEnabled();\n T setEnabled(boolean enabled);\n T setEnabled();\n T setDisabled();\n\n GuiElement getTooltip(RenderInfo renderInfo);\n T setTooltip(GuiElement tooltip);\n\n /**\n * Returns the layer this element takes part in.\n * The standard layer is layer 0. Event handlers will be called for this layer.\n * @return The layer of this element\n */\n int getLayer();\n\n}", "public class GuiLabel extends AbstractGuiLabel<GuiLabel> {\n public GuiLabel() {\n }\n\n public GuiLabel(GuiContainer container) {\n super(container);\n }\n\n @Override\n protected GuiLabel getThis() {\n return this;\n }\n}", "public interface Typeable {\n boolean typeKey(ReadablePoint mousePosition, int keyCode, char keyChar, boolean ctrlDown, boolean shiftDown);\n}", "public class VerticalLayout implements Layout {\n private static final Data DEFAULT_DATA = new Data(0);\n\n private final Alignment alignment;\n\n private int spacing;\n\n public VerticalLayout() {\n this(Alignment.TOP);\n }\n\n public VerticalLayout(Alignment alignment) {\n this.alignment = alignment;\n }\n\n @Override\n public Map<GuiElement, Pair<ReadablePoint, ReadableDimension>> layOut(GuiContainer<?> container, ReadableDimension size) {\n int y = 0;\n int spacing = 0;\n Map<GuiElement, Pair<ReadablePoint, ReadableDimension>> map = new LinkedHashMap<>();\n for (Map.Entry<GuiElement, LayoutData> entry : container.getElements().entrySet()) {\n y += spacing;\n spacing = this.spacing;\n\n GuiElement element = entry.getKey();\n Data data = entry.getValue() instanceof Data ? (Data) entry.getValue() : DEFAULT_DATA;\n Dimension elementSize = new Dimension(element.getMinSize());\n ReadableDimension elementMaxSize = element.getMaxSize();\n elementSize.setHeight(Math.min(size.getHeight() - y, Math.min(elementSize.getHeight(), elementMaxSize.getHeight())));\n elementSize.setWidth(Math.min(size.getWidth(), (data.maximizeWidth ? elementMaxSize : elementSize).getWidth()));\n int remainingWidth = size.getWidth() - elementSize.getWidth();\n int x = (int) (data.alignment * remainingWidth);\n map.put(element, Pair.<ReadablePoint, ReadableDimension>of(new Point(x, y), elementSize));\n y += elementSize.getHeight();\n }\n if (alignment != Alignment.TOP) {\n int remaining = size.getHeight() - y;\n if (alignment == Alignment.CENTER) {\n remaining /= 2;\n }\n for (Pair<ReadablePoint, ReadableDimension> pair : map.values()) {\n ((Point) pair.getLeft()).translate(0, remaining);\n }\n }\n return map;\n }\n\n @Override\n public ReadableDimension calcMinSize(GuiContainer<?> container) {\n int maxWidth = 0;\n int height = 0;\n int spacing = 0;\n for (Map.Entry<GuiElement, LayoutData> entry : container.getElements().entrySet()) {\n height += spacing;\n spacing = this.spacing;\n\n GuiElement element = entry.getKey();\n ReadableDimension minSize = element.getMinSize();\n int width = minSize.getWidth();\n if (width > maxWidth) {\n maxWidth = width;\n }\n height += minSize.getHeight();\n }\n return new Dimension(maxWidth, height);\n }\n\n public int getSpacing() {\n return this.spacing;\n }\n\n public VerticalLayout setSpacing(int spacing) {\n this.spacing = spacing;\n return this;\n }\n\n public static class Data implements LayoutData {\n private double alignment;\n private boolean maximizeWidth;\n\n public Data() {\n this(0);\n }\n\n public Data(double alignment) {\n this(alignment, true);\n }\n\n public Data(double alignment, boolean maximizeWidth) {\n this.alignment = alignment;\n this.maximizeWidth = maximizeWidth;\n }\n\n public double getAlignment() {\n return this.alignment;\n }\n\n public boolean isMaximizeWidth() {\n return this.maximizeWidth;\n }\n\n public void setAlignment(double alignment) {\n this.alignment = alignment;\n }\n\n public void setMaximizeWidth(boolean maximizeWidth) {\n this.maximizeWidth = maximizeWidth;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n Data data = (Data) o;\n return Double.compare(data.alignment, alignment) == 0 &&\n maximizeWidth == data.maximizeWidth;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(alignment, maximizeWidth);\n }\n\n @Override\n public String toString() {\n return \"Data{\" +\n \"alignment=\" + alignment +\n \", maximizeWidth=\" + maximizeWidth +\n '}';\n }\n }\n\n public enum Alignment {\n TOP, BOTTOM, CENTER\n }\n}", "public interface Colors extends ReadableColor {\n ReadableColor TRANSPARENT = new Color(0, 0, 0, 0);\n ReadableColor LIGHT_TRANSPARENT = new Color(0, 0, 0, 64);\n ReadableColor HALF_TRANSPARENT = new Color(0, 0, 0, 128);\n ReadableColor DARK_TRANSPARENT = new Color(0, 0, 0, 192);\n ReadableColor LIGHT_GRAY = new Color(192, 192, 192);\n ReadableColor DARK_RED = new Color(170, 0, 0);\n}", "public static abstract class Keyboard {\n public static final int KEY_ESCAPE = GLFW.GLFW_KEY_ESCAPE;\n public static final int KEY_HOME = GLFW.GLFW_KEY_HOME;\n public static final int KEY_END = GLFW.GLFW_KEY_END;\n public static final int KEY_UP = GLFW.GLFW_KEY_UP;\n public static final int KEY_DOWN = GLFW.GLFW_KEY_DOWN;\n public static final int KEY_LEFT = GLFW.GLFW_KEY_LEFT;\n public static final int KEY_RIGHT = GLFW.GLFW_KEY_RIGHT;\n public static final int KEY_BACK = GLFW.GLFW_KEY_BACKSPACE;\n public static final int KEY_DELETE = GLFW.GLFW_KEY_DELETE;\n public static final int KEY_RETURN = GLFW.GLFW_KEY_ENTER;\n public static final int KEY_TAB = GLFW.GLFW_KEY_TAB;\n public static final int KEY_A = GLFW.GLFW_KEY_A;\n public static final int KEY_C = GLFW.GLFW_KEY_C;\n public static final int KEY_V = GLFW.GLFW_KEY_V;\n public static final int KEY_X = GLFW.GLFW_KEY_X;\n\n public static void enableRepeatEvents(boolean enabled) {\n getMinecraft().keyboard.setRepeatEvents(enabled);\n }\n}" ]
import de.johni0702.minecraft.gui.layout.VerticalLayout; import de.johni0702.minecraft.gui.utils.Colors; import de.johni0702.minecraft.gui.utils.lwjgl.Dimension; import de.johni0702.minecraft.gui.utils.lwjgl.ReadablePoint; import de.johni0702.minecraft.gui.versions.MCVer.Keyboard; import de.johni0702.minecraft.gui.container.GuiContainer; import de.johni0702.minecraft.gui.container.GuiPanel; import de.johni0702.minecraft.gui.element.GuiButton; import de.johni0702.minecraft.gui.element.GuiElement; import de.johni0702.minecraft.gui.element.GuiLabel; import de.johni0702.minecraft.gui.function.Typeable;
/* * This file is part of jGui API, licensed under the MIT License (MIT). * * Copyright (c) 2016 johni0702 <https://github.com/johni0702> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package de.johni0702.minecraft.gui.popup; //#if MC>=11400 //#else //$$ import org.lwjgl.input.Keyboard; //#endif public class GuiInfoPopup extends AbstractGuiPopup<GuiInfoPopup> implements Typeable { public static GuiInfoPopup open(GuiContainer container, String...info) { GuiElement[] labels = new GuiElement[info.length]; for (int i = 0; i < info.length; i++) { labels[i] = new GuiLabel().setI18nText(info[i]).setColor(Colors.BLACK); } return open(container, labels); } public static GuiInfoPopup open(GuiContainer container, GuiElement... info) { GuiInfoPopup popup = new GuiInfoPopup(container).setBackgroundColor(Colors.DARK_TRANSPARENT); popup.getInfo().addElements(new VerticalLayout.Data(0.5), info); popup.open(); return popup; } private Runnable onClosed = () -> {}; private final GuiButton closeButton = new GuiButton().setSize(150, 20).onClick(() -> { close(); onClosed.run(); }).setI18nLabel("gui.back"); private final GuiPanel info = new GuiPanel().setMinSize(new Dimension(320, 50)) .setLayout(new VerticalLayout(VerticalLayout.Alignment.TOP).setSpacing(2)); { popup.setLayout(new VerticalLayout().setSpacing(10)) .addElements(new VerticalLayout.Data(0.5), info, closeButton); } private int layer; public GuiInfoPopup(GuiContainer container) { super(container); } public GuiInfoPopup setCloseLabel(String label) { closeButton.setLabel(label); return this; } public GuiInfoPopup setCloseI18nLabel(String label, Object...args) { closeButton.setI18nLabel(label, args); return this; } public GuiInfoPopup onClosed(Runnable onClosed) { this.onClosed = onClosed; return this; } @Override protected GuiInfoPopup getThis() { return this; } @Override public boolean typeKey(ReadablePoint mousePosition, int keyCode, char keyChar, boolean ctrlDown, boolean shiftDown) {
if (keyCode == Keyboard.KEY_ESCAPE) {
8
reines/game
game-server/src/main/java/com/game/server/handlers/packet/WalkHandler.java
[ "public class Packet {\n\tprivate static final Logger log = LoggerFactory.getLogger(Packet.class);\n\n\tpublic static final int HEADER_SIZE = 4 + 4; // type + size\n\n\tprotected static final CharsetDecoder stringDecoder;\n\n\tstatic {\n\t\tstringDecoder = Charset.forName(\"UTF-8\").newDecoder();\n\t}\n\n\t// X_SEND are packets from the client -> server\n\t// X_RESPONSE are from the server -> client\n\tpublic enum Type {\n\t\tLOGIN_SEND,\t\t\t\tLOGIN_RESPONSE,\n\t\tPING_SEND,\n\t\tCHAT_SEND,\t\t\t\tCHAT_RESPONSE,\n\t\t\t\t\t\t\t\tMESSAGE_RESPONSE,\n\t\tUSE_ITEM_SEND,\n\t\t\t\t\t\t\t\tFRIEND_LOGIN_RESPONSE,\n\t\tFRIEND_ADD_SEND,\t\tFRIEND_ADD_RESPONSE,\n\t\tFRIEND_MESSAGE_SEND,\tFRIEND_MESSAGE_RESPONSE,\n\t\tFRIEND_REMOVE_SEND,\t\tFRIEND_REMOVE_RESPONSE,\n\t\t\t\t\t\t\t\tPLAYERS_ADD_RESPONSE,\n\t\t\t\t\t\t\t\tPLAYERS_REMOVE_RESPONSE,\n\t\t\t\t\t\t\t\tPLAYERS_UPDATE_RESPONSE,\n\t\t\t\t\t\t\t\tINVENTORY_ADD_RESPONSE,\n\t\t\t\t\t\t\t\tINVENTORY_REMOVE_RESPONSE,\n\t\t\t\t\t\t\t\tINVENTORY_UPDATE_RESPONSE,\n\t\tWALK_TO_SEND,\n\t\tSTAT_UPDATE_SEND,\n\t}\n\n\tprotected final Type type;\n\tprotected IoBuffer payload;\n\tprotected final IoSession session;\n\n\tpublic Packet(Type type, IoBuffer payload, IoSession session) {\n\t\tthis.type = type;\n\t\tthis.payload = payload;\n\t\tthis.session = session;\n\t}\n\n\tpublic IoSession getSession() {\n\t\treturn session;\n\t}\n\n\tpublic Type getType() {\n\t\treturn type;\n\t}\n\n\tprotected byte[] getBytes() {\n\t\tbyte[] bytes = new byte[this.size()];\n\n\t\tpayload.rewind();\n\t\tpayload.get(bytes, 0, bytes.length);\n\n\t\treturn bytes;\n\t}\n\n\tprotected void setBytes(byte[] bytes) {\n\t\tpayload = IoBuffer.wrap(bytes).asReadOnlyBuffer();\n\t}\n\n\tpublic void decrypt(PrivateKey key) {\n\t\ttry {\n\t\t\tCipher cipher = Cipher.getInstance(\"RSA\");\n\t\t\tcipher.init(Cipher.DECRYPT_MODE, key);\n\n\t\t\tbyte[] encrypted = this.getBytes();\n\t\t\tbyte[] decrypted = cipher.doFinal(encrypted);\n\n\t\t\tthis.setBytes(decrypted);\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\tlog.error(\"Error decrpyting packet: \" + e.getMessage());\n\t\t}\n\t}\n\n\tpublic <E extends Enum<E>> E getEnum(Class<E> enumClass) {\n\t\treturn payload.getEnum(enumClass);\n\t}\n\n\tpublic String getString() {\n\t\ttry {\n\t\t\treturn payload.getString(stringDecoder);\n\t\t}\n\t\tcatch (CharacterCodingException e) {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic Hash getHash() {\n\t\tbyte[] data = new byte[Hash.LENGTH];\n\t\tpayload.get(data, 0, Hash.LENGTH);\n\n\t\treturn Hash.fromBytes(data);\n\t}\n\n\tpublic Point getPoint() {\n\t\tint x = this.getShort();\n\t\tint y = this.getShort();\n\n\t\treturn new Point(x, y);\n\t}\n\n\tpublic Stat getStat() {\n\t\tStat.Type type = this.getEnum(Stat.Type.class);\n\t\tlong exp = this.getLong();\n\t\tint current = this.getShort();\n\n\t\treturn new Stat(type, exp, current);\n\t}\n\n\tpublic Item getItem() {\n\t\tint id = this.getShort();\n\t\tlong amount = this.getLong();\n\t\tboolean equiped = this.getBoolean();\n\n\t\treturn new Item(id, amount, equiped);\n\t}\n\n\tpublic Friend getFriend() {\n\t\tHash id = this.getHash();\n\t\tString username = this.getString();\n\t\tboolean online = this.getBoolean();\n\n\t\treturn new Friend(id, username, online);\n\t}\n\n\tpublic Date getDate() {\n\t\tlong time = this.getLong();\n\n\t\treturn new Date(time);\n\t}\n\n\tpublic Path getPath() {\n\t\tPath path = new Path();\n\n\t\tint stepCount = this.getShort();\n\t\tfor (int i = 0;i < stepCount;i++)\n\t\t\tpath.append(this.getPoint());\n\n\t\treturn path;\n\t}\n\n\tpublic boolean getBoolean() {\n\t\treturn payload.get() == 1;\n\t}\n\n\tpublic byte getByte() {\n\t\treturn payload.get();\n\t}\n\n\tpublic short getShort() {\n\t\treturn payload.getShort();\n\t}\n\n\tpublic int getInt() {\n\t\treturn payload.getInt();\n\t}\n\n\tpublic long getLong() {\n\t\treturn payload.getLong();\n\t}\n\n\tpublic void rewind() {\n\t\tpayload.rewind();\n\t}\n\n\tpublic int size() {\n\t\treturn payload.limit();\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"packet[\" + type + \"].length = \" + this.size();\n\t}\n}", "public class Path implements Iterable<Point> {\n\n\tprotected final Deque<Point> steps;\n\n\tpublic Path() {\n\t\tsteps = new LinkedList<Point>();\n\t}\n\n\tpublic Path(Deque<Point> steps) {\n\t\tthis.steps = steps;\n\t}\n\n\tpublic void prepend(Point step) {\n\t\tsteps.addFirst(step);\n\t}\n\n\tpublic void append(Point step) {\n\t\tsteps.addLast(step);\n\t}\n\n\tpublic boolean hasNext() {\n\t\treturn !steps.isEmpty();\n\t}\n\n\tpublic Point getNext() {\n\t\treturn steps.peekFirst();\n\t}\n\n\tpublic Point removeNext() {\n\t\treturn steps.pollFirst();\n\t}\n\n\tpublic Point getLast() {\n\t\treturn steps.peekLast();\n\t}\n\n\tpublic int length() {\n\t\treturn steps.size();\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"path[length = \" + steps.size() + \", next = \" + this.getNext() + \", target = \" + this.getLast() + \"]\";\n\t}\n\n\t@Override\n\tpublic Iterator<Point> iterator() {\n\t\treturn steps.iterator();\n\t}\n}", "public class Server implements IoHandler, Runnable {\n\tprivate static final Logger log = LoggerFactory.getLogger(Server.class);\n\n\tpublic static final int DEFAULT_PORT = 36954;\n\tpublic static final int LOOP_DELAY = 100;\n\n\tprotected static final Options options;\n\n\tstatic {\n\t\toptions = new Options();\n\n\t\toptions.addOption(\"h\", \"help\", false, \"print this help.\");\n\t\toptions.addOption(\"p\", \"port\", true, \"port number to listen on, default \" + DEFAULT_PORT + \".\");\n\t\toptions.addOption(\"b\", \"bind\", true, \"IP address to bind to, default all.\");\n\t}\n\n\tpublic static void main(String[] args) {\n\t\ttry {\n\t\t\tCommandLineParser parser = new PosixParser();\n\t\t\tCommandLine config = parser.parse(options, args);\n\n\t\t\tif (config.hasOption(\"h\")) {\n\t\t\t\tHelpFormatter help = new HelpFormatter();\n\t\t\t\thelp.printHelp(\"java \" + Server.class.getSimpleName(), options);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tServer server = new Server(config);\n\t\t\tserver.start();\n\t\t}\n\t\tcatch (ParseException e) {\n\t\t\tlog.error(\"Error parsing command line options: \" + e);\n\t\t}\n\t\tcatch (RuntimeException e) {\n\t\t\tlog.error(e.getMessage());\n\t\t}\n\t}\n\n\tprotected final CommandLine config;\n\tprotected final NioSocketAcceptor acceptor;\n\tprotected final Map<Packet.Type, PacketHandler> packetHandlers;\n\tprotected final Database db;\n\tprotected final WorldManager world;\n\tprotected final PrivateKey privateKey;\n\tprotected final Queue<Packet> packets;\n\tprotected boolean running;\n\tprotected long lastPacketUpdate;\n\n\tprivate Server(CommandLine config) {\n\t\tthis.config = config;\n\n\t\tpacketHandlers = this.loadPacketHandlers();\n\n\t\t// Connection to the MySQL database\n\t\tFile dbConfig = new File(\"database.conf.xml\");\n\t\tif (!dbConfig.exists()) {\n\t\t\t// fatal error\n\t\t\tthrow new RuntimeException(\"Unable to load database config file: \" + dbConfig.getAbsolutePath());\n\t\t}\n\n\t\tprivateKey = (PrivateKey) PersistenceManager.load(Server.class.getResource(\"privatekey.xml\"));\n\n\t\t// Pre-load the item definitions\n\t\tItem.load();\n\n\t\tdb = new Database(dbConfig, this);\n\n\t\tacceptor = new NioSocketAcceptor();\n\t\tacceptor.setReuseAddress(true);\n\n\t\tacceptor.getFilterChain().addLast(\"codec\", new ProtocolCodecFilter(new PacketCodecFactory()));\n\n\t\t// Set the idle timeout to 5 seconds - once a client has logged in this gets increased\n\t\tacceptor.getSessionConfig().setIdleTime(IdleStatus.READER_IDLE, 5);\n\t\tacceptor.setHandler(this);\n\n\t\tworld = new WorldManager(this);\n\n\t\tpackets = new LinkedList<Packet>();\n\n\t\trunning = false;\n\t\tlastPacketUpdate = 0;\n\t}\n\n\tprivate Map<Packet.Type, PacketHandler> loadPacketHandlers() {\n\t\tMap<Packet.Type, PacketHandler> handlers = new HashMap<Packet.Type, PacketHandler>();\n\t\tURL path = PacketHandler.class.getResource(\"packethandlers.xml\");\n\t\tif (path == null) {\n\t\t\t// fatal error\n\t\t\tthrow new RuntimeException(\"Unable to find packethandlers.xml resource\");\n\t\t}\n\n\t\tPersistenceManager.PacketHandler[] definitions = (PersistenceManager.PacketHandler[]) PersistenceManager.load(path);\n\t\tfor (PersistenceManager.PacketHandler definition : definitions) {\n\t\t\ttry {\n\t\t\t\tPacketHandler handler = (PacketHandler) definition.handler.newInstance();\n\t\t\t\tfor (Packet.Type type : definition.types)\n\t\t\t\t\thandlers.put(type, handler);\n\t\t\t}\n\t\t\tcatch (Exception e) {\n\t\t\t\t// fatal error\n\t\t\t\tthrow new RuntimeException(\"Error loading packet handlers: \" + e.getMessage());\n\t\t\t}\n\t\t}\n\n\t\tif (log.isDebugEnabled())\n\t\t\tlog.debug(\"Loaded \" + handlers.size() + \" packet handlers\");\n\n\t\treturn handlers;\n\t}\n\n\tpublic Database getDatabase() {\n\t\treturn db;\n\t}\n\n\tpublic WorldManager getWorldManager() {\n\t\treturn world;\n\t}\n\n\t@Override\n\tpublic void run() {\n\t\twhile (running) {\n\t\t\tlong start = System.currentTimeMillis();\n\t\t\tthis.update(start);\n\n\t\t\tint duration = (int) (System.currentTimeMillis() - start);\n\t\t\tif (duration < LOOP_DELAY) {\n\t\t\t\ttry { Thread.sleep(LOOP_DELAY - duration); } catch (InterruptedException e) { }\n\t\t\t}\n\t\t}\n\n\t\t// TODO: Shut down the server\n\t}\n\n\tprivate void update(long now) {\n\t\t// Process the queued packets\n\t\tsynchronized (packets) {\n\t\t\tfor (Packet message : packets)\n\t\t\t\tthis.processPacket(message);\n\n\t\t\tpackets.clear();\n\t\t}\n\n\t\t// Update the world\n\t\tworld.update(now);\n\t}\n\n\tprivate boolean processPacket(Packet message) {\n\t\tIoSession session = message.getSession();\n\t\t// Confirm the client is still connected and valid\n\t\tif (!session.isConnected() || (!session.containsAttribute(\"client\") && !session.containsAttribute(\"pending\")))\n\t\t\treturn false;\n\n\t\tPlayer client = (Player) session.getAttribute(\"client\");\n\n\t\tPacketHandler handler = packetHandlers.get(message.getType());\n\t\t// If there's no handler then close the session (forcefully)\n\t\tif (handler == null) {\n\t\t\tlog.warn(\"Unhandled packet from: \" + client);\n\t\t\tsession.close(true);\n\t\t\treturn false;\n\t\t}\n\n\t\ttry {\n\t\t\thandler.handlePacket(this, world, client, message);\n\t\t\treturn true;\n\t\t}\n\t\t// Something went wrong (malformed packet?), close the session (forcefully)\n\t\tcatch (Exception e) {\n\t\t\tlog.warn(\"Error decoding packet from: \" + client);\n\t\t\te.printStackTrace();\n\t\t\tsession.close(true);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tprivate void start() {\n\t\tif (running)\n\t\t\treturn;\n\n\t\tint port = DEFAULT_PORT;\n\t\tif (config.hasOption(\"p\")) {\n\t\t\ttry {\n\t\t\t\tport = Integer.parseInt(config.getOptionValue(\"p\"));\n\t\t\t}\n\t\t\tcatch (NumberFormatException e) {\n\t\t\t\t// fatal error\n\t\t\t\tthrow new RuntimeException(\"Invalid port number: \" + config.getOptionValue(\"p\"));\n\t\t\t}\n\t\t}\n\n\t\tInetSocketAddress listen = null;\n\t\tif (config.hasOption(\"b\"))\n\t\t\tlisten = new InetSocketAddress(config.getOptionValue(\"b\"), port);\n\t\telse\n\t\t\tlisten = new InetSocketAddress(port);\n\n\t\trunning = true;\n\t\tnew Thread(this).start();\n\n\t\ttry {\n\t\t\tacceptor.bind(listen);\n\t\t\tSystem.out.println(\"Server listening on: \" + listen.getHostName() + \":\" + listen.getPort());\n\t\t}\n\t\tcatch (IOException e) {\n\t\t\t// fatal error\n\t\t\tthrow new RuntimeException(\"Unable to bind to: \" + listen.getHostName() + \":\" + listen.getPort());\n\t\t}\n\t}\n\n\tpublic void stop() {\n\t\trunning = false;\n\t}\n\n\t@Override\n\tpublic void exceptionCaught(IoSession session, Throwable cause) throws Exception {\n\t\tlog.warn(\"Error from \" + (session.containsAttribute(\"client\") ? session.getAttribute(\"client\") : \"new\") + \" connection: \" + cause.getMessage());\n\n\t\t// Close the session (forcefully)\n\t\tsession.close(true);\n\t}\n\n\t@Override\n\tpublic void messageReceived(IoSession session, Object o) throws Exception {\n\t\tPacket message = (Packet) o;\n\t\t// We should only process 1 packet from a session at a time\n\t\tsynchronized (session) {\n\t\t\t// If there is a client, queue the packet for processing\n\t\t\tif (session.containsAttribute(\"client\") || session.containsAttribute(\"pending\")) {\n\t\t\t\tsynchronized (packets) {\n\t\t\t\t\tpackets.add(message);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// If there isn't a client attached then this must be the login request\n\t\t\telse if (message.getType() == Packet.Type.LOGIN_SEND) {\n\t\t\t\t// Decrypt the login request\n\t\t\t\tmessage.decrypt(privateKey);\n\n\t\t\t\t// Mark this session as pending login\n\t\t\t\tsession.setAttribute(\"pending\");\n\n\t\t\t\t// Queue the packet\n\t\t\t\tsynchronized (packets) {\n\t\t\t\t\tpackets.add(message);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Otherwise this packet shouldn't be here!\n\t\t\telse {\n\t\t\t\tlog.warn(\"Client isn't logged in, but sent a packet\");\n\t\t\t\tsession.close(true);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic void messageSent(IoSession session, Object o) throws Exception { }\n\n\t@Override\n\tpublic void sessionClosed(IoSession session) throws Exception {\n\t\tsynchronized (packets) {\n\t\t\t// If the session has a client attached, call the session closed method\n\t\t\tif (session.containsAttribute(\"client\")) {\n\t\t\t\tPlayer client = (Player) session.getAttribute(\"client\");\n\t\t\t\tworld.removePlayer(client);\n\t\t\t}\n\t\t\t// Otherwise they haven't logged in yet, so who cares just drop them\n\t\t}\n\t}\n\n\t@Override\n\tpublic void sessionCreated(IoSession session) throws Exception { }\n\n\t@Override\n\tpublic void sessionIdle(IoSession session, IdleStatus status) throws Exception {\n\t\t// When a session becomes idle, close it (gracefully)\n\t\tsession.close(false);\n\t}\n\n\t@Override\n\tpublic void sessionOpened(IoSession session) throws Exception { }\n}", "public class WorldManager {\n\tpublic static final int PLAYER_UPDATE_DELAY = 200;\n\n\tprotected final Server server;\n\tprotected final WorldMap map;\n\tprotected final EntityList<Player> players;\n\tprotected long lastPlayerUpdate;\n\n\tpublic WorldManager(Server server) {\n\t\tthis.server = server;\n\n\t\tmap = WorldMap.load();\n\t\tplayers = new EntityList<Player>();\n\n\t\tlastPlayerUpdate = 0;\n\t}\n\n\tpublic WorldMap getMap() {\n\t\treturn map;\n\t}\n\n\tpublic void update(long now) {\n\t\tif (now - lastPlayerUpdate > PLAYER_UPDATE_DELAY) {\n\t\t\tlastPlayerUpdate = now;\n\n\t\t\tsynchronized (players) {\n\t\t\t\t// Update all the players\n\t\t\t\tfor (Player player : players.allEntities())\n\t\t\t\t\tplayer.update(now, players);\n\n\t\t\t\tCollection<Player> newPlayers = players.newEntities();\n\t\t\t\tCollection<Player> removedPlayers = players.removedEntities();\n\n\t\t\t\t// Alert all the players of any logins/logouts\n\t\t\t\tfor (Player player : players.allEntities()) {\n\t\t\t\t\t// Alert this player if any of the new players are their friends\n\t\t\t\t\tfor (Player newPlayer : newPlayers) {\n\t\t\t\t\t\tif (player.getFriends().contains(newPlayer.getID()))\n\t\t\t\t\t\t\tplayer.sendFriendLogin(newPlayer.getID(), true);\n\t\t\t\t\t}\n\n\t\t\t\t\t// Alert this player is any of the removed players are their friends\n\t\t\t\t\tfor (Player removedPlayer : removedPlayers) {\n\t\t\t\t\t\tif (player.getFriends().contains(removedPlayer.getID()))\n\t\t\t\t\t\t\tplayer.sendFriendLogin(removedPlayer.getID(), false);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tplayers.reset();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic Collection<Player> getPlayers() {\n\t\treturn players.allEntities();\n\t}\n\n\tpublic Player getPlayer(Hash id) {\n\t\treturn players.get(id);\n\t}\n\n\tpublic void addPlayer(Player player) {\n\t\tsynchronized (players) {\n\t\t\tplayer.onSessionStarted();\n\t\t\tplayers.add(player);\n\t\t}\n\t}\n\n\tpublic void removePlayer(Player player) {\n\t\tsynchronized (players) {\n\t\t\tplayers.remove(player.getID());\n\t\t\tplayer.onSessionEnded();\n\t\t}\n\t}\n}", "public interface PacketHandler {\n\n\tpublic void handlePacket(Server server, WorldManager world, Player player, Packet packet) throws Exception;\n\n}", "public class Player extends Entity implements Observer {\n\tprivate static final Logger log = LoggerFactory.getLogger(Player.class);\n\n\tpublic static final int VIEW_DISTANCE = 64;\n\n\tprotected final Server server;\n\tprotected final WorldManager world;\n\tprotected final IoSession session;\n\tprotected final PlayerProfile profile;\n\tprotected final EntityList<Player> knownPlayers;\n\tprotected Path path;\n\n\tpublic Player(Server server, IoSession session, PlayerProfile profile) {\n\t\tthis.server = server;\n\t\tthis.session = session;\n\t\tthis.profile = profile;\n\n\t\tfor (Stat stat : profile.stats)\n\t\t\tstat.addObserver(this);\n\n\t\tpath = null;\n\t\tworld = server.getWorldManager();\n\t\tknownPlayers = new EntityList<Player>();\n\n\t\t// Once a client is logged in, we can relax the idle time to 60 seconds\n\t\tsession.getConfig().setIdleTime(IdleStatus.READER_IDLE, 60);\n\t}\n\n\tpublic void setPath(Path path) {\n\t\tthis.path = path;\n\t}\n\n\tpublic void update(long now, EntityList<Player> allPlayers) {\n\t\t// If we have a path set, move to the next step along\n\t\tif (path != null) {\n\t\t\tPoint step = path.removeNext();\n\t\t\tif (!path.hasNext())\n\t\t\t\tpath = null;\n\n\t\t\t// The next step is next to us and a valid step\n\t\t\tif (world.getMap().isValidStep(profile.location, step)) {\n\t\t\t\tthis.setLocation(step);\n\t\t\t}\n\t\t\t// The next step isn't next to us, we have an invalid path!\n\t\t\telse {\n\t\t\t\t// TODO: This can happen if the player is walking and they generate a new path, can we someone handle this nicely?\n\t\t\t\tlog.warn(\"Received invalid path from: \" + this);\n\t\t\t\tpath = null;\n\t\t\t}\n\t\t}\n\n\t\t// For each player we know about, check they are still within our view area and logged in\n\t\tfor (Iterator<Player> it = knownPlayers.iterator();it.hasNext();) {\n\t\t\tPlayer player = it.next();\n\t\t\tdouble distance = this.getLocation().distanceTo(player.getLocation());\n\t\t\tif (distance > VIEW_DISTANCE || !allPlayers.contains(player))\n\t\t\t\tit.remove();\n\t\t}\n\n\t\t// For each player in our view area, check they are in our known players list\n\t\tfor (Player player : allPlayers) {\n\t\t\tdouble distance = this.getLocation().distanceTo(player.getLocation());\n\t\t\tif (distance > VIEW_DISTANCE)\n\t\t\t\tcontinue;\n\n\t\t\tknownPlayers.add(player);\n\t\t}\n\n\t\t// Alert this player of new players\n\t\tif (knownPlayers.hasNewEntities())\n\t\t\tthis.sendAddPlayers(knownPlayers.newEntities());\n\n\t\t// Alert this player of removed players\n\t\tif (knownPlayers.hasRemovedEntities())\n\t\t\tthis.sendRemovePlayers(knownPlayers.removedEntities());\n\n\t\t// Alert this player of updated players\n\t\tif (knownPlayers.hasUpdatedEntities())\n\t\t\tthis.sendUpdatePlayers(knownPlayers.updatedEntities());\n\n\t\t// Reset the new and removed list ready for next time\n\t\tknownPlayers.reset();\n\t}\n\n\tpublic Collection<Player> getKnownPlayers() {\n\t\treturn knownPlayers.allEntities();\n\t}\n\n\tpublic StatList getStats() {\n\t\treturn profile.stats;\n\t}\n\n\tpublic FriendList getFriends() {\n\t\treturn profile.friends;\n\t}\n\n\tpublic Inventory getInventory() {\n\t\treturn profile.inventory;\n\t}\n\n\tpublic void onSessionStarted() {\n\t\tlog.info(\"Client connected: \" + this);\n\t\tWorldTile tile = world.getMap().getTile(profile.location);\n\t\tif (tile == null) {\n\t\t\tlog.error(\"Attempted to add client to non-existant tile: \" + this);\n\n\t\t\tsession.close(false);\n\t\t\treturn;\n\t\t}\n\n\t\ttile.add(this);\n\t}\n\n\t@Override\n\tpublic Point getLocation() {\n\t\treturn profile.location;\n\t}\n\n\t@Override\n\tpublic void setLocation(Point p) {\n\t\t// If we haven't moved then don't bother updating tiles\n\t\tif (profile.location.equals(p))\n\t\t\treturn;\n\n\t\t// Remove ourselves from the old tile\n\t\tworld.getMap().getTile(profile.location).remove(this);\n\n\t\tWorldTile tile = world.getMap().getTile(p);\n\t\tif (tile == null) {\n\t\t\tlog.error(\"Attempted to add client to non-existant tile: \" + this);\n\n\t\t\tsession.close(false);\n\t\t\treturn;\n\t\t}\n\n\t\t// Update our location\n\t\tprofile.location.set(p);\n\n\t\t// Add ourselves to the new tile\n\t\ttile.add(this);\n\n\t\t// Mark us as changed\n\t\tsuper.setChanged();\n\t\tsuper.notifyObservers();\n\t}\n\n\tpublic String getUsername() {\n\t\treturn profile.username;\n\t}\n\n\t@Override\n\tpublic Hash getID() {\n\t\treturn profile.id;\n\t}\n\n\tpublic void write(PacketBuilder packet) {\n\t\tsession.write(packet);\n\t}\n\n\tpublic void onSessionEnded() {\n\t\t// Remove ourselves from the map\n\t\tworld.getMap().getTile(profile.location).remove(this);\n\n\t\t// Update our last session time and save our profile\n\t\tprofile.lastSession.setTime(System.currentTimeMillis());\n\t\tserver.getDatabase().save(profile);\n\n\t\tlog.info(\"Client disconnected: \" + this);\n\t}\n\n\tpublic void sendChat(Player from, String message) {\n\t\tPacketBuilder packet = new PacketBuilder(Packet.Type.CHAT_RESPONSE);\n\n\t\tpacket.putHash(from.getID());\n\t\tpacket.putString(message);\n\n\t\tthis.write(packet);\n\t}\n\n\tpublic void sendMessage(String message) {\n\t\tPacketBuilder packet = new PacketBuilder(Packet.Type.MESSAGE_RESPONSE);\n\n\t\tpacket.putString(message);\n\n\t\tthis.write(packet);\n\t}\n\n\tpublic void sendInventoryAdd(Item item) {\n\t\tPacketBuilder packet = new PacketBuilder(Packet.Type.INVENTORY_ADD_RESPONSE);\n\n\t\tpacket.putItem(item);\n\n\t\tthis.write(packet);\n\t}\n\n\tpublic void sendInventoryRemove(int index) {\n\t\tPacketBuilder packet = new PacketBuilder(Packet.Type.INVENTORY_REMOVE_RESPONSE);\n\n\t\tpacket.putByte((byte) index);\n\n\t\tthis.write(packet);\n\t}\n\n\tpublic void sendInventoryUpdate(int index, Item item) {\n\t\tPacketBuilder packet = new PacketBuilder(Packet.Type.INVENTORY_UPDATE_RESPONSE);\n\n\t\tpacket.putByte((byte) index);\n\t\tpacket.putLong(item.getAmount());\n\t\tpacket.putBoolean(item.isEquiped());\n\n\t\tthis.write(packet);\n\t}\n\n\tpublic void sendAddFriend(Friend friend) {\n\t\tPacketBuilder packet = new PacketBuilder(Packet.Type.FRIEND_ADD_RESPONSE);\n\n\t\tpacket.putFriend(friend);\n\n\t\tthis.write(packet);\n\t}\n\n\tpublic void sendRemoveFriend(Friend friend) {\n\t\tPacketBuilder packet = new PacketBuilder(Packet.Type.FRIEND_REMOVE_RESPONSE);\n\n\t\tpacket.putHash(friend.getID());\n\n\t\tthis.write(packet);\n\t}\n\n\tpublic void sendFriendMessage(String username, String message) {\n\t\tPacketBuilder packet = new PacketBuilder(Packet.Type.FRIEND_MESSAGE_RESPONSE);\n\n\t\tpacket.putString(username);\n\t\tpacket.putString(message);\n\n\t\tthis.write(packet);\n\t}\n\n\tpublic void sendFriendLogin(Hash id, boolean in) {\n\t\tPacketBuilder packet = new PacketBuilder(Packet.Type.FRIEND_LOGIN_RESPONSE);\n\n\t\tpacket.putHash(id);\n\t\tpacket.putBoolean(in);\n\n\t\tthis.write(packet);\n\t}\n\n\tpublic void sendAddPlayers(Collection<Player> players) {\n\t\t// Remove ourself, we already know where we are!\n\t\tint playerCount = players.size();\n\t\tif (players.contains(this))\n\t\t\tplayerCount--;\n\n\t\t// If there's no players then we have nothing to send\n\t\tif (playerCount == 0)\n\t\t\treturn;\n\n\t\tPacketBuilder packet = new PacketBuilder(Packet.Type.PLAYERS_ADD_RESPONSE);\n\n\t\tpacket.putShort((short) playerCount);\n\t\tfor (Player player : players) {\n\t\t\tif (player.equals(this))\n\t\t\t\tcontinue;\n\n\t\t\tpacket.putHash(player.getID());\n\t\t\tpacket.putString(player.getUsername());\n\t\t\tpacket.putPoint(player.getLocation());\n\t\t}\n\n\t\tthis.write(packet);\n\t}\n\n\tpublic void sendRemovePlayers(Collection<Player> players) {\n\t\t// Remove ourself, we already know where we are!\n\t\tint playerCount = players.size();\n\t\tif (players.contains(this))\n\t\t\tplayerCount--;\n\n\t\t// If there's no players then we have nothing to send\n\t\tif (playerCount == 0)\n\t\t\treturn;\n\n\t\tPacketBuilder packet = new PacketBuilder(Packet.Type.PLAYERS_REMOVE_RESPONSE);\n\n\t\tpacket.putShort((short) playerCount);\n\t\tfor (Player player : players) {\n\t\t\tif (player.equals(this))\n\t\t\t\tcontinue;\n\n\t\t\tpacket.putHash(player.getID());\n\t\t}\n\n\t\tthis.write(packet);\n\t}\n\n\tpublic void sendUpdatePlayers(Collection<Player> players) {\n\t\tint playerCount = players.size();\n\t\t// If there's no players then we have nothing to send\n\t\tif (playerCount == 0)\n\t\t\treturn;\n\n\t\tPacketBuilder packet = new PacketBuilder(Packet.Type.PLAYERS_UPDATE_RESPONSE);\n\n\t\tpacket.putShort((short) playerCount);\n\t\tfor (Player player : players) {\n\t\t\tpacket.putHash(player.getID());\n\t\t\tpacket.putPoint(player.getLocation());\n\t\t}\n\n\t\tthis.write(packet);\n\t}\n\n\tpublic void sendUpdateStat(Stat stat) {\n\t\tPacketBuilder packet = new PacketBuilder(Packet.Type.STAT_UPDATE_SEND);\n\n\t\tpacket.putStat(stat);\n\n\t\tthis.write(packet);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn profile.hashCode();\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (!(o instanceof Player))\n\t\t\treturn false;\n\n\t\tPlayer c = (Player) o;\n\t\treturn this.getID().equals(c.getID());\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"player[id = \" + this.getID() + \", username = '\" + profile.username + \"']\";\n\t}\n\n\t@Override\n\tpublic void update(Observable o, Object arg) {\n\t\t// A stat was updated, send the update to the client\n\t\tif (o instanceof Stat) {\n\t\t\tStat stat = (Stat) o;\n\t\t\tboolean levelNotification = (Boolean) arg;\n\t\t\tif (levelNotification)\n\t\t\t\tthis.sendMessage(\"You increased a \" + stat.getType().name + \" level!\");\n\t\t\telse\n\t\t\t\tthis.sendUpdateStat(stat);\n\t\t}\n\t}\n}" ]
import com.game.common.codec.Packet; import com.game.common.model.Path; import com.game.server.Server; import com.game.server.WorldManager; import com.game.server.handlers.PacketHandler; import com.game.server.model.Player;
package com.game.server.handlers.packet; public class WalkHandler implements PacketHandler { @Override
public void handlePacket(Server server, WorldManager world, Player player, Packet packet) throws Exception {
0
IPEldorado/RemoteResources
src/com/eldorado/remoteresources/ui/model/PersistentDeviceModel.java
[ "public class CaptureManager implements ClientChangedListener {\n\n\tprivate static CaptureManager instance;\n\n\tprivate final ScreenPanel canvas;\n\n\tprivate Client client;\n\n\tprivate String deviceSerialNumber;\n\n\tprivate Device userDevice;\n\n\tprivate boolean isRunning;\n\n\tprivate EventsListener mouseListener;\n\n\tprivate final Set<CaptureStateListener> listeners;\n\n\tprivate CaptureManager() {\n\t\tcanvas = new ScreenPanel();\n\t\tlisteners = new HashSet<CaptureStateListener>();\n\t\tClientConnectionManager.getInstance().addClientChangedListener(this);\n\t}\n\n\tpublic static CaptureManager getInstance() {\n\t\tif (instance == null) {\n\t\t\tinstance = new CaptureManager();\n\t\t}\n\n\t\treturn instance;\n\t}\n\n\t/**\n\t * Adds a new capture listener to this manager. Does nothing if already\n\t * added.\n\t * \n\t * @param listener\n\t * the listener\n\t */\n\n\tpublic void addCaptureStateListener(CaptureStateListener listener) {\n\t\tlisteners.add(listener);\n\t}\n\n\t/**\n\t * Remove the listener from this manager listeners\n\t * \n\t * @param listener\n\t * the listener to be removed\n\t */\n\tpublic void removeCaptureStateListener(CaptureStateListener listener) {\n\t\tlisteners.remove(listener);\n\t}\n\n\tpublic ScreenPanel getCanvas() {\n\t\treturn canvas;\n\t}\n\n\t/**\n\t * \n\t * @param device\n\t */\n\tpublic void startCapture(Client client, Device userDevice) {\n\t\tcanvas.createBufferStrategy(2);\n\n\t\tfinal Image image = ResourcesLoader.getAnimatedGif(\"loader\");\n\t\ttry {\n\t\t\tcanvas.drawScreen(image, true);\n\t\t} catch (IllegalStateException e) {\n\t\t\t// this exception happens very rarely and freezes the application,\n\t\t\t// so ignore it, because it doesn't affect the screen capture\n\t\t\te.printStackTrace();\n\t\t}\n\t\tif (!isRunning && (userDevice != null)) {\n\t\t\tisRunning = true;\n\t\t\tdeviceSerialNumber = userDevice.getSerialNumber();\n\t\t\tthis.client = client;\n\t\t\tthis.userDevice = userDevice;\n\t\t\tmouseListener = new EventsListener(client, deviceSerialNumber);\n\t\t\tcanvas.addMouseListener(mouseListener);\n\t\t\tcanvas.addMouseMotionListener(mouseListener);\n\t\t\tthis.client.addDataReceivedListener(deviceSerialNumber,\n\t\t\t\t\tnew DataReceivedListener() {\n\t\t\t\t\t\tprivate BufferedImage prevImage = null;\n\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic void newFrameReceived(String serialNumber,\n\t\t\t\t\t\t\t\tbyte[] frameContent) {\n\t\t\t\t\t\t\tif (isRunning) {\n\t\t\t\t\t\t\t\tBufferedImage currentImage;\n\t\t\t\t\t\t\t\tif (prevImage == null) {\n\t\t\t\t\t\t\t\t\tcanvas.stopAnimation();\n\t\t\t\t\t\t\t\t\tcanvas.setLocation(0, 0);\n\t\t\t\t\t\t\t\t\tcanvas.setSize(new Dimension(canvas\n\t\t\t\t\t\t\t\t\t\t\t.getParent().getWidth() - 20,\n\t\t\t\t\t\t\t\t\t\t\tcanvas.getParent().getHeight() - 20));\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tif (frameContent == null) {\n\t\t\t\t\t\t\t\t\t\tcurrentImage = prevImage;\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tcurrentImage = ImageIO.read(ImageUtils\n\t\t\t\t\t\t\t\t\t\t\t\t.decompress(new ByteArrayInputStream(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tframeContent)));\n\t\t\t\t\t\t\t\t\t\tprevImage = currentImage;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcanvas.drawScreen(currentImage);\n\t\t\t\t\t\t\t\t} catch (IOException e) {\n\t\t\t\t\t\t\t\t\tClientLogger\n\t\t\t\t\t\t\t\t\t\t\t.error(CaptureManager.class,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"Failed to decompress received frame. Using previous one if available\",\n\t\t\t\t\t\t\t\t\t\t\t\t\te);\n\t\t\t\t\t\t\t\t\tcurrentImage = prevImage;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\tClientConnectionManager.getInstance().startDataConnection(client,\n\t\t\t\t\tdeviceSerialNumber);\n\t\t\twhile (!client.isDataConnectionActive(deviceSerialNumber)) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(100);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t// do nothing\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (userDevice.getProperty(Device.POLLING_RATE) != null) {\n\t\t\t\tclient.setPollingRate(deviceSerialNumber,\n\t\t\t\t\t\tuserDevice.getProperty(Device.POLLING_RATE));\n\t\t\t}\n\t\t\tif (userDevice.getProperty(Device.IMAGE_QUALITY) != null) {\n\t\t\t\tclient.setImageQuality(deviceSerialNumber,\n\t\t\t\t\t\tuserDevice.getProperty(Device.IMAGE_QUALITY));\n\t\t\t}\n\t\t\tfor (CaptureStateListener listener : listeners) {\n\t\t\t\tlistener.captureStarted(client, deviceSerialNumber);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void stopCapture() {\n\t\tif (mouseListener != null) {\n\t\t\tcanvas.removeMouseListener(mouseListener);\n\t\t\tcanvas.removeMouseMotionListener(mouseListener);\n\t\t}\n\t\tif (isRunning) {\n\t\t\tClient c = client;\n\t\t\tString device = deviceSerialNumber;\n\t\t\tisRunning = false;\n\t\t\tdeviceSerialNumber = null;\n\t\t\tclient = null;\n\t\t\tuserDevice = null;\n\t\t\tcanvas.drawScreen(null);\n\t\t\tClientConnectionManager.getInstance().stopDataConnection(c, device);\n\t\t\tfor (CaptureStateListener listener : listeners) {\n\t\t\t\tlistener.captureFinished(c, device);\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\t/**\n\t * \n\t * @return\n\t */\n\tpublic boolean isRunning() {\n\t\treturn isRunning;\n\t}\n\n\t@Override\n\tpublic void clientConnected(Client client) {\n\t\t// do nothing\n\n\t}\n\n\t@Override\n\tpublic void clientDisconnected(Client client) {\n\t\t// do nothing\n\n\t}\n\n\t@Override\n\tpublic void deviceConnected(Client client, String device) {\n\t\t// do nothing\n\n\t}\n\n\t@Override\n\tpublic void deviceDisconnected(Client client, String device) {\n\t\tif (isRunning && device.equals(deviceSerialNumber)) {\n\t\t\tDevice dev = userDevice;\n\t\t\tstopCapture();\n\t\t\tJOptionPane\n\t\t\t\t\t.showConfirmDialog(\n\t\t\t\t\t\t\tnull,\n\t\t\t\t\t\t\t\"Lost connection with device \"\n\t\t\t\t\t\t\t\t\t+ dev.getName()\n\t\t\t\t\t\t\t\t\t+ \" (\"\n\t\t\t\t\t\t\t\t\t+ dev.getHost()\n\t\t\t\t\t\t\t\t\t+ \"). Make sure that both device and host are connected and try again.\",\n\t\t\t\t\t\t\t\"Device disconnected\", JOptionPane.DEFAULT_OPTION,\n\t\t\t\t\t\t\tJOptionPane.ERROR_MESSAGE);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void deviceAdded(Client client, String device) {\n\t\t// do nothing\n\n\t}\n\n\t@Override\n\tpublic void deviceRemoved(Client client, AndroidDeviceClient device) {\n\t\t// do nothing\n\n\t}\n\n}", "public class RemoteResourcesLocalization {\n\n\tpublic enum RemoteResourcesLocalization_Languages {\n\t\ten_US, pt_BR\n\t};\n\n\tprivate static ResourceBundle bundle = ResourceBundle.getBundle(\n\t\t\t\"com.eldorado.remoteresources.i18n.RemoteResourcesMessages\",\n\t\t\tLocale.getDefault());\n\n\t/**\n\t * Get a message with a following id\n\t * \n\t * @param message\n\t * the message id\n\t * @return the message\n\t */\n\tpublic static String getMessage(String message) {\n\t\treturn bundle.getString(message);\n\t}\n\n\t/**\n\t * Get a message with the parameters in place\n\t * \n\t * @param message\n\t * the message id\n\t * @param parameters\n\t * the parameters\n\t * @return the compound message\n\t */\n\tpublic static String getMessage(String message, Object... parameters) {\n\t\treturn MessageFormat.format(bundle.getString(message), parameters);\n\t}\n\n\tpublic static void setLanguage(\n\t\t\tRemoteResourcesLocalization_Languages language) {\n\t\tswitch (language) {\n\t\tcase en_US:\n\t\t\tbundle = ResourceBundle\n\t\t\t\t\t.getBundle(\n\t\t\t\t\t\t\t\"com.eldorado.remoteresources.i18n.RemoteResourcesMessages\",\n\t\t\t\t\t\t\tLocale.getDefault());\n\t\t\tbreak;\n\t\tcase pt_BR:\n\t\t\tbundle = ResourceBundle\n\t\t\t\t\t.getBundle(\n\t\t\t\t\t\t\t\"com.eldorado.remoteresources.i18n.RemoteResourcesMessages\",\n\t\t\t\t\t\t\tnew Locale(\"pt\", \"BR\"));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbundle = ResourceBundle\n\t\t\t\t\t.getBundle(\n\t\t\t\t\t\t\t\"com.eldorado.remoteresources.i18n.RemoteResourcesMessages\",\n\t\t\t\t\t\t\tLocale.getDefault());\n\t\t}\n\t}\n}", "public class RemoteResourcesMessages {\n\n\t/**\n\t * Add new messages here in the following format: Class_Category_MessageName\n\t * Where Category can be Info, Error, Warning, Debug (for log information)\n\t * or UI (for ui labels and messages)\n\t */\n\n\t/*\n\t * RemoteResources\n\t */\n\tpublic static final String RemoteResources_OneInstance = \"RemoteResources_OneInstance\";\n\n\t/*\n\t * AddDeviceAction\n\t */\n\tpublic static final String AddDeviceAction_Tooltip_AddDevice = \"AddDeviceAction_Tooltip_AddDevice\";\n\n\tpublic static final String AddDeviceAction_LongTooltip_AddDevice = \"AddDeviceAction_LongTooltip_AddDevice\";\n\n\t/*\n\t * AddDevicePage\n\t */\n\tpublic static final String AddDevicePage_Error_DeviceAlreadyExists = \"AddDevicePage_Error_DeviceAlreadyExists\";\n\n\tpublic static final String AddDevicePage_Error_DeviceAlreadyCreated = \"AddDevicePage_Error_DeviceAlreadyCreated\";\n\n\tpublic static final String AddDevicePage_Error_NameIsEmpty = \"AddDevicePage_Error_NameIsEmpty\";\n\n\tpublic static final String AddDevicePage_Error_NoAvailableDevice = \"AddDevicePage_Error_NoAvailableDevice\";\n\n\tpublic static final String AddDevicePage_Error_NoSelectedDevice = \"AddDevicePage_Error_NoSelectedDevice\";\n\n\tpublic static final String AddDevicePage_UI_DeviceTableColumn_DeviceModel = \"AddDevicePage_UI_DeviceTableColumn_DeviceModel\";\n\n\tpublic static final String AddDevicePage_UI_DeviceTableColumn_DeviceSerialNumber = \"AddDevicePage_UI_DeviceTableColumn_DeviceSerialNumber\";\n\n\tpublic static final String AddDevicePage_UI_DeviceNameLabel = \"AddDevicePage_UI_DeviceNameLabel\";\n\n\tpublic static final String AddDevicePage_UI_DeviceNameTooltip = \"AddDevicePage_UI_DeviceNameTooltip\";\n\n\tpublic static final String AddDevicePage_UI_PageDescription = \"AddDevicePage_UI_PageDescription\";\n\n\t/*\n\t * AddHostPage\n\t */\n\n\tpublic static final String AddHostPage_Error_EmptyHostname = \"AddHostPage_Error_EmptyHostname\";\n\n\tpublic static final String AddHostPage_Error_ExistingHostNickname = \"AddHostPage_Error_ExistingHostNickname\";\n\n\tpublic static final String AddHostPage_Error_InvalidIPAddress = \"AddHostPage_Error_InvalidIPAddress\";\n\n\tpublic static final String AddHostPage_Error_InvalidPort = \"AddHostPage_Error_InvalidPort\";\n\n\tpublic static final String AddHostPage_Error_UnableToConnect = \"AddHostPage_Error_UnableToConnect\";\n\n\tpublic static final String AddHostPage_Error_UnknownHost = \"AddHostPage_Error_UnknownHost\";\n\n\tpublic static final String AddHostPage_UI_HostsComboLabel = \"AddHostPage_UI_HostsComboLabel\";\n\n\tpublic static final String AddHostPage_UI_NewHost_HostAddress = \"AddHostPage_UI_NewHost_HostAddress\";\n\n\tpublic static final String AddHostPage_UI_NewHost_HostNickname = \"AddHostPage_UI_NewHost_HostNickname\";\n\n\tpublic static final String AddHostPage_UI_NewHost_HostPort = \"AddHostPage_UI_NewHost_HostPort\";\n\n\tpublic static final String AddHostPage_UI_PageDescription = \"AddHostPage_UI_PageDescription\";\n\n\tpublic static final String AddHostPage_UI_Radio_ExistingHost_Label = \"AddHostPage_UI_Radio_ExistingHost_Label\";\n\n\tpublic static final String AddHostPage_UI_Radio_NewHost_Label = \"AddHostPage_UI_Radio_NewHost_Label\";\n\n\tpublic static final String AddHostPage_Warning_NoHostValidationPerformed = \"AddHostPage_Warning_NoHostValidationPerformed\";\n\n\t/*\n\t * ButtonBarPanel\n\t */\n\tpublic static final String ButtonBarPanel_TypeMessage = \"ButtonBarPanel_TypeMessage\";\n\tpublic static final String ButtonBarPanel_ActionsMenu = \"ButtonBarPanel_ActionsMenu\";\n\n\t/*\n\t * Client\n\t */\n\tpublic static final String Client_Error_IOError = \"Client_Error_IOError\";\n\n\tpublic static final String Client_Error_UnableToSendMessage = \"Client_Error_UnableToSendMessage\";\n\n\tpublic static final String Client_Error_UnknownObjectType = \"Client_Error_UnknownObjectType\";\n\n\tpublic static final String Client_Info_ConnectingToServer = \"Client_Info_ConnectingToServer\";\n\n\tpublic static final String Client_Info_DisconnectingFromServer = \"Client_Info_DisconnectingFromServer\";\n\n\t/*\n\t * ClientLogger\n\t */\n\tpublic static final String ClientLogger_Error_InsufficientPermissions = \"ClientLogger_Error_InsufficientPermissions\";\n\n\tpublic static final String ClientLogger_Error_UnableToConfigure = \"ClientLogger_Error_UnableToConfigure\";\n\n\t/*\n\t * ConnectDeviceAction\n\t */\n\tpublic static final String ConnectDeviceAction_Tooltip_StartCapture = \"ConnectDeviceAction_Tooltip_StartCapture\";\n\n\tpublic static final String ConnectDeviceAction_Tooltip_StopCapture = \"ConnectDeviceAction_Tooltip_StopCapture\";\n\n\tpublic static final String ConnectDeviceAction_CaptureErrorMessage = \"ConnectDeviceAction_CaptureErrorMessage\";\n\n\tpublic static final String ConnectDeviceAction_ChangeDevice = \"ConnectDeviceAction_ChangeDevice\";\n\n\tpublic static final String ConnectDeviceAction_RemoveDevice = \"ConnectDeviceAction_RemoveDevice\";\n\n\tpublic static final String ConnectDeviceAction_RemoveDeviceTitle = \"ConnectDeviceAction_RemoveDeviceTitle\";\n\n\tpublic static final String ConnectDeviceAction_RemoveDeviceYes = \"ConnectDeviceAction_RemoveDeviceYes\";\n\n\tpublic static final String ConnectDeviceAction_RemoveDeviceNo = \"ConnectDeviceAction_RemoveDeviceNo\";\n\n\t/*\n\t * ConnectHostAction\n\t */\n\tpublic static final String ConnectHostAction_Tooltip_StartHost = \"ConnectHostAction_Tooltip_StartHost\";\n\n\tpublic static final String ConnectHostAction_Tooltip_StopHost = \"ConnectHostAction_Tooltip_StopHost\";\n\n\t/*\n\t * DataClient\n\t */\n\tpublic static final String DataClient_Error_IOError = \"DataClient_Error_IOError\";\n\n\tpublic static final String DataClient_Error_UnknownObjectType = \"DataClient_Error_UnknownObjectType\";\n\n\tpublic static final String DataClient_Error_UnableToCloseProperly = \"DataClient_Error_UnableToCloseProperly\";\n\n\tpublic static final String DataClient_UI_ThreadName = \"DataClient_UI_ThreadName\";\n\n\t/*\n\t * DevicePanel\n\t */\n\tpublic static final String DevicePanel_Tooltip_Configuration = \"DevicePanel_Tooltip_Configuration\";\n\n\tpublic static final String DevicePanel_Tooltip_Remotion = \"DevicePanel_Tooltip_Remotion\";\n\n\tpublic static final String DevicePanel_Tooltip_StartCapture = \"DevicePanel_Tooltip_StartCapture\";\n\n\t/*\n\t * DeviceConfigurationDialog\n\t */\n\tpublic static final String DeviceConfigurationDialog_EditNicknameButton = \"DeviceConfigurationDialog_EditNicknameButton\";\n\n\tpublic static final String DeviceConfigurationDialog_ScriptLocation = \"DeviceConfigurationDialog_ScriptLocation\";\n\n\tpublic static final String DeviceConfigurationDialog_ActivateScriptGeneration = \"DeviceConfigurationDialog_ActivateScriptGeneration\";\n\n\tpublic static final String DeviceConfigurationDialog_PollingLabel = \"DeviceConfigurationDialog_PollingLabel\";\n\n\tpublic static final String DeviceConfigurationDialog_QualityLabel = \"DeviceConfigurationDialog_QualityLabel\";\n\n\tpublic static final String DeviceConfigurationDialog_DeviceHost = \"DeviceConfigurationDialog_DeviceHost\";\n\n\tpublic static final String DeviceConfigurationDialog_DeviceName = \"DeviceConfigurationDialog_DeviceName\";\n\n\tpublic static final String DeviceConfigurationDialog_DeviceSerialNumber = \"DeviceConfigurationDialog_DeviceSerialNumber\";\n\n\tpublic static final String DeviceConfigurationDialog_Title = \"DeviceConfigurationDialog_Title\";\n\n\tpublic static final String DeviceConfigurationDialog_EditNickNameError = \"DeviceConfigurationDialog_EditNickNameError\";\n\n\t/*\n\t * HostPanel\n\t */\n\tpublic static final String HostPanel_Tooltip_Remotion = \"HostPanel_Tooltip_Remotion\";\n\n\tpublic static final String HostPanel_Tooltip_Information = \"HostPanel_Tooltip_Information\";\n\n\tpublic static final String HostPanel_RemoveHost = \"HostPanel_RemoveHost\";\n\n\t/*\n\t * HostConfigurationDialog\n\t */\n\tpublic static final String HostConfigurationDialog_DeviceList = \"HostConfigurationDialog_DeviceList\";\n\n\tpublic static final String HostConfigurationDialog_NoDeviceMessage = \"HostConfigurationDialog_NoDeviceMessage\";\n\n\tpublic static final String HostConfigurationDialog_HostNickname = \"HostConfigurationDialog_HostNickname\";\n\n\tpublic static final String HostConfigurationDialog_HostAddress = \"HostConfigurationDialog_HostAddress\";\n\n\tpublic static final String HostConfigurationDialog_HostPort = \"HostConfigurationDialog_HostPort\";\n\n\tpublic static final String HostConfigurationDialog_Title = \"HostConfigurationDialog_Title\";\n\n\t/*\n\t * IConnnectionConstants\n\t */\n\n\tpublic static final String IConnnectionConstants_PollingRates1 = \"IConnnectionConstants_PollingRates1\";\n\n\tpublic static final String IConnnectionConstants_PollingRates2 = \"IConnnectionConstants_PollingRates2\";\n\n\tpublic static final String IConnnectionConstants_PollingRates3 = \"IConnnectionConstants_PollingRates3\";\n\n\tpublic static final String IConnnectionConstants_PollingRates4 = \"IConnnectionConstants_PollingRates4\";\n\n\tpublic static final String IConnnectionConstants_PollingRates5 = \"IConnnectionConstants_PollingRates5\";\n\n\tpublic static final String IConnnectionConstants_PollingRates6 = \"IConnnectionConstants_PollingRates6\";\n\n\tpublic static final String IConnnectionConstants_Qualities1 = \"IConnnectionConstants_Qualities1\";\n\n\tpublic static final String IConnnectionConstants_Qualities2 = \"IConnnectionConstants_Qualities2\";\n\n\tpublic static final String IConnnectionConstants_Qualities3 = \"IConnnectionConstants_Qualities3\";\n\n\tpublic static final String IConnnectionConstants_Qualities4 = \"IConnnectionConstants_Qualities4\";\n\n\tpublic static final String IConnnectionConstants_Qualities5 = \"IConnnectionConstants_Qualities5\";\n\n\tpublic static final String IConnnectionConstants_Qualities6 = \"IConnnectionConstants_Qualities6\";\n\n\t/*\n\t * LanguageOptionsDialog\n\t */\n\tpublic static final String LanguageOptionsDialog_Title = \"LanguageOptionsDialog_Title\";\n\tpublic static final String LanguageOptionsRestart = \"LanguageOptionsRestart\";\n\n\t/*\n\t * MenuBarOptionsDialog\n\t */\n\tpublic static final String MenuBarOptionsDialog_Tooltip_ImputText = \"MenuBarOptionsDialog_Tooltip_ImputText\";\n\n\tpublic static final String MenuBarOptionsDialog_Tooltip_GetScreenshot = \"MenuBarOptionsDialog_Tooltip_GetScreenshot\";\n\n\tpublic static final String MenuBarOptionsDialog_Tooltip_GetLog = \"MenuBarOptionsDialog_Tooltip_GetLog\";\n\n\tpublic static final String MenuBarOptionsDialog_Tooltip_PlayScript = \"MenuBarOptionsDialog_Tooltip_PlayScript\";\n\n\t/*\n\t * MenuBarPanel\n\t */\n\tpublic static final String MenuBarPanel_Tooltip_MainMenu = \"MenuBarPanel_Tooltip_MainMenu\";\n\n\t/*\n\t * RemoteResources\n\t */\n\tpublic static final String RemoteResources_Error_ConnectionError = \"RemoteResources_Error_ConnectionError\";\n\n\t/*\n\t * RemoteResourcesConfiguration\n\t */\n\tpublic static final String RemoteResourcesConfiguration_Error_UnableToLoad = \"RemoteResourcesConfiguration_Error_UnableToLoad\";\n\tpublic static final String RemoteResourcesConfiguration_Error_UnableToStore = \"RemoteResourcesConfiguration_Error_UnableToStore\";\n\tpublic static final String RemoteResourcesConfiguration_Error_StoreGenericError = \"RemoteResourcesConfiguration_Error_StoreGenericError\";\n\tpublic static final String RemoteResourcesConfiguration_Error_ConfigFileError = \"RemoteResourcesConfiguration_Error_ConfigFileError\";\n\n\t/*\n\t * RemoteResourcesPanel\n\t */\n\tpublic static final String RemoteResourcesPanel_UI_HeaderTitle = \"RemoteResourcesPanel_UI_HeaderTitle\";\n\n\tpublic static final String RemoteResourcesPanel_UI_ExitMessage = \"RemoteResourcesPanel_UI_ExitMessage\";\n\n\tpublic static final String RemoteResourcesPanel_UI_Tooltip_Switch2HostView = \"RemoteResourcesPanel_UI_Tooltip_Switch2HostView\";\n\n\tpublic static final String RemoteResourcesPanel_UI_Tooltip_Switch2DeviceView = \"RemoteResourcesPanel_UI_Tooltip_Switch2DeviceView\";\n\n\tpublic static final String RemoteResourcesPanel_UI_LocalTitle = \"RemoteResourcesPanel_UI_LocalTitle\";\n\n\tpublic static final String RemoteResourcesPanel_UI_RemoteTitle = \"RemoteResourcesPanel_UI_RemoteTitle\";\n\n\tpublic static final String RemoteResourcesPanel_UI_ExitMessageYes = \"RemoteResourcesPanel_UI_ExitMessageYes\";\n\n\tpublic static final String RemoteResourcesPanel_UI_ExitMessageNo = \"RemoteResourcesPanel_UI_ExitMessageNo\";\n\n\t/*\n\t * RemoteResourcesServer\n\t */\n\tpublic static final String RemoteResourcesServer_UI_ThreadName = \"RemoteResourcesServer_UI_ThreadName\";\n\n\tpublic static final String RemoteResourcesServer_Error_AdbNotFound = \"RemoteResourcesServer_Error_AdbNotFound\";\n\n\tpublic static final String RemoteResourcesServer_Error_InvalidPortNumber = \"RemoteResourcesServer_Error_InvalidPortNumber\";\n\n\tpublic static final String RemoteResourcesServer_Error_AdbNoPath = \"RemoteResourcesServer_Error_AdbNoPath\";\n\n\tpublic static final String RemoteResourcesServer_Error_NoPortNumber = \"RemoteResourcesServer_Error_NoPortNumber\";\n\n\tpublic static final String RemoteResourcesServer_Error_UnableToBind = \"RemoteResourcesServer_Error_UnableToBind\";\n\n\tpublic static final String RemoteResourcesServer_Error_WaitingForConnection = \"RemoteResourcesServer_Error_WaitingForConnection\";\n\n\tpublic static final String RemoteResourcesServer_Info_StartingServer = \"RemoteResourcesServer_Info_StartingServer\";\n\n\tpublic static final String RemoteResourcesServer_Info_StoppingServer = \"RemoteResourcesServer_Info_StoppingServer\";\n\n\tpublic static final String RemoteResourcesServer_Warning_NoConfigFile = \"RemoteResourcesServer_Warning_NoConfigFile\";\n\n\t/*\n\t * ScriptConfigurationDialog\n\t */\n\tpublic static final String ScriptConfigurationDialog_Title = \"ScriptConfigurationDialog_Title\";\n\n\tpublic static final String ScriptConfigurationDialog_FileLabel = \"ScriptConfigurationDialog_FileLabel\";\n\n\tpublic static final String ScriptConfigurationDialog_EnableEditionLabel = \"ScriptConfigurationDialog_EnableEditionLabel\";\n\n\tpublic static final String ScriptConfigurationDialog_PauseLabel = \"ScriptConfigurationDialog_PauseLabel\";\n\n\tpublic static final String ScriptConfigurationDialog_SleepLabel = \"ScriptConfigurationDialog_SleepLabel\";\n\n\tpublic static final String ScriptConfigurationDialog_SaveButton = \"ScriptConfigurationDialog_SaveButton\";\n\n\tpublic static final String ScriptConfigurationDialog_AddActionButton = \"ScriptConfigurationDialog_AddActionButton\";\n\n\tpublic static final String ScriptConfigurationDialog_InformationLabel = \"ScriptConfigurationDialog_InformationLabel\";\n\n\tpublic static final String ScriptConfigurationDialog_SaveFileMessage = \"ScriptConfigurationDialog_SaveFileMessage\";\n\n\tpublic static final String ScriptConfigurationDialog_ErrorTimeMessage = \"ScriptConfigurationDialog_ErrorTimeMessage\";\n\n\tpublic static final String ScriptConfigurationDialog_ErrorLabel = \"ScriptConfigurationDialog_ErrorLabel\";\n\n\tpublic static final String ScriptConfigurationDialog_ExecuteLabel = \"ScriptConfigurationDialog_ExecuteLabel\";\n\n\tpublic static final String ScriptConfigurationDialog_ExecuteActionButton = \"ScriptConfigurationDialog_ExecuteActionButton\";\n\n\tpublic static final String ScriptConfigurationDialog_ExecuteScriptButton = \"ScriptConfigurationDialog_ExecuteScriptButton\";\n\n\tpublic static final String ScriptConfigurationDialog_FinishedExecutionMessage = \"ScriptConfigurationDialog_FinishedExecutionMessage\";\n\n\t/*\n\t * LogCaptureDialog\n\t */\n\tpublic static final String LogCaptureDialog_Label = \"LogCaptureDialog_Label\";\n\n\tpublic static final String LogCaptureDialog_DirectoryLabel = \"LogCaptureDialog_DirectoryLabel\";\n\n\tpublic static final String LogCaptureDialog_LogLevel = \"LogCaptureDialog_LogLevel\";\n\n\t/*\n\t * Generic Messages\n\t */\n\n\tpublic static final String UI_Cancel = \"UI_Cancel\";\n\n\tpublic static final String UI_Finish = \"UI_Finish\";\n\n\tpublic static final String UI_Next = \"UI_Next\";\n\n\tpublic static final String UI_OK = \"UI_OK\";\n\n\tpublic static final String UI_Previous = \"UI_Previous\";\n\n}", "public class DevicesContainer extends BasePanel implements\n\t\tDeviceModelChangeListener {\n\n\tprivate static final long serialVersionUID = 3805929184064963051L;\n\n\tprivate GridBagLayout deviceListLayout;\n\n\tprivate BasePanel headerPanel;\n\n\tprivate final Map<String, DevicePanel> devicesMap = new HashMap<String, DevicePanel>();\n\n\tprivate final List<DevicePanel> panelList = new ArrayList<DevicePanel>();\n\n\tprivate final PersistentDeviceModel model;\n\n\tprivate String hostToIgnore;\n\n\tprivate String hostToShow;\n\n\t/**\n\t * Creates a new container\n\t * \n\t * @param model\n\t * the device model to listen to\n\t */\n\tpublic DevicesContainer(PersistentDeviceModel model, String headerText) {\n\t\tthis.model = model;\n\t\tmodel.addModelChangedListener(this);\n\t\tsetLayout(deviceListLayout = new GridBagLayout());\n\t\tcreateHeader(headerText);\n\t}\n\n\tprivate void createHeader(String header) {\n\t\theaderPanel = new BasePanel();\n\t\theaderPanel.setBackground(Color.LIGHT_GRAY);\n\t\tGridBagConstraints constraints = new GridBagConstraints();\n\t\tconstraints.weightx = 1;\n\t\tconstraints.weighty = 1;\n\t\tconstraints.anchor = GridBagConstraints.PAGE_START;\n\t\tconstraints.gridx = 0;\n\t\tconstraints.gridy = 0;\n\t\tdeviceListLayout.addLayoutComponent(headerPanel, constraints);\n\t\tadd(headerPanel);\n\n\t\tJLabel title = new JLabel();\n\t\ttitle.setText(header);\n\t\tFont currentFont = title.getFont();\n\t\ttitle.setFont(currentFont.deriveFont(Font.BOLD, 14));\n\t\theaderPanel.add(title);\n\n\t}\n\n\t/**\n\t * Adds a new device to this container. Not intended to be used outside this\n\t * package\n\t * \n\t * @param device\n\t */\n\tvoid addDevice(Device device) {\n\n\t\t// if device was in list of saved localhost devices, copy saved\n\t\t// preferences to this device\n\t\tfor (Device d : model.getDevices()) {\n\t\t\tif (device.getSerialNumber().equals(d.getSerialNumber())) {\n\t\t\t\tdevice.copyProperties(d);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t// if user previously preferred not to delete local device from list,\n\t\t// avoids creating two entries for same device\n\t\tfor (DevicePanel panel : panelList) {\n\t\t\tif (panel.getDevice().getSerialNumber()\n\t\t\t\t\t.equals(device.getSerialNumber())) {\n\t\t\t\tpanel.setCaptureButton(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tDevicePanel devicePanel = new DevicePanel(model, device);\n\t\tClientConnectionManager.getInstance().addClientChangedListener(\n\t\t\t\tdevicePanel);\n\t\tGridBagConstraints devicePanelConstraints = new GridBagConstraints();\n\t\tdevicePanelConstraints.gridx = 0;\n\t\tdevicePanelConstraints.anchor = GridBagConstraints.PAGE_START;\n\t\tdevicePanelConstraints.gridwidth = GridBagConstraints.REMAINDER;\n\t\tdevicePanelConstraints.weightx = 1;\n\t\tdevicePanelConstraints.fill = GridBagConstraints.HORIZONTAL;\n\t\tdevicePanelConstraints.insets = new Insets(1, 1, 1, 1);\n\n\t\tif (panelList.size() > 0) {\n\t\t\tGridBagConstraints lastConstraints = deviceListLayout\n\t\t\t\t\t.getConstraints(panelList.get(panelList.size() - 1));\n\t\t\tlastConstraints.weighty = 0;\n\t\t\tdeviceListLayout.setConstraints(\n\t\t\t\t\tpanelList.get(panelList.size() - 1), lastConstraints);\n\t\t}\n\t\tdevicePanelConstraints.weighty = 1;\n\n\t\tif (devicesMap.isEmpty()) {\n\t\t\tGridBagConstraints headerC = deviceListLayout\n\t\t\t\t\t.getConstraints(headerPanel);\n\t\t\theaderC.weighty = 0;\n\t\t\tdeviceListLayout.setConstraints(headerPanel, headerC);\n\t\t}\n\n\t\tdeviceListLayout\n\t\t\t\t.addLayoutComponent(devicePanel, devicePanelConstraints);\n\n\t\tadd(devicePanel);\n\t\tdevicesMap.put(device.getName(), devicePanel);\n\t\tpanelList.add(devicePanel);\n\t\trevalidate();\n\t\trepaint();\n\n\t}\n\n\t/**\n\t * Set hostname to ignore. Cleans host to show.\n\t * \n\t * @param hostToIgnore\n\t */\n\tpublic void setHostToIgnore(String hostToIgnore) {\n\t\tthis.hostToIgnore = hostToIgnore;\n\t\thostToShow = null;\n\t}\n\n\t/**\n\t * Set hostname to show. Cleans host to ignore.\n\t * \n\t * @param hostToShow\n\t * the host to show.\n\t */\n\tpublic void setHostToShow(String hostToShow) {\n\t\tthis.hostToShow = hostToShow;\n\t\thostToIgnore = null;\n\t}\n\n\t/**\n\t * Remove a device from this container\n\t * \n\t * @param device\n\t */\n\tvoid removeDevice(Device device) {\n\t\tDevicePanel dp = devicesMap.remove(device.getName());\n\t\tif (dp != null) {\n\t\t\tClientConnectionManager.getInstance().removeClientChangedListener(\n\t\t\t\t\tdp);\n\t\t\tif ((panelList.size() > 1)\n\t\t\t\t\t&& (panelList.indexOf(dp) == (panelList.size() - 1))) {\n\t\t\t\tGridBagConstraints newLastConstraints = deviceListLayout\n\t\t\t\t\t\t.getConstraints(panelList.get(panelList.size() - 2));\n\t\t\t\tnewLastConstraints.weighty = 1;\n\t\t\t\tdeviceListLayout\n\t\t\t\t\t\t.setConstraints(panelList.get(panelList.size() - 2),\n\t\t\t\t\t\t\t\tnewLastConstraints);\n\t\t\t} else if (panelList.size() == 1) {\n\t\t\t\tGridBagConstraints headerC = deviceListLayout\n\t\t\t\t\t\t.getConstraints(headerPanel);\n\t\t\t\theaderC.weighty = 1;\n\t\t\t\tdeviceListLayout.setConstraints(headerPanel, headerC);\n\t\t\t}\n\t\t\tpanelList.remove(dp);\n\t\t\tremove(dp);\n\t\t\trevalidate();\n\t\t\trepaint();\n\t\t}\n\t}\n\n\t@Override\n\tpublic void deviceAdded(Device device) {\n\t\tif (isNotFiltered(device.getHost())) {\n\t\t\taddDevice(device);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void deviceRemoved(Device device) {\n\t\tif (isNotFiltered(device.getHost())) {\n\t\t\tremoveDevice(device);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void hostAdded(Host host) {\n\t\tif (isNotFiltered(host.getHostname())) {\n\t\t\tfor (Device device : host.getDevices()) {\n\t\t\t\taddDevice(device);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic void hostRemoved(Host host) {\n\t\tif (isNotFiltered(host.getHostname())) {\n\t\t\tfor (Device device : host.getDevices()) {\n\t\t\t\tremoveDevice(device);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate boolean isNotFiltered(String host) {\n\t\treturn ((hostToIgnore == null) && (hostToShow == null))\n\t\t\t\t|| ((hostToIgnore != null) && !hostToIgnore.equals(host))\n\t\t\t\t|| ((hostToShow != null) && hostToShow.equals(host));\n\t}\n\n\t@Override\n\tpublic void deviceChangedName(Device device, String oldName) {\n\t\tDevicePanel dp = devicesMap.remove(oldName);\n\t\tif (dp != null) {\n\t\t\tdp.setDeviceNameLabel(device.getName());\n\t\t\tdevicesMap.put(device.getName(), dp);\n\t\t}\n\t}\n\n\tpublic void disableCapture(Device d) {\n\t\tDevicePanel dp = devicesMap.get(d.getName());\n\t\tif (dp != null) {\n\t\t\tdp.setCaptureButton(false);\n\t\t}\n\t}\n\n}", "public class HostsContainer extends BasePanel implements\n\t\tDeviceModelChangeListener {\n\n\tprivate static final long serialVersionUID = -5880806310788196376L;\n\n\tprivate GridBagLayout hostListLayout;\n\n\tprivate final Map<String, HostPanel> hostsMap = new HashMap<String, HostPanel>();\n\n\tprivate final List<HostPanel> hostList = new ArrayList<HostPanel>();\n\n\tprivate final PersistentDeviceModel model;\n\n\t/**\n\t * Create a new container listening to the model\n\t * \n\t * @param model\n\t * the model to listen to changes\n\t */\n\tpublic HostsContainer(PersistentDeviceModel model) {\n\t\tsetLayout(hostListLayout = new GridBagLayout());\n\t\tthis.model = model;\n\t\tmodel.addModelChangedListener(this);\n\t}\n\n\t/**\n\t * Add a new host to this container. All its devices will be added as well\n\t * \n\t * @param host\n\t * the host to add\n\t * @return the panel created as the result of this add operation\n\t */\n\tHostPanel addHost(Host host) {\n\t\tHostPanel hostpanel = new HostPanel(model, host);\n\t\t// the host isn't in the panel, then add it.\n\t\tif (!hostsMap.keySet().contains(host.getName())) {\n\t\t\tClientConnectionManager.getInstance().addClientChangedListener(\n\t\t\t\t\thostpanel);\n\t\t\tGridBagConstraints constraints = new GridBagConstraints();\n\t\t\tconstraints.anchor = GridBagConstraints.PAGE_START;\n\t\t\tconstraints.fill = GridBagConstraints.HORIZONTAL;\n\t\t\tconstraints.gridx = 0;\n\t\t\tconstraints.weightx = 1;\n\n\t\t\tif (hostList.size() > 0) {\n\t\t\t\tGridBagConstraints lastConstraints = hostListLayout\n\t\t\t\t\t\t.getConstraints(hostList.get(hostList.size() - 1));\n\t\t\t\tlastConstraints.weighty = 0;\n\t\t\t\thostListLayout.setConstraints(\n\t\t\t\t\t\thostList.get(hostList.size() - 1), lastConstraints);\n\t\t\t}\n\t\t\tconstraints.weighty = 1;\n\t\t\thostList.add(hostpanel);\n\n\t\t\thostListLayout.addLayoutComponent(hostpanel, constraints);\n\t\t\tadd(hostpanel);\n\t\t\thostsMap.put(host.getName(), hostpanel);\n\t\t} // The host is already in the list, just return it.\n\t\telse {\n\t\t\thostpanel = hostsMap.get(host.getName());\n\t\t}\n\t\treturn hostpanel;\n\t}\n\n\t/**\n\t * Remove a host\n\t * \n\t * @param host\n\t */\n\tprivate void removeHost(Host host) {\n\t\tHostPanel hp = hostsMap.remove(host.getName());\n\t\tif (hp != null) {\n\t\t\tClientConnectionManager.getInstance().removeClientChangedListener(\n\t\t\t\t\thp);\n\n\t\t\tif ((hostList.size() > 1)\n\t\t\t\t\t&& (hostList.indexOf(hp) == (hostList.size() - 1))) {\n\t\t\t\tGridBagConstraints newLastConstraints = hostListLayout\n\t\t\t\t\t\t.getConstraints(hostList.get(hostList.size() - 2));\n\t\t\t\tnewLastConstraints.weighty = 1;\n\t\t\t\thostListLayout.setConstraints(\n\t\t\t\t\t\thostList.get(hostList.size() - 2), newLastConstraints);\n\t\t\t}\n\t\t\tremove(hp);\n\t\t\trevalidate();\n\t\t\trepaint();\n\t\t}\n\t}\n\n\t@Override\n\tpublic void deviceAdded(Device device) {\n\t\thostsMap.get(device.getHost()).addDevice(device);\n\t}\n\n\t@Override\n\tpublic void deviceRemoved(Device device) {\n\t\tHostPanel panel = hostsMap.get(device.getHost());\n\t\tif (panel != null) {\n\t\t\tpanel.removeDevice(device);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void hostAdded(Host host) {\n\t\tHostPanel panel = addHost(host);\n\t\tfor (Device d : host.getDevices()) {\n\t\t\tpanel.addDevice(d);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void hostRemoved(Host host) {\n\t\tremoveHost(host);\n\t}\n\n\t@Override\n\tpublic void deviceChangedName(Device device, String oldName) {\n\t\tHostPanel hp = hostsMap.get(device.getHost());\n\t\tif (hp != null) {\n\t\t\thp.getDevicePanel(device.getSerialNumber()).setDeviceNameLabel(\n\t\t\t\t\tdevice.getName());\n\t\t}\n\t}\n\n\tpublic void disableCapture(Device d) {\n\t\tHostPanel hp = hostsMap.get(d.getHost());\n\t\tDevicePanel dp = hp.getDevicePanel(d.getSerialNumber());\n\t\tif (dp != null) {\n\t\t\tdp.setCaptureButton(false);\n\t\t}\n\t}\n\n}" ]
import com.eldorado.remoteresources.android.client.screencapture.CaptureManager; import com.eldorado.remoteresources.i18n.RemoteResourcesLocalization; import com.eldorado.remoteresources.i18n.RemoteResourcesMessages; import com.eldorado.remoteresources.ui.DevicesContainer; import com.eldorado.remoteresources.ui.HostsContainer; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.swing.JOptionPane;
devices.put(device.getName(), device); devicesHistory.put(device.getSerialNumber(), device); } Host host = hosts.get(device.getHost()); if (!host.getDevices().contains(device)) { host.addDevice(device); } if (notifyListeners) { for (DeviceModelChangeListener listener : listeners) { listener.deviceAdded(device); } } } public void addHost(Host host) { if (hosts.get(host.getName()) == null) { hosts.put(host.getName(), host); } for (DeviceModelChangeListener listener : listeners) { listener.hostAdded(host); } for (Device device : host.getDevices()) { addDevice(device, false); } } public void removeDevice(Device device) { removeDevice(device, true); } private void removeDevice(Device device, boolean notify) { boolean disconnectDevice = true; Host h = hosts.get(device.getHost()); if (h != null) { int option = JOptionPane .showOptionDialog( null, RemoteResourcesLocalization .getMessage(RemoteResourcesMessages.ConnectDeviceAction_RemoveDevice), RemoteResourcesLocalization .getMessage(RemoteResourcesMessages.ConnectDeviceAction_RemoveDeviceTitle), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, new String[] { RemoteResourcesLocalization .getMessage(RemoteResourcesMessages.ConnectDeviceAction_RemoveDeviceYes), RemoteResourcesLocalization .getMessage(RemoteResourcesMessages.ConnectDeviceAction_RemoveDeviceNo) }, null); disconnectDevice = option == JOptionPane.YES_OPTION ? true : false; } if (disconnectDevice) { Device d = devices.remove(device.getName()); if (!d.getHost().equalsIgnoreCase(LOCALHOST)) { devicesHistory.remove(d.getSerialNumber()); } if (h != null) { h.getDevices().remove(d.getName()); } if ((d != null) && notify) { for (DeviceModelChangeListener listener : listeners) { listener.deviceRemoved(d); } } } else { Device d = devices.get(device.getName()); if ((d != null) && notify) { for (DeviceModelChangeListener listener : listeners) { if (listener instanceof DevicesContainer) { ((DevicesContainer) listener).disableCapture(d); } else if (listener instanceof HostsContainer) { ((HostsContainer) listener).disableCapture(d); } } } } } public void changeDeviceName(Device device, String oldName) { Device d = devices.get(oldName); if (d != null) { devices.remove(oldName); devices.put(device.getName(), device); for (DeviceModelChangeListener listener : listeners) { listener.deviceChangedName(device, oldName); } } } public void removeHost(String name) { Host h = hosts.remove(name); boolean disconnectHost = true; int option = JOptionPane .showConfirmDialog( null, RemoteResourcesLocalization .getMessage(RemoteResourcesMessages.HostPanel_RemoveHost), "Remove Host", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); disconnectHost = option == JOptionPane.YES_OPTION ? true : false; if (disconnectHost) { if (h != null) { for (Device device : h.getDevices()) { removeDevice(device, false);
CaptureManager.getInstance().stopCapture();
0
tkrajina/10000sentences
10000sentencesapp/src/main/java/info/puzz/a10000sentences/tasks/ImporterAsyncTask.java
[ "public class Application extends android.app.Application {\n\n public static DiComponent COMPONENT;\n\n @Override\n public void onCreate() {\n super.onCreate();\n initIconify();\n initActiveAndroid();\n initDagger();\n }\n\n private void initDagger() {\n COMPONENT = DaggerDiComponent.builder()\n .appModule(new AppModule())\n .build();\n }\n\n private void initIconify() {\n //FontAwesomeIcons.fa_volume_up\n Iconify.with(new FontAwesomeModule());\n }\n\n private void initActiveAndroid() {\n ActiveAndroid.initialize(this);\n }\n\n}", "public class BaseActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {\n\n private static final Random RANDOM = new SecureRandom(String.valueOf(System.currentTimeMillis()).getBytes());\n\n private static final String TAG = BaseActivity.class.getSimpleName();\n\n private boolean collectionNavigationSet;\n\n @Inject\n Dao dao;\n\n public interface OnCollectionsReloaded {\n public void onCollectionsReloaded();\n }\n\n @Override\n protected void onPause() {\n super.onPause();\n if (BuildConfig.DEBUG) {\n // Test db locally with:\n //adb pull /sdcard/debug_10000sentences.db && sqlite3 debug_10000sentences.db\n DebugUtils.backupDatabase(this, \"10000sentences.db\");\n }\n }\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n Application.COMPONENT.inject(this);\n }\n\n @Override\n protected void onResume() {\n super.onResume();\n initNavigation();\n }\n\n protected boolean isNetworkAvailable() {\n ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();\n return activeNetworkInfo != null && activeNetworkInfo.isConnected();\n }\n\n void reloadLanguages() {\n if (!isNetworkAvailable()) {\n Toast.makeText(this, getString(R.string.no_newtork), Toast.LENGTH_SHORT).show();\n return;\n }\n\n final ProgressDialog progressDialog = new ProgressDialog(this);\n progressDialog.setTitle(\"Loading\");\n progressDialog.setMessage(\"Loading\");\n progressDialog.show();\n\n Call<InfoVO> info = Api.instance().info(RANDOM.nextInt());\n info.enqueue(new Callback<InfoVO>() {\n @Override\n public void onResponse(Call<InfoVO> call, Response<InfoVO> response) {\n try {\n _onResponse(response);\n Toast.makeText(BaseActivity.this, getString(R.string.imported), Toast.LENGTH_SHORT).show();\n } finally {\n progressDialog.hide();\n }\n }\n\n private void _onResponse(Response<InfoVO> response) {\n Log.i(TAG, String.valueOf(response.body()));\n InfoVO info = response.body();\n if (info == null || info.getLanguages() == null) {\n Toast.makeText(BaseActivity.this, getString(R.string.error_retrieving), Toast.LENGTH_SHORT).show();\n return;\n }\n for (LanguageVO languageVO : info.getLanguages()) {\n Language language = new Language()\n .setLanguageId(languageVO.getAbbrev())\n .setFamily(languageVO.getFamily())\n .setName(languageVO.getName())\n .setNativeName(languageVO.getNativeName())\n .setRightToLeft(languageVO.isRightToLeft());\n dao.importLanguage(language);\n }\n for (SentenceCollectionVO collectionVO : info.getSentenceCollections()) {\n SentenceCollection col = new SentenceCollection()\n .setCollectionID(String.format(\"%s-%s\", collectionVO.getKnownLanguage(), collectionVO.getTargetLanguage()))\n .setKnownLanguage(collectionVO.getKnownLanguage())\n .setTargetLanguage(collectionVO.getTargetLanguage())\n .setType(collectionVO.getType())\n .setFilename(collectionVO.getFilename());\n dao.importCollection(col);\n }\n\n if (BaseActivity.this instanceof OnCollectionsReloaded) {\n ((OnCollectionsReloaded) BaseActivity.this).onCollectionsReloaded();\n }\n }\n\n @Override\n public void onFailure(Call<InfoVO> call, Throwable t) {\n progressDialog.hide();\n Log.e(TAG, t.getMessage(), t);\n Toast.makeText(BaseActivity.this, getString(R.string.error_retrieving), Toast.LENGTH_SHORT).show();\n }\n });\n }\n\n private void initNavigation() {\n Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);\n setSupportActionBar(toolbar);\n\n DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);\n ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(\n this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);\n drawer.setDrawerListener(toggle);\n toggle.syncState();\n\n NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);\n navigationView.setNavigationItemSelectedListener(this);\n\n setupMenuIcon(navigationView, R.id.nav_collections, FontAwesomeIcons.fa_list);\n setupMenuIcon(navigationView, R.id.nav_reload, FontAwesomeIcons.fa_refresh);\n setupMenuIcon(navigationView, R.id.nav_annotations, FontAwesomeIcons.fa_language);\n setupMenuIcon(navigationView, R.id.nav_stats, FontAwesomeIcons.fa_line_chart);\n setupMenuIcon(navigationView, R.id.nav_settings, FontAwesomeIcons.fa_toggle_on);\n setupMenuIcon(navigationView, R.id.nav_tts_settings, FontAwesomeIcons.fa_file_sound_o);\n setupMenuIcon(navigationView, R.id.nav_about, FontAwesomeIcons.fa_info);\n setupMenuIcon(navigationView, R.id.nav_help, FontAwesomeIcons.fa_question);\n\n setupCollectionsNavigation(navigationView);\n }\n\n private void setupCollectionsNavigation(NavigationView navigationView) {\n if (collectionNavigationSet) {\n return;\n }\n collectionNavigationSet = true;\n\n SubMenu submenu = navigationView.getMenu().addSubMenu(R.string.downloaded_colections);\n Map<String, Language> languages = dao.getLanguagesByLanguageID();\n\n for (final SentenceCollection collection : dao.getCollections()) {\n Language language = languages.get(collection.targetLanguage);\n if (language == null) {\n continue;\n }\n if (collection.todoCount == 0) {\n continue;\n }\n MenuItem menu = submenu.add(language.name).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {\n @Override\n public boolean onMenuItemClick(MenuItem menuItem) {\n CollectionActivity.start(BaseActivity.this, collection.collectionID);\n return true;\n }\n });\n setupMenuIcon(menu, FontAwesomeIcons.fa_language);\n }\n }\n\n @Override\n public void onBackPressed() {\n DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);\n if (drawer.isDrawerOpen(GravityCompat.START)) {\n drawer.closeDrawer(GravityCompat.START);\n } else {\n super.onBackPressed();\n }\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n // Handle action bar item clicks here. The action bar will\n // automatically handle clicks on the Home/Up button, so long\n // as you specify a parent activity in AndroidManifest.xml.\n int id = item.getItemId();\n\n //noinspection SimplifiableIfStatement\n if (id == R.id.action_settings) {\n return true;\n }\n\n return super.onOptionsItemSelected(item);\n }\n\n @SuppressWarnings(\"StatementWithEmptyBody\")\n @Override\n public boolean onNavigationItemSelected(MenuItem item) {\n // Handle navigation view item clicks here.\n int id = item.getItemId();\n\n if (id == R.id.nav_collections) {\n CollectionsActivity.start(this);\n } else if (id == R.id.nav_annotations) {\n AnnotationsActivity.start(this);\n } else if (id == R.id.nav_reload) {\n reloadLanguages();\n } else if (id == R.id.nav_stats) {\n StatsActivity.start(this);\n } else if (id == R.id.nav_settings) {\n SettingsActivity.start(this);\n } else if (id == R.id.nav_tts_settings) {\n Intent intent = new Intent()\n .setAction(\"com.android.settings.TTS_SETTINGS\")\n .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n startActivity(intent);\n } else if (id == R.id.nav_about) {\n try {\n PackageInfo info = getPackageManager().getPackageInfo(this.getPackageName(), 0);\n HtmlActivity.start(this, getString(R.string.about), getString(R.string.info_contents, info.versionName, String.valueOf(info.versionCode)), false);\n } catch (Exception e) {\n Toast.makeText(this, R.string.unexpected_error, Toast.LENGTH_SHORT).show();\n Log.e(TAG, e.getMessage(), e);\n }\n } else if (id == R.id.nav_help) {\n HtmlActivity.start(this, getString(R.string.help), getString(R.string.help_contents), true);\n }\n\n DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);\n drawer.closeDrawer(GravityCompat.START);\n return true;\n }\n\n private void setupMenuIcon(NavigationView navigationView, int menuResId, FontAwesomeIcons icon) {\n MenuItem menuItem = navigationView.getMenu().findItem(menuResId);\n setupMenuIcon(menuItem, icon);\n }\n\n private void setupMenuIcon(MenuItem menuItem, FontAwesomeIcons icon) {\n menuItem.setIcon(new IconDrawable(this, icon).colorRes(R.color.colorPrimary).actionBarSize());\n }\n}", "public class Dao {\n\n @Inject\n public Dao() {\n }\n\n public void importLanguage(Language language) {\n language.save();\n }\n\n public void importCollection(SentenceCollection col) {\n SentenceCollection sentenceCollection = new Select()\n .from(SentenceCollection.class)\n .where(\"collection_id = ?\", col.getCollectionID())\n .executeSingle();\n if (sentenceCollection != null) {\n sentenceCollection\n .setType(col.getType())\n .setFilename(col.getFilename())\n .save();\n } else {\n col.save();\n }\n }\n\n public void importSentences(List<Sentence> sentences) {\n\n List<String> ids = new ArrayList<>();\n for (Sentence sentence : sentences) {\n ids.add(sentence.getSentenceId());\n }\n\n List<Sentence> existingSentences = new Select()\n .from(Sentence.class)\n .where(\n String.format(\"sentence_id in (%s)\", StringUtils.repeat(\"? \", sentences.size()).trim().replace(\" \", \",\")),\n ids.toArray(new String[ids.size()]))\n .execute();\n\n Map<String, Sentence> existingSentencesMap = new HashMap<>();\n for (Sentence model : existingSentences) {\n existingSentencesMap.put(model.getSentenceId(), model);\n }\n\n ActiveAndroid.beginTransaction();\n try {\n for (Sentence sentence : sentences) {\n if (existingSentencesMap.containsKey(sentence.getSentenceId())) {\n Sentence existingSentence = existingSentencesMap.get(sentence.getSentenceId());\n existingSentence.setTargetSentence(sentence.getTargetSentence());\n existingSentence.setKnownSentence(sentence.getKnownSentence());\n existingSentence.setComplexity(sentence.getComplexity());\n existingSentence.save();\n } else {\n sentence.save();\n }\n }\n ActiveAndroid.setTransactionSuccessful();\n } finally {\n ActiveAndroid.endTransaction();\n }\n }\n\n public List<SentenceCollection> getCollections() {\n return new Select()\n .from(SentenceCollection.class)\n .orderBy(\"-done_count, target_lang, known_lang\")\n .execute();\n }\n\n public List<Language> getLanguages() {\n return new Select()\n .from(Language.class)\n .execute();\n }\n\n public SentenceCollection getCollection(String collectionId) {\n if (StringUtils.isEmpty(collectionId)) {\n return null;\n }\n\n return new Select()\n .from(SentenceCollection.class)\n .where(\"collection_id = ?\", collectionId)\n .executeSingle();\n }\n\n public Language getLanguage(String languageID) {\n List<Language> res = new Select()\n .from(Language.class)\n .where(\"language_id = ?\", languageID)\n .limit(1)\n .execute();\n if (res.size() == 0) {\n return null;\n }\n return res.get(0);\n }\n\n public SentenceCollection reloadCollectionCounter(SentenceCollection collection) {\n DBG.todo(\"Threads\");\n\n int rows = SQLiteUtils.intQuery(\n \"select count(*) from sentence where collection_id = ?\",\n new String[] {collection.getCollectionID()});\n int todoRows = SQLiteUtils.intQuery(\n \"select count(*) from sentence where collection_id = ? and status = ?\",\n new String[] {collection.getCollectionID(), String.valueOf(SentenceStatus.TODO.getStatus())});\n int againRows = SQLiteUtils.intQuery(\n \"select count(*) from sentence where collection_id = ? and status = ?\",\n new String[] {collection.getCollectionID(), String.valueOf(SentenceStatus.REPEAT.getStatus())});\n int doneRows = SQLiteUtils.intQuery(\n \"select count(*) from sentence where collection_id = ? and status = ?\",\n new String[] {collection.getCollectionID(), String.valueOf(SentenceStatus.DONE.getStatus())});\n int ignoreRows = SQLiteUtils.intQuery(\n \"select count(*) from sentence where collection_id = ? and status = ?\",\n new String[] {collection.getCollectionID(), String.valueOf(SentenceStatus.IGNORE.getStatus())});\n int skippedRows = SQLiteUtils.intQuery(\n \"select count(*) from sentence where collection_id = ? and status = ?\",\n new String[] {collection.getCollectionID(), String.valueOf(SentenceStatus.SKIPPED.getStatus())});\n int annotationCount = SQLiteUtils.intQuery(\n \"select count(*) from annotation where collection_id = ?\",\n new String[] {collection.getCollectionID()});\n\n if (todoRows > SentenceCollection.MAX_SENTENCES) {\n todoRows = SentenceCollection.MAX_SENTENCES;\n }\n todoRows = todoRows - doneRows - skippedRows;\n\n collection.count = rows;\n collection.todoCount = todoRows;\n collection.repeatCount = againRows;\n collection.doneCount = doneRows;\n collection.ignoreCount = ignoreRows;\n collection.annotationCount = annotationCount;\n collection.skippedCount = skippedRows;\n collection.save();\n\n return collection;\n }\n\n public List<Sentence> getRandomSentences(SentenceCollection collection) {\n return new Select()\n .from(Sentence.class)\n .where(\"collection_id = ?\", collection.collectionID)\n .orderBy(\"random()\")\n .limit(100)\n .execute();\n }\n\n public void removeCollectionSentences(SentenceCollection collection) {\n new Delete()\n .from(Sentence.class)\n .where(\"collection_id=?\", collection.getCollectionID())\n .execute();\n reloadCollectionCounter(collection);\n }\n\n public Map<String, Language> getLanguagesByLanguageID() {\n HashMap<String, Language> res = new HashMap<>();\n for (Language language : getLanguages()) {\n res.put(language.getLanguageId(), language);\n }\n return res;\n }\n\n public Sentence getSentenceBySentenceId(String sentenceId) {\n return new Select()\n .from(Sentence.class)\n .where(\"sentence_id = ?\", sentenceId)\n .executeSingle();\n }\n\n public From getSentencesByCollection(String collectionId, String filter) {\n From res = new Select()\n .from(Sentence.class)\n .where(\"collection_id=?\", collectionId);\n if (!StringUtils.isEmpty(filter)) {\n SqlFilterUtils.addFilter(res, new String[]{\"known\", \"target\"}, filter);\n }\n res.orderBy(\"complexity\");\n return res;\n }\n\n public From getSentencesByCollectionAndStatus(String collectionId, int sentenceStatus, String filter) {\n From res = new Select()\n .from(Sentence.class)\n .where(\"(collection_id=? and status=?)\", collectionId, sentenceStatus);\n if (!StringUtils.isEmpty(filter)) {\n SqlFilterUtils.addFilter(res, new String[]{\"known\", \"target\"}, filter);\n }\n res.orderBy(\"complexity\");\n return res;\n }\n\n public SentenceHistory getLatestSentenceHistory() {\n return new Select()\n .from(SentenceHistory.class)\n .orderBy(\"created desc\")\n .executeSingle();\n }\n}", "@Table(name = \"sentence\")\npublic class Sentence extends Model {\n\n @Column(name = \"sentence_id\", index = true, unique = true, onUniqueConflict = Column.ConflictAction.REPLACE)\n public String sentenceId;\n\n @Column(name = \"collection_id\", index = true)\n public String collectionId;\n\n @Column(name = \"known\")\n public String knownSentence;\n\n @Column(name = \"target\")\n public String targetSentence;\n\n @Column(name = \"status\")\n public int status = SentenceStatus.TODO.getStatus();\n\n @Column(name = \"complexity\", index = true)\n float complexity;\n\n public String[] getKnownSentences() {\n String[] res = String.valueOf(knownSentence).split(\"\\\\|\");\n if (res.length == 1) {\n return res;\n }\n for (int i = 0; i < res.length; i++) {\n res[i] += String.format(\" [%d/%d]\", i+1, res.length);\n }\n return res;\n }\n\n public String getFirstKnownSentence() {\n return getKnownSentences()[0];\n }\n\n public SentenceStatus getSentenceStatus() {\n return SentenceStatus.fromStatus(status);\n }\n\n public String getSentenceId() {\n return sentenceId;\n }\n\n public Sentence setSentenceId(String sentenceId) {\n this.sentenceId = sentenceId;\n return this;\n }\n\n public String getCollectionId() {\n return collectionId;\n }\n\n public Sentence setCollectionId(String collectionId) {\n this.collectionId = collectionId;\n return this;\n }\n\n public String getKnownSentence() {\n return knownSentence;\n }\n\n public Sentence setKnownSentence(String knownSentence) {\n this.knownSentence = knownSentence;\n return this;\n }\n\n public String getTargetSentence() {\n return targetSentence;\n }\n\n public Sentence setTargetSentence(String targetSentence) {\n this.targetSentence = targetSentence;\n return this;\n }\n\n public int getStatus() {\n return status;\n }\n\n public Sentence setStatus(int status) {\n this.status = status;\n return this;\n }\n\n public float getComplexity() {\n return complexity;\n }\n\n public Sentence setComplexity(float complexity) {\n this.complexity = complexity;\n return this;\n }\n}", "@Table(name = \"sentence_collection\")\npublic class SentenceCollection extends Model {\n\n private static final NumberFormat NUMBER_FORMAT = NumberFormat.getNumberInstance(Locale.US);\n public static final int MAX_SENTENCES = 10_000;\n\n @Column(name = \"collection_id\", index = true, unique = true, onUniqueConflict = Column.ConflictAction.REPLACE)\n public String collectionID;\n\n @Column(name = \"known_lang\")\n public String knownLanguage;\n\n @Column(name = \"target_lang\")\n public String targetLanguage;\n\n @Column(name = \"filename\")\n public String filename;\n\n @Column(name = \"count\")\n public int count;\n\n @Column(name = \"todo_count\")\n public int todoCount;\n\n @Column(name = \"repeat_count\")\n public int repeatCount;\n\n @Column(name = \"done_count\")\n public int doneCount;\n\n @Column(name = \"ignore_count\")\n public int ignoreCount;\n\n @Column(name = \"skipped_count\")\n public int skippedCount;\n\n @Column(name = \"annotation_count\")\n public int annotationCount;\n\n @Column(name=\"type\")\n public CollectionType type;\n\n public boolean isDownloaded() {\n return count > 0;\n }\n\n public String formatDoneCount() {\n return formatCount(doneCount);\n }\n\n public String formatTodoCount() {\n return formatCount(todoCount);\n }\n\n public String formatIgnoreCount() {\n return formatCount(ignoreCount);\n }\n\n public String formatSkippedCount() {\n return formatCount(skippedCount);\n }\n\n public String formatRepeatCount() {\n return formatCount(repeatCount);\n }\n\n public String formatAnnotationCount() {\n return formatCount(annotationCount);\n }\n\n private String formatCount(int count) {\n if (count <= MAX_SENTENCES) {\n return NUMBER_FORMAT.format(count);\n }\n return NUMBER_FORMAT.format(MAX_SENTENCES) + \"+\";\n }\n\n public String getCollectionID() {\n return collectionID;\n }\n\n public SentenceCollection setCollectionID(String collectionID) {\n this.collectionID = collectionID;\n return this;\n }\n\n public String getKnownLanguage() {\n return knownLanguage;\n }\n\n public SentenceCollection setKnownLanguage(String knownLanguage) {\n this.knownLanguage = knownLanguage;\n return this;\n }\n\n public String getTargetLanguage() {\n return targetLanguage;\n }\n\n public SentenceCollection setTargetLanguage(String targetLanguage) {\n this.targetLanguage = targetLanguage;\n return this;\n }\n\n public String getFilename() {\n return filename;\n }\n\n public SentenceCollection setFilename(String filename) {\n this.filename = filename;\n return this;\n }\n\n public int getCount() {\n return count;\n }\n\n public SentenceCollection setCount(int count) {\n this.count = count;\n return this;\n }\n\n public int getTodoCount() {\n return todoCount;\n }\n\n public SentenceCollection setTodoCount(int todoCount) {\n this.todoCount = todoCount;\n return this;\n }\n\n public int getRepeatCount() {\n return repeatCount;\n }\n\n public SentenceCollection setRepeatCount(int repeatCount) {\n this.repeatCount = repeatCount;\n return this;\n }\n\n public int getDoneCount() {\n return doneCount;\n }\n\n public SentenceCollection setDoneCount(int doneCount) {\n this.doneCount = doneCount;\n return this;\n }\n\n public int getIgnoreCount() {\n return ignoreCount;\n }\n\n public SentenceCollection setIgnoreCount(int ignoreCount) {\n this.ignoreCount = ignoreCount;\n return this;\n }\n\n public int getSkippedCount() {\n return skippedCount;\n }\n\n public SentenceCollection setSkippedCount(int skippedCount) {\n this.skippedCount = skippedCount;\n return this;\n }\n\n public int getAnnotationCount() {\n return annotationCount;\n }\n\n public SentenceCollection setAnnotationCount(int annotationCount) {\n this.annotationCount = annotationCount;\n return this;\n }\n\n public CollectionType getType() {\n return type;\n }\n\n public SentenceCollection setType(CollectionType type) {\n this.type = type;\n return this;\n }\n}" ]
import android.app.ProgressDialog; import android.content.pm.ActivityInfo; import android.os.AsyncTask; import android.widget.Toast; import com.activeandroid.util.Log; import org.apache.commons.lang3.StringUtils; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import info.puzz.a10000sentences.Application; import info.puzz.a10000sentences.R; import info.puzz.a10000sentences.activities.BaseActivity; import info.puzz.a10000sentences.dao.Dao; import info.puzz.a10000sentences.models.Sentence; import info.puzz.a10000sentences.models.SentenceCollection; import okhttp3.Call; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response;
package info.puzz.a10000sentences.tasks; public class ImporterAsyncTask extends AsyncTask<String, Integer, Void> { private static final java.lang.String TAG = ImporterAsyncTask.class.getSimpleName(); public static final int PROGRESS_EVERY = 50; @Inject Dao dao; private final BaseActivity activity; private final ProgressDialog progressDialog; private final SentenceCollection collection; private final CollectionReloadedListener listener; public interface CollectionReloadedListener { void onCollectionReloaded(SentenceCollection collection); } public ImporterAsyncTask(BaseActivity activity, SentenceCollection collection, CollectionReloadedListener listener) { Application.COMPONENT.inject(this); this.activity = activity; this.collection = collection; this.listener = listener; this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR); progressDialog = new ProgressDialog(activity); progressDialog.setTitle("Loading"); progressDialog.setMessage("Loading"); progressDialog.show(); } @Override protected Void doInBackground(String... strings) { String url = strings[0]; publishProgress(0); OkHttpClient httpClient = new OkHttpClient(); Call call = httpClient.newCall(new Request.Builder().url(url).get().build()); try { Response response = call.execute(); InputStream stream = response.body().byteStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
List<Sentence> sentences = new ArrayList<>();
3
darko1002001/android-rest-client
rest-client-demo/src/main/java/com/dg/examples/restclientdemo/MainActivity.java
[ "public class BlogsGoogleRequest extends RestClientRequest<ResponseModel> {\n\n public static final String TAG = BlogsGoogleRequest.class.getSimpleName();\n\n public BlogsGoogleRequest(String query) {\n super();\n setRequestMethod(RequestMethod.GET);\n setUrl(RestConstants.GOOGLE_BLOGS);\n\n setParser(new BlogsGoogleParser());\n\n addQueryParam(\"q\", query);\n addQueryParam(\"v\", \"1.0\");\n addQueryParam(\"include_entities\", \"\" + true);\n }\n\n @Override\n protected void doAfterSuccessfulRequestInBackgroundThread(ResponseModel data) {\n try {\n\n Log.d(TAG, \"sleeping to be able to see Bound callbacks in action\");\n Thread.sleep(3000);\n } catch (InterruptedException e) {\n }\n super.doAfterSuccessfulRequestInBackgroundThread(data);\n }\n\n @Override\n protected void customizeClient(OkHttpClient client) {\n super.customizeClient(client);\n client.setRetryOnConnectionFailure(false);\n }\n}", "public class PatchRequest extends RestClientRequest<Void> {\n\n public static final String TAG = PatchRequest.class.getSimpleName();\n\n public PatchRequest(String query) {\n super();\n\n setParser(new HttpResponseParser<Void>() {\n @Override\n public Void parse(InputStream instream) throws Exception {\n Log.d(TAG, org.apache.commons.io.IOUtils.toString(instream));\n return null;\n }\n });\n\n setRequestMethod(RequestMethod.PATCH);\n addEncodedQueryParam(\"q\", query);\n addQueryParam(\"v\", \"1.0\");\n addQueryParam(\"include_entities\", \"\" + true);\n setUrl(RestConstants.HTTP_BIN_URL + \"patch\");\n }\n\n}", "public class ResponseModel {\n // To learn how to configure this go here:\n // http://wiki.fasterxml.com/JacksonInFiveMinutes\n // Url to pull down is set under communication/RestConstants.java\n public static final String TAG = ResponseModel.class.getSimpleName();\n\n @JsonProperty\n private String responseStatus;\n\n @JsonProperty\n private String responseDetails;\n\n @JsonProperty\n private ResponseDataModel responseData;\n\n public String getResponseStatus() {\n return responseStatus;\n }\n\n public void setResponseStatus(String responseStatus) {\n this.responseStatus = responseStatus;\n }\n\n public String getResponseDetails() {\n return responseDetails;\n }\n\n public void setResponseDetails(String responseDetails) {\n this.responseDetails = responseDetails;\n }\n\n public ResponseDataModel getResponseData() {\n return responseData;\n }\n\n public void setResponseData(ResponseDataModel responseData) {\n this.responseData = responseData;\n }\n\n @Override\n public String toString() {\n return \"ResponseModel [responseStatus=\" + responseStatus\n + \", responseDetails=\" + responseDetails + \", responseData=\"\n + responseData + \"]\";\n }\n\n\n}", "public interface HttpCallback<T> {\n\n /**\n * This method shows that the callback successfully finished. It contains\n * response data which represents the return type of the callback.\n * \n * @param responseData\n * It can be of any type.\n */\n void onSuccess(T responseData, ResponseStatus responseStatus);\n\n /**\n * This method shows that the callback has failed due to server issue, no\n * connectivity or parser error\n * \n * @param responseStatus\n */\n void onHttpError(ResponseStatus responseStatus);\n\n}", "public class ResponseStatus {\n\n public static final String TAG = ResponseStatus.class.getSimpleName();\n\n private int statusCode;\n private String statusMessage;\n\n public ResponseStatus(int statusCode, String statusMessage) {\n this.statusCode = statusCode;\n this.statusMessage = statusMessage;\n }\n\n public ResponseStatus() {\n }\n\n public int getStatusCode() {\n return statusCode;\n }\n\n public void setStatusCode(int statusCode) {\n this.statusCode = statusCode;\n }\n\n public String getStatusMessage() {\n return statusMessage;\n }\n\n public void setStatusMessage(String statusMessage) {\n this.statusMessage = statusMessage;\n }\n\n public static ResponseStatus getConnectionErrorStatus() {\n ResponseStatus status = new ResponseStatus();\n status.setStatusCode(HttpStatus.SC_REQUEST_TIMEOUT);\n status.setStatusMessage(\"HTTP Connection Error\");\n return status;\n }\n\n public static ResponseStatus getParseErrorStatus() {\n ResponseStatus status = new ResponseStatus();\n status.setStatusCode(HttpStatus.SC_BAD_REQUEST);\n status.setStatusMessage(\"Parser Error\");\n return status;\n }\n\n @Override\n public String toString() {\n StringBuilder builder = new StringBuilder();\n builder.append(\"ResponseStatus [statusCode=\");\n builder.append(statusCode);\n builder.append(\", statusMessage=\");\n builder.append(statusMessage);\n builder.append(\"]\");\n return builder.toString();\n }\n\n}", "public abstract class RestClientRequest<T> implements HttpRequest {\n\n private String TAG = RestClientRequest.class.getSimpleName();\n\n private HttpResponseParser<T> parser;\n private ResponseHandler<T> handler;\n private ResponseStatusHandler statusHandler;\n private BoundCallback<T> callback;\n private Request.Builder request = new Request.Builder();\n private StringBuilder queryParams;\n private String url;\n\n RequestOptions requestOptions = null;\n AuthenticationProvider authenticationProvider;\n\n protected RestClientRequest() {\n authenticationProvider = RestClientConfiguration.get().getAuthenticationProvider();\n }\n\n public RestClientRequest<T> setAuthenticationProvider(AuthenticationProvider authenticationProvider) {\n this.authenticationProvider = authenticationProvider;\n return this;\n }\n\n protected HttpCallback<T> getCallback() {\n return callback;\n }\n\n public RestClientRequest<T> setCallback(HttpCallback<T> callback) {\n BoundCallback<T> boundCallback = new BoundCallback<>(callback);\n this.callback = boundCallback;\n return this;\n }\n\n public RestClientRequest<T> setActivityBoundCallback(Activity activity, HttpCallback<T> callback) {\n this.callback = new ActivityBoundHttpCallback<>(activity, callback);\n return this;\n }\n\n public RestClientRequest<T> setFragmentBoundCallback(Fragment fragment, HttpCallback<T> callback) {\n this.callback = new FragmentBoundHttpCallback<>(fragment, callback);\n return this;\n }\n\n\n public RestClientRequest<T> setParser(HttpResponseParser<T> parser) {\n this.parser = parser;\n return this;\n }\n\n public ResponseHandler<T> getHandler() {\n return handler;\n }\n\n /**\n * Adds a new header value, existing value with same key will not be overwritten\n *\n * @param key\n * @param value\n */\n public RestClientRequest<T> addHeader(final String key, final String value) {\n request.addHeader(key, value);\n return this;\n }\n\n /**\n * Overrides an existing header value\n *\n * @param key\n * @param value\n */\n public RestClientRequest<T> header(final String key, final String value) {\n request.header(key, value);\n return this;\n }\n\n @Override\n public void run() {\n doBeforeRunRequestInBackgroundThread();\n validateRequestArguments();\n runRequest();\n }\n\n public void validateRequestArguments() {\n if (TextUtils.isEmpty(this.url)) {\n Log.e(TAG, \"Request url is empty or null\", new IllegalArgumentException());\n }\n }\n\n @Override\n public void cancel() {\n if (callback != null) {\n callback.unregister();\n }\n }\n\n public boolean isCanceled() {\n return callback != null && callback.isRegistered();\n }\n\n /**\n * Set a custom handler that will be triggered when the response returns\n * either Success or Fail. You can choose where this info is sent. **Default**\n * is the UIThreadREsponseHandler implementation which runs the appropriate\n * callback on the UI thread.\n *\n * @param handler\n */\n public RestClientRequest<T> setResponseHandler(ResponseHandler<T> handler) {\n this.handler = handler;\n return this;\n }\n\n /**\n * By default success is a code in the range of 2xx. Everything else triggers\n * an Error. You can set a handler which will take into account your own\n * custom error codes to determine if the response is a success or fail.\n *\n * @param statusHandler\n */\n public RestClientRequest<T> setStatusHandler(ResponseStatusHandler statusHandler) {\n this.statusHandler = statusHandler;\n return this;\n }\n\n protected HttpResponseParser<T> getParser() {\n return parser;\n }\n\n public RestClientRequest<T> setUrl(String url) {\n this.url = url;\n return this;\n }\n\n /**\n * Access URL formatting options with the format ex. /action/:type/otheraction/:other\n * Removes any suffixes such as query params (url ends with somepath?one=two becomes somepath)\n *\n * @param url a string url\n * @param params\n * @return\n */\n public RestClientRequest<T> setUrlWithFormat(String url, String... params) {\n if (params.length == 0) {\n this.url = url;\n return this;\n }\n int questionMark = url.indexOf(\"?\");\n StringBuilder sb = new StringBuilder(questionMark > -1 ? url.substring(0, questionMark) : url);\n for (String param : params) {\n int start = sb.indexOf(\"/:\");\n if (start == -1) {\n throw new IllegalArgumentException(\"Need to add the same amount of placeholder params in the string as /:value/ where you want to replace it\");\n }\n int end = sb.indexOf(\"/\", start + 1);\n if (end == -1) {\n end = sb.length();\n }\n sb.replace(start + 1, end, param);\n }\n this.url = sb.toString();\n return this;\n }\n\n public RestClientRequest<T> setRequestMethod(RequestMethod requestMethod) {\n return setRequestMethod(requestMethod, null);\n\n }\n\n public RestClientRequest<T> setRequestMethod(RequestMethod requestMethod, RequestBody requestBody) {\n request.method(requestMethod.name(), requestBody);\n return this;\n }\n\n protected void runRequest() {\n if (handler == null) {\n handler = new UIThreadResponseHandler<>(callback);\n }\n if (statusHandler == null) {\n statusHandler = new DefaultResponseStatusHandler();\n }\n\n OkHttpClient client = generateClient();\n StringBuilder url = new StringBuilder(this.url);\n StringBuilder queryParams = this.queryParams;\n if (queryParams != null) {\n url.append(queryParams);\n }\n\n request.url(url.toString());\n\n if (this.authenticationProvider != null) {\n authenticationProvider.authenticateRequest(this);\n }\n\n Request preparedRequest = request.build();\n Response response;\n try {\n response = client.newCall(preparedRequest).execute();\n } catch (final Exception e) {\n ResponseStatus responseStatus = ResponseStatus.getConnectionErrorStatus();\n Log.e(TAG, responseStatus.toString(), e);\n handler.handleError(responseStatus);\n doAfterRunRequestInBackgroundThread();\n return;\n }\n\n final ResponseStatus status = new ResponseStatus(response.code(), response.message());\n Log.d(TAG, status.toString());\n if (handleResponseStatus(status)) {\n doAfterRunRequestInBackgroundThread();\n return;\n }\n\n try {\n if (parser != null) {\n InputStream instream = response.body().byteStream();\n final T responseData = parser.parse(instream);\n close(response.body());\n doAfterSuccessfulRequestInBackgroundThread(responseData);\n handler.handleSuccess(responseData, status);\n } else {\n Log.i(TAG, \"You haven't added a parser for your request\");\n handler.handleSuccess(null, status);\n doAfterSuccessfulRequestInBackgroundThread(null);\n }\n } catch (final Exception e) {\n ResponseStatus responseStatus = ResponseStatus.getParseErrorStatus();\n Log.d(TAG, responseStatus.toString(), e);\n handler.handleError(responseStatus);\n }\n doAfterRunRequestInBackgroundThread();\n\n }\n\n /**\n * Return true if you have handled the status yourself.\n */\n protected boolean handleResponseStatus(ResponseStatus status) {\n if (statusHandler.hasErrorInStatus(status)) {\n handler.handleError(status);\n return true;\n }\n return false;\n }\n\n @Override\n public void executeAsync() {\n TaskStore.get(RestClientConfiguration.get().getContext()).queue(this, getRequestOptions());\n }\n\n public RequestOptions getRequestOptions() {\n return requestOptions;\n }\n\n public RestClientRequest<T> setRequestOptions(RequestOptions requestOptions) {\n this.requestOptions = requestOptions;\n return this;\n }\n\n /**\n * Use this method to add the required data to the request. This will happen\n * in the background thread which enables you to pre-process the parameters,\n * do queries etc..\n */\n protected void doBeforeRunRequestInBackgroundThread() {\n }\n\n /**\n * This will happen in the background thread which enables you to do some\n * cleanup in the background after the request finishes\n */\n protected void doAfterRunRequestInBackgroundThread() {\n }\n\n /**\n * This will happen in the background thread only if the request execution is successful\n */\n protected void doAfterSuccessfulRequestInBackgroundThread(T data) {\n }\n\n private OkHttpClient generateClient() {\n OkHttpClient client = new OkHttpClient();\n customizeClient(client);\n return client;\n }\n\n protected void customizeClient(OkHttpClient client) {\n client.setConnectTimeout(RestClientConfiguration.get().getConnectionTimeout(), TimeUnit.MILLISECONDS);\n client.setReadTimeout(RestClientConfiguration.get().getReadTimeout(), TimeUnit.MILLISECONDS);\n client.setWriteTimeout(RestClientConfiguration.get().getWriteTimeout(), TimeUnit.MILLISECONDS);\n }\n\n public RestClientRequest<T> addQueryParam(String name, String value) {\n addQueryParam(name, value, false, true);\n return this;\n }\n\n public RestClientRequest<T> addEncodedQueryParam(String name, String value) {\n addQueryParam(name, value, false, false);\n return this;\n }\n\n private void addQueryParam(String name, Object value, boolean encodeName, boolean encodeValue) {\n if (value instanceof Iterable) {\n for (Object iterableValue : (Iterable<?>) value) {\n if (iterableValue != null) { // Skip null values\n addQueryParam(name, iterableValue.toString(), encodeName, encodeValue);\n }\n }\n } else if (value.getClass().isArray()) {\n for (int x = 0, arrayLength = Array.getLength(value); x < arrayLength; x++) {\n Object arrayValue = Array.get(value, x);\n if (arrayValue != null) { // Skip null values\n addQueryParam(name, arrayValue.toString(), encodeName, encodeValue);\n }\n }\n } else {\n addQueryParam(name, value.toString(), encodeName, encodeValue);\n }\n }\n\n private void addQueryParam(String name, String value, boolean encodeName, boolean encodeValue) {\n if (name == null) {\n throw new IllegalArgumentException(\"Query param name must not be null.\");\n }\n if (value == null) {\n throw new IllegalArgumentException(\"Query param \\\"\" + name + \"\\\" value must not be null.\");\n }\n try {\n StringBuilder queryParams = this.queryParams;\n if (queryParams == null) {\n this.queryParams = queryParams = new StringBuilder();\n }\n\n queryParams.append(queryParams.length() > 0 ? '&' : '?');\n\n if (encodeName) {\n name = URLEncoder.encode(name, \"UTF-8\");\n }\n if (encodeValue) {\n value = URLEncoder.encode(value, \"UTF-8\");\n }\n queryParams.append(name).append('=').append(value);\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(\n \"Unable to convert query parameter \\\"\" + name + \"\\\" value to UTF-8: \" + value, e);\n }\n }\n\n private void close(ResponseBody body) {\n try {\n if (body != null) {\n body.close();\n }\n } catch (IOException e) {\n }\n\n }\n}" ]
import android.app.Activity; import android.os.Bundle; import android.widget.TextView; import android.widget.Toast; import com.dg.examples.restclientdemo.communication.requests.BlogsGoogleRequest; import com.dg.examples.restclientdemo.communication.requests.PatchRequest; import com.dg.examples.restclientdemo.domain.ResponseModel; import com.dg.libs.rest.callbacks.HttpCallback; import com.dg.libs.rest.domain.ResponseStatus; import com.dg.libs.rest.requests.RestClientRequest;
package com.dg.examples.restclientdemo; public class MainActivity extends Activity { private TextView textViewResponse; private RestClientRequest<ResponseModel> request; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textViewResponse = (TextView) findViewById(R.id.textViewResponse); request = new BlogsGoogleRequest("Official Google Blogs").setCallback(new GoogleBlogsCallback()); request .executeAsync();
new PatchRequest("Hello").setCallback(new HttpCallback<Void>() {
3
monkeyk/oauth2-shiro
authz/src/main/java/com/monkeyk/os/oauth/authorize/CodeAuthorizeHandler.java
[ "public class ClientDetails extends BasicClientInfo {\n\n\n /**\n * 客户端所拥有的资源ID(resource-id), 至少有一个,\n * 多个ID时使用逗号(,)分隔, 如: os,mobile\n */\n private String resourceIds;\n\n private String scope;\n\n /**\n * 客户端所支持的授权模式(grant_type),\n * 至少一个, 多个值时使用逗号(,)分隔, 如: password,refresh_token\n */\n private String grantTypes;\n\n /*\n * Shiro roles\n * */\n private String roles;\n\n /**\n * access_token 的有效时长, 单位: 秒.\n * 若不填或为空(null)则使用默认值: 12小时\n */\n private Integer accessTokenValidity;\n\n /**\n * refresh_token的 有效时长, 单位: 秒\n * 若不填或为空(null)则使用默认值: 30天\n */\n private Integer refreshTokenValidity;\n\n /**\n * 该 客户端是否为授信任的,\n * 若为信任的,, 则在 grant_type = authorization_code 时将跳过用户同意/授权 步骤\n */\n private boolean trusted = false;\n\n /**\n * 逻辑删除的标识, true表示已经删除\n */\n private boolean archived = false;\n\n /**\n * 创建时间\n */\n private Date createTime = DateUtils.now();\n\n\n public ClientDetails() {\n }\n\n\n public String resourceIds() {\n return resourceIds;\n }\n\n public ClientDetails resourceIds(String resourceIds) {\n this.resourceIds = resourceIds;\n return this;\n }\n\n public String scope() {\n return scope;\n }\n\n public ClientDetails scope(String scope) {\n this.scope = scope;\n return this;\n }\n\n public String grantTypes() {\n return grantTypes;\n }\n\n public ClientDetails grantTypes(String grantTypes) {\n this.grantTypes = grantTypes;\n return this;\n }\n\n public String roles() {\n return roles;\n }\n\n public ClientDetails roles(String roles) {\n this.roles = roles;\n return this;\n }\n\n public Integer accessTokenValidity() {\n return accessTokenValidity;\n }\n\n public ClientDetails accessTokenValidity(Integer accessTokenValidity) {\n this.accessTokenValidity = accessTokenValidity;\n return this;\n }\n\n public Integer refreshTokenValidity() {\n return refreshTokenValidity;\n }\n\n public ClientDetails refreshTokenValidity(Integer refreshTokenValidity) {\n this.refreshTokenValidity = refreshTokenValidity;\n return this;\n }\n\n public boolean trusted() {\n return trusted;\n }\n\n public ClientDetails trusted(boolean trusted) {\n this.trusted = trusted;\n return this;\n }\n\n public boolean archived() {\n return archived;\n }\n\n public ClientDetails archived(boolean archived) {\n this.archived = archived;\n return this;\n }\n\n public Date createTime() {\n return createTime;\n }\n\n public ClientDetails createTime(Date createTime) {\n this.createTime = createTime;\n return this;\n }\n\n public boolean supportRefreshToken() {\n return this.grantTypes != null && this.grantTypes.contains(GrantType.REFRESH_TOKEN.toString());\n }\n}", "public abstract class WebUtils {\n\n\n private WebUtils() {\n }\n\n\n public static void writeOAuthJsonResponse(HttpServletResponse response, OAuthResponse oAuthResponse) {\n\n final int responseStatus = oAuthResponse.getResponseStatus();\n try {\n\n final Map<String, String> headers = oAuthResponse.getHeaders();\n for (String key : headers.keySet()) {\n response.addHeader(key, headers.get(key));\n }\n // CORS setting\n response.setHeader(\"Access-Control-Allow-Origin\", \"*\");\n\n response.setContentType(OAuth.ContentType.JSON); //json\n response.setStatus(responseStatus);\n\n final PrintWriter out = response.getWriter();\n out.print(oAuthResponse.getBody());\n out.flush();\n } catch (IOException e) {\n throw new IllegalStateException(\"Write OAuthResponse error\", e);\n }\n }\n\n\n public static void writeOAuthQueryResponse(HttpServletResponse response, OAuthResponse oAuthResponse) {\n final String locationUri = oAuthResponse.getLocationUri();\n try {\n\n final Map<String, String> headers = oAuthResponse.getHeaders();\n for (String key : headers.keySet()) {\n response.addHeader(key, headers.get(key));\n }\n\n response.setStatus(oAuthResponse.getResponseStatus());\n response.sendRedirect(locationUri);\n\n } catch (IOException e) {\n throw new IllegalStateException(\"Write OAuthResponse error\", e);\n }\n }\n\n\n /**\n * Retrieve client ip address\n *\n * @param request HttpServletRequest\n * @return IP\n */\n public static String retrieveClientIp(HttpServletRequest request) {\n String ip = request.getHeader(\"x-forwarded-for\");\n if (isUnAvailableIp(ip)) {\n ip = request.getHeader(\"Proxy-Client-IP\");\n }\n if (isUnAvailableIp(ip)) {\n ip = request.getHeader(\"WL-Proxy-Client-IP\");\n }\n if (isUnAvailableIp(ip)) {\n ip = request.getRemoteAddr();\n }\n return ip;\n }\n\n private static boolean isUnAvailableIp(String ip) {\n return (StringUtils.isEmpty(ip) || \"unknown\".equalsIgnoreCase(ip));\n }\n}", "public class OAuthAuthxRequest extends OAuthAuthzRequest {\n\n\n public OAuthAuthxRequest(HttpServletRequest request) throws OAuthSystemException, OAuthProblemException {\n super(request);\n }\n\n\n /*\n * 判断响应的类型是否为CODE\n * */\n public boolean isCode() {\n return ResponseType.CODE.name().equalsIgnoreCase(this.getResponseType());\n }\n\n /*\n * 判断响应的类型是否为TOKEN\n * */\n public boolean isToken() {\n return ResponseType.TOKEN.name().equalsIgnoreCase(this.getResponseType());\n }\n\n /*\n * 获取 request 对象\n * */\n public HttpServletRequest request() {\n return this.request;\n }\n}", "public abstract class AbstractClientDetailsValidator {\n\n private static final Logger LOG = LoggerFactory.getLogger(AbstractClientDetailsValidator.class);\n\n\n protected OauthService oauthService = BeanProvider.getBean(OauthService.class);\n\n protected OAuthRequest oauthRequest;\n\n private ClientDetails clientDetails;\n\n protected AbstractClientDetailsValidator(OAuthRequest oauthRequest) {\n this.oauthRequest = oauthRequest;\n }\n\n\n protected ClientDetails clientDetails() {\n if (clientDetails == null) {\n clientDetails = oauthService.loadClientDetails(oauthRequest.getClientId());\n }\n return clientDetails;\n }\n\n\n protected OAuthResponse invalidClientErrorResponse() throws OAuthSystemException {\n return OAuthResponse.errorResponse(HttpServletResponse.SC_UNAUTHORIZED)\n .setError(OAuthError.TokenResponse.INVALID_CLIENT)\n .setErrorDescription(\"Invalid client_id '\" + oauthRequest.getClientId() + \"'\")\n .buildJSONMessage();\n }\n\n protected OAuthResponse invalidRedirectUriResponse() throws OAuthSystemException {\n return OAuthResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)\n .setError(OAuthError.CodeResponse.INVALID_REQUEST)\n .setErrorDescription(\"Invalid redirect_uri '\" + oauthRequest.getRedirectURI() + \"'\")\n .buildJSONMessage();\n }\n\n protected OAuthResponse invalidScopeResponse() throws OAuthSystemException {\n return OAuthResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)\n .setError(OAuthError.CodeResponse.INVALID_SCOPE)\n .setErrorDescription(\"Invalid scope '\" + oauthRequest.getScopes() + \"'\")\n .buildJSONMessage();\n }\n\n\n public final OAuthResponse validate() throws OAuthSystemException {\n final ClientDetails details = clientDetails();\n if (details == null) {\n return invalidClientErrorResponse();\n }\n\n return validateSelf(details);\n }\n\n\n protected boolean excludeScopes(Set<String> scopes, ClientDetails clientDetails) {\n final String clientDetailsScope = clientDetails.scope(); //read write\n for (String scope : scopes) {\n if (!clientDetailsScope.contains(scope)) {\n LOG.debug(\"Invalid scope - ClientDetails scopes '{}' exclude '{}'\", clientDetailsScope, scope);\n return true;\n }\n }\n return false;\n }\n\n\n protected OAuthResponse invalidClientSecretResponse() throws OAuthSystemException {\n return OAuthResponse.errorResponse(HttpServletResponse.SC_UNAUTHORIZED)\n .setError(OAuthError.TokenResponse.UNAUTHORIZED_CLIENT)\n .setErrorDescription(\"Invalid client_secret by client_id '\" + oauthRequest.getClientId() + \"'\")\n .buildJSONMessage();\n }\n\n\n protected abstract OAuthResponse validateSelf(ClientDetails clientDetails) throws OAuthSystemException;\n}", "public class CodeClientDetailsValidator extends AbstractClientDetailsValidator {\n\n private static final Logger LOG = LoggerFactory.getLogger(CodeClientDetailsValidator.class);\n\n public CodeClientDetailsValidator(OAuthAuthzRequest oauthRequest) {\n super(oauthRequest);\n }\n\n /*\n * grant_type=\"authorization_code\"\n * ?response_type=code&scope=read,write&client_id=[client_id]&redirect_uri=[redirect_uri]&state=[state]\n * */\n @Override\n public OAuthResponse validateSelf(ClientDetails clientDetails) throws OAuthSystemException {\n //validate redirect_uri\n final String redirectURI = oauthRequest.getRedirectURI();\n if (redirectURI == null || !redirectURI.equals(clientDetails.getRedirectUri())) {\n LOG.debug(\"Invalid redirect_uri '{}' by response_type = 'code', client_id = '{}'\", redirectURI, clientDetails.getClientId());\n return invalidRedirectUriResponse();\n }\n\n //validate scope\n final Set<String> scopes = oauthRequest.getScopes();\n if (scopes.isEmpty() || excludeScopes(scopes, clientDetails)) {\n return invalidScopeResponse();\n }\n\n //validate state\n final String state = getState();\n if (StringUtils.isEmpty(state)) {\n LOG.debug(\"Invalid 'state', it is required, but it is empty\");\n return invalidStateResponse();\n }\n\n return null;\n }\n\n private String getState() {\n return ((OAuthAuthzRequest) oauthRequest).getState();\n }\n\n private OAuthResponse invalidStateResponse() throws OAuthSystemException {\n return OAuthResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)\n .setError(OAuthError.CodeResponse.INVALID_REQUEST)\n .setErrorDescription(\"Parameter 'state' is required\")\n .buildJSONMessage();\n }\n\n\n}" ]
import com.monkeyk.os.domain.oauth.ClientDetails; import com.monkeyk.os.web.WebUtils; import com.monkeyk.os.oauth.OAuthAuthxRequest; import com.monkeyk.os.oauth.validator.AbstractClientDetailsValidator; import com.monkeyk.os.oauth.validator.CodeClientDetailsValidator; import org.apache.oltu.oauth2.as.response.OAuthASResponse; import org.apache.oltu.oauth2.common.exception.OAuthSystemException; import org.apache.oltu.oauth2.common.message.OAuthResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletResponse; import java.io.IOException;
package com.monkeyk.os.oauth.authorize; /** * 2015/6/25 * <p/> * Handle response_type = 'code' * * @author Shengzhao Li */ public class CodeAuthorizeHandler extends AbstractAuthorizeHandler { private static final Logger LOG = LoggerFactory.getLogger(CodeAuthorizeHandler.class); public CodeAuthorizeHandler(OAuthAuthxRequest oauthRequest, HttpServletResponse response) { super(oauthRequest, response); } @Override protected AbstractClientDetailsValidator getValidator() {
return new CodeClientDetailsValidator(oauthRequest);
4
SolraBizna/jarm
src/name/bizna/jarmtest/TestDirectory.java
[ "public class AlignmentException extends Exception {\n\tstatic final long serialVersionUID = 1;\n}", "public final class BusErrorException extends Exception {\n\n\tprivate static final long serialVersionUID = 1;\n\n\tprivate final String reason;\n\tprivate final long address;\n\tprivate final AccessType accessType;\n\n\tpublic BusErrorException(String reason, long address, AccessType accessType) {\n\t\tsuper(String.format(\"Failed to %s 0x%8x (%s)\", accessType.name(), address, reason));\n\n\t\tthis.reason = reason;\n\t\tthis.address = address;\n\t\tthis.accessType = accessType;\n\t}\n\n\tpublic String getReason() {\n\t\treturn reason;\n\t}\n\n\tpublic long getAddress() {\n\t\treturn address;\n\t}\n\n\tpublic AccessType getAccessType() {\n\t\treturn accessType;\n\t}\n\n\tpublic static enum AccessType {\n\t\tREAD, WRITE, UNKNOWN;\n\t}\n}", "public final class ByteArrayRegion extends ByteBackedRegion {\n\n\tprotected boolean allowWrites;\n\tprotected boolean dirty;\n\tprotected byte[] backing;\n\n\t/* Because of JVM limitations, size cannot be larger than 1GB. */\n\tpublic ByteArrayRegion(long size, int accessLatency, boolean wide) {\n\t\tsuper(accessLatency, wide);\n\t\tassert (size <= (1 * 1024 * 1024 * 1024));\n\t\tthis.allowWrites = true;\n\t\tthis.backing = new byte[(int) size];\n\t}\n\n\tpublic ByteArrayRegion(long size, int accessLatency) {\n\t\tthis(size, accessLatency, true);\n\t}\n\n\tpublic ByteArrayRegion(long size) {\n\t\tthis(size, 1, true);\n\t}\n\n\tpublic ByteArrayRegion(byte[] backing, boolean allowWrites, int accessLatency, boolean wide) {\n\t\tsuper(accessLatency, wide);\n\t\tthis.allowWrites = allowWrites;\n\t\tthis.backing = backing;\n\t}\n\n\tpublic ByteArrayRegion(byte[] backing, boolean allowWrites, int accessLatency) {\n\t\tthis(backing, allowWrites, accessLatency, true);\n\t}\n\n\tpublic ByteArrayRegion(byte[] backing, boolean allowWrites) {\n\t\tthis(backing, allowWrites, 1, true);\n\t}\n\n\tpublic ByteArrayRegion(byte[] backing) {\n\t\tthis(backing, true, 1, true);\n\t}\n\n\tpublic boolean isDirty() {\n\t\treturn dirty;\n\t}\n\n\tpublic void setDirty(boolean dirty) {\n\t\tthis.dirty = dirty;\n\t}\n\n\t@Override\n\tpublic long getRegionSize() {\n\t\treturn backing.length;\n\t}\n\n\t@Override\n\tpublic byte backingReadByte(int address) throws BusErrorException {\n\t\treturn backing[address];\n\t}\n\n\t@Override\n\tpublic void backingWriteByte(int address, byte b) throws BusErrorException {\n\t\tif (allowWrites) {\n\t\t\tdirty = true;\n\t\t\tbacking[address] = b;\n\t\t} else {\n\t\t\tthrow new BusErrorException(\"ByteArrayRegion is readonly\", address, BusErrorException.AccessType.WRITE);\n\t\t}\n\t}\n\n\tpublic byte[] getBackingArray() {\n\t\treturn backing;\n\t}\n\n}", "public final class CPU {\n\t/*** CONSTANTS ***/\n\t/* processor modes; HYP is PL2, USER is PL0, all others are PL1 (B1-1139) */\n\tpublic static enum ProcessorMode {\n\t\tUSER(16, 0, 0, false, true),\n\t\tSYSTEM(31, 0, 0, true, true),\n\t\tHYP(26, 1, 0, true, false), /* need Virtualization Extensions */\n\t\tFIQ(17, 2, 1, true, true),\n\t\tIRQ(18, 3, 2, true, true),\n\t\tSUPERVISOR(19, 4, 3, true, true),\n\t\tMONITOR(22, 5, 4, true, false), /* need Security Extensions */\n\t\tABORT(23, 6, 5, true, true),\n\t\tUNDEFINED(27, 7, 6, true, true);\n\t\tprivate static final HashMap<Integer, ProcessorMode> modeMap = new HashMap<Integer, ProcessorMode>();\n\t\tpublic final int modeRepresentation;\n\t\tpublic final int spIndex, spsrIndex, lrIndex;\n\t\tpublic final boolean privileged, supported;\n\t\tProcessorMode(int modeRepresentation, int spIndex, int lrIndex, boolean privileged, boolean supported) {\n\t\t\tthis.modeRepresentation = modeRepresentation;\n\t\t\tthis.spIndex = spIndex;\n\t\t\tthis.spsrIndex = spIndex-1;\n\t\t\tthis.lrIndex = lrIndex;\n\t\t\tthis.privileged = privileged;\n\t\t\tthis.supported = supported;\n\t\t}\n\t\tprivate static final ProcessorMode getModeFromRepresentation(int rep) {\n\t\t\treturn modeMap.get(Integer.valueOf(rep));\n\t\t}\n\t\tstatic {\n\t\t\tfor(ProcessorMode mode : ProcessorMode.values()) {\n\t\t\t\tmodeMap.put(Integer.valueOf(mode.modeRepresentation), mode);\n\t\t\t}\n\t\t}\n\t}\n\tprivate static final int EXCEPTION_VECTOR_RESET = 0;\n\tprivate static final int EXCEPTION_VECTOR_UNDEFINED = 1;\n\tprivate static final int EXCEPTION_VECTOR_SUPERVISOR_CALL = 2;\n\tprivate static final int EXCEPTION_VECTOR_PREFETCH_ABORT = 3;\n\tprivate static final int EXCEPTION_VECTOR_DATA_ABORT = 4;\n\t/* vector #5 only used when Virtualization Extensions are present */\n\tprivate static final int EXCEPTION_VECTOR_IRQ = 6;\n\tprivate static final int EXCEPTION_VECTOR_FIQ = 7;\n\t/* APSR/CPSR bits (B1-1148) */\n\tprivate static final int CPSR_BIT_N = 31;\n\tprivate static final int CPSR_BIT_Z = 30;\n\tprivate static final int CPSR_BIT_C = 29;\n\tprivate static final int CPSR_BIT_V = 28;\n\tprivate static final int CPSR_MASK_CLEAR_CONDITIONS = ~0 >>> 4;\n\tprivate static final int CPSR_BIT_Q = 27;\n\tprivate static final int CPSR_SHIFT_ITLO = 25;\n\tprivate static final int CPSR_MASK_ITLO = 3;\n\tprivate static final int CPSR_SHIFT_ITHI = 10;\n\tprivate static final int CPSR_MASK_ITHI = 63;\n\tprivate static final int CPSR_POSTSHIFT_ITHI = 2;\n\tprivate static final int CPSR_BIT_J = 24;\n\tprivate static final int CPSR_SHIFT_GE = 16;\n\tprivate static final int CPSR_MASK_GE = 15;\n\tprivate static final int CPSR_BIT_E = 9;\n\tprivate static final int CPSR_BIT_A = 8;\n\tprivate static final int CPSR_BIT_I = 7;\n\tprivate static final int CPSR_BIT_F = 6;\n\tprivate static final int CPSR_BIT_T = 5;\n\tprivate static final int CPSR_MASK_M = 0x1F;\n\tprivate static final int APSR_READ_MASK = 0xF80F0100;\n\tprivate static final int APSR_WRITE_MASK = 0xF80F0000;\n\tprivate static final int CPSR_USER_READ_MASK = 0xF8FFF3DF;\n\tprivate static final int CPSR_READ_MASK = 0xFFFFFFFF;\n\t/* the ARM ARM ARM says we should be able to write the E bit this way but also deprecates it\n\t * we'll let them write it because it costs us nothing\n\t * also! don't write the mode here, we'll handle that specially in code that writes CPSR */\n\tprivate static final int CPSR_WRITE_MASK = 0xF80F03C0;\n\t/* exception returns always restore the whole CPSR */\n\tprivate static final int SPSR_READ_MASK = 0xFFFFFFFF;\n\t/* as above, don't write the mode here, we'll handle that specially in code */\n\tprivate static final int SPSR_WRITE_MASK = 0xFF0FFFEF;\n\t/*** REGISTERS ***/\n\tprivate int gpr[] = new int[13];\n\tprivate int gprFIQ[] = new int[5];\n\tprivate int sp[] = new int[8];\n\tprivate int lr[] = new int[7];\n\tprivate int cur_sp, cur_lr;\n\tprivate int pc;\n\t\n\tprivate final Debugger debugger;\n\t\n\tpublic int readGPR(int r) {\n\t\tif(mode == ProcessorMode.FIQ && r >= 8) return gprFIQ[r-8];\n\t\telse return gpr[r];\n\t}\n\tpublic void writeGPR(int r, int new_value) {\n\t\tif(mode == ProcessorMode.FIQ && r >= 8) gprFIQ[r-8] = new_value;\n\t\telse gpr[r] = new_value;\n\t}\n\tpublic int readSP() { return sp[mode.spIndex]; }\n\tpublic void writeSP(int new_value) { sp[mode.spIndex] = new_value; }\n\tpublic int readLR() { return lr[mode.lrIndex]; }\n\tpublic void writeLR(int new_value) { lr[mode.lrIndex] = new_value; }\n\tpublic int readPC() { return isThumb() ? pc + 2 : pc + 4; }\n\tpublic int readCurrentPC() { return pc; }\n\tpublic void interworkingBranch(int new_pc) {\n\t\tif((new_pc & 1) != 0) {\n\t\t\t/* THUMB jump */\n\t\t\tcpsr |= 1<<CPSR_BIT_T;\n\t\t\tpc = new_pc & ~1;\n\t\t}\n\t\telse {\n\t\t\t/* ARM jump */\n\t\t\tcpsr &= ~(1<<CPSR_BIT_T);\n\t\t\tpc = new_pc & ~3;\n\t\t}\n\t}\n\tpublic void branch(int new_pc) {\n\t\tif(isThumb()) pc = new_pc & ~1;\n\t\telse pc = new_pc & ~3;\n\t}\n\tpublic void loadPC(int new_pc) {\n\t\tinterworkingBranch(new_pc);\n\t}\n\tpublic void writePC(int new_pc) {\n\t\tif(isThumb()) pc = new_pc & ~1;\n\t\telse interworkingBranch(new_pc);\n\t}\n\tpublic int readRegister(int r) {\n\t\tswitch(r) {\n\t\tcase 13: return readSP();\n\t\tcase 14: return readLR();\n\t\tcase 15: return readPC();\n\t\tdefault: return readGPR(r);\n\t\t}\n\t}\n\tpublic int readRegisterAlignPC(int r) {\n\t\tswitch(r) {\n\t\tcase 13: return readSP();\n\t\tcase 14: return readLR();\n\t\tcase 15: return readPC()&~3;\n\t\tdefault: return readGPR(r);\n\t\t}\n\t}\n\tpublic void writeRegister(int r, int new_value) {\n\t\tswitch(r) {\n\t\tcase 13: writeSP(new_value); break;\n\t\tcase 14: writeLR(new_value); break;\n\t\tcase 15: writePC(new_value); break;\n\t\tdefault: writeGPR(r, new_value); break;\n\t\t}\n\t}\n\t/*** CPSR/APSR ***/\n\tprivate int cpsr;\n\tprivate int spsr[] = new int[7];\n\tprivate ProcessorMode mode;\n\tpublic ProcessorMode getProcessorMode() { return mode; }\n\t/* does not sanity-check the operation! */\n\tprivate void setProcessorMode(ProcessorMode newMode) {\n\t\tcpsr = (cpsr & ~CPSR_MASK_M) | newMode.modeRepresentation;\n\t\tcur_sp = newMode.spIndex;\n\t\tcur_lr = newMode.lrIndex;\n\t\tmode = newMode;\n\t}\n\tprivate void setProcessorMode(int newModeRep) throws UndefinedException {\n\t\tProcessorMode newMode = ProcessorMode.getModeFromRepresentation(newModeRep);\n\t\tif(newMode == null) throw new UndefinedException();\n\t\tsetProcessorMode(newMode);\n\t}\n\tprivate void enterProcessorModeByException(ProcessorMode newMode) {\n\t\tif(newMode.spsrIndex >= 0)\n\t\t\tspsr[newMode.spsrIndex] = cpsr;\n\t\tsetProcessorMode(newMode);\n\t}\n\tprivate void returnFromProcessorMode() {\n\t\tif(mode.spsrIndex >= 0) {\n\t\t\tProcessorMode newMode = ProcessorMode.getModeFromRepresentation(spsr[mode.spsrIndex] & CPSR_MASK_M);\n\t\t\tassert(newMode != null);\n\t\t\tcpsr = spsr[mode.spsrIndex];\n\t\t\tcur_sp = newMode.spIndex;\n\t\t\tcur_lr = newMode.lrIndex;\n\t\t\tmode = newMode;\n\t\t}\n\t}\n\tpublic boolean conditionN() { return (cpsr & (1<<CPSR_BIT_N)) != 0; }\n\tpublic boolean conditionZ() { return (cpsr & (1<<CPSR_BIT_Z)) != 0; }\n\tpublic boolean conditionC() { return (cpsr & (1<<CPSR_BIT_C)) != 0; }\n\tpublic boolean conditionV() { return (cpsr & (1<<CPSR_BIT_V)) != 0; }\n\tpublic boolean conditionQ() { return (cpsr & (1<<CPSR_BIT_Q)) != 0; }\n\tpublic void setConditionN(boolean nu) { if(nu) cpsr |= (1<<CPSR_BIT_N); else cpsr &= ~(1<<CPSR_BIT_N); }\n\tpublic void setConditionZ(boolean nu) { if(nu) cpsr |= (1<<CPSR_BIT_Z); else cpsr &= ~(1<<CPSR_BIT_Z); }\n\tpublic void setConditionC(boolean nu) { if(nu) cpsr |= (1<<CPSR_BIT_C); else cpsr &= ~(1<<CPSR_BIT_C); }\n\tpublic void setConditionV(boolean nu) { if(nu) cpsr |= (1<<CPSR_BIT_V); else cpsr &= ~(1<<CPSR_BIT_V); }\n\tpublic void setConditionQ(boolean nu) { if(nu) cpsr |= (1<<CPSR_BIT_Q); else cpsr &= ~(1<<CPSR_BIT_Q); }\n\tpublic void setConditions(int cc) { cpsr = (cpsr & 0x0FFFFFFF) | (cc<<28); }\n\tpublic boolean isThumb() { return (cpsr & (1<<CPSR_BIT_T)) != 0; }\n\tpublic boolean isARM() { return (cpsr & (1<<CPSR_BIT_T)) == 0; }\n\tpublic boolean isLittleEndian() { return (cpsr & (1<<CPSR_BIT_E)) == 0; }\n\tpublic boolean isBigEndian() { return (cpsr & (1<<CPSR_BIT_E)) != 0; }\n\tpublic boolean isPrivileged() { return mode.privileged; }\n\tpublic boolean usingStrictAlignment() { return (cpsr & (1<<CPSR_BIT_A)) != 0; }\n\tpublic boolean areIRQsEnabled() { return (cpsr & (1<<CPSR_BIT_I)) != 0; }\n\tpublic boolean areFIQsEnabled() { return (cpsr & (1<<CPSR_BIT_F)) != 0; }\n\tpublic int getMode() { return cpsr & 31; }\n\tpublic void writeCPSR(int value) { cpsr = value; }\n\tpublic int readCPSR() { return cpsr; }\n\tprivate void instrWriteCurCPSR(int value, int mask, boolean isExceptionReturn) throws UndefinedException {\n\t\t/* (B1-1153) */\n\t\tint writeMask = 0;\n\t\tif((mask & 8) != 0) {\n\t\t\t/* N,Z,C,V,Q, and also IT<1:0>/J if exception return */\n\t\t\tif(isExceptionReturn) writeMask |= 0xFF;\n\t\t\telse writeMask |= 0xF8;\n\t\t}\n\t\tif((mask & 4) != 0) {\n\t\t\t/* GE<3:0> */\n\t\t\twriteMask |= 0x000F0000;\n\t\t}\n\t\tif((mask & 2) != 0) {\n\t\t\t/* E bit, also A mask if privileged, and IT<7:2> if exception return */\n\t\t\tif(isExceptionReturn) writeMask |= 0x0000FF00;\n\t\t\telse writeMask |= 0x00000300;\n\t\t}\n\t\tif((mask & 1) != 0) {\n\t\t\t/* I bit, F bit (unless NMFI), M bits, and also T if exception return */\n\t\t\tif(isExceptionReturn) writeMask |= 0x000000BF;\n\t\t\telse writeMask |= 0x0000009F;\n\t\t\tif((cp15.SCTLR&(1<<CP15.SCTLR_BIT_NMFI)) == 0) writeMask |= 0x00000040;\n\t\t}\n\t\tif(!isPrivileged()) writeMask &= APSR_WRITE_MASK;\n\t\t// System.out.printf(\"Value: %08X, mask:%1X = %08X\\n\", value, mask, writeMask);\n\t\tcpsr = (cpsr & ~writeMask) | (value & writeMask);\n\t\tif((writeMask & 31) == 31) setProcessorMode(value & 31);\n\t}\n\tprivate void instrWriteCurSPSR(int value, int mask) throws UndefinedException {\n\t\t/* (B1-1154) */\n\t\tif(mode.spsrIndex < 0) throw new UndefinedException();\n\t\tint writeMask = 0;\n\t\tif((mask & 8) != 0) {\n\t\t\t/* N,Z,C,V,Q, IT<1:0>,J */\n\t\t\twriteMask |= 0xFF;\n\t\t}\n\t\tif((mask & 4) != 0) {\n\t\t\t/* GE<3:0> */\n\t\t\twriteMask |= 0x000F0000;\n\t\t}\n\t\tif((mask & 2) != 0) {\n\t\t\t/* E,A,IT<7:2> */\n\t\t\twriteMask |= 0x0000FF00;\n\t\t}\n\t\tif((mask & 1) != 0) {\n\t\t\t/* I,F,T,M */\n\t\t\twriteMask |= 0x000000FF;\n\t\t}\n\t\tspsr[mode.spsrIndex] = (spsr[mode.spsrIndex] & ~writeMask) | (value & writeMask);\n\t}\n\t/*** MEMORY MODEL ***/\n\tprivate final PhysicalMemorySpace mem = new PhysicalMemorySpace();\n\tpublic PhysicalMemorySpace getMemorySpace() { return mem; }\n\tprivate final VirtualMemorySpace vm;\n\tpublic VirtualMemorySpace getVirtualMemorySpace() { return vm; }\n\tpublic int instructionReadWord(int address, boolean privileged) throws BusErrorException, AlignmentException, EscapeRetryException, EscapeCompleteException {\n\t\treturn vm.readInt(address, inStrictAlignMode(), isBigEndian());\n\t}\n\tpublic void instructionWriteWord(int address, int value, boolean privileged) throws BusErrorException, AlignmentException, EscapeRetryException, EscapeCompleteException {\n\t\tvm.writeInt(address,value, inStrictAlignMode(), isBigEndian());\n\t}\n\tpublic byte instructionReadByte(int address, boolean privileged) throws BusErrorException, AlignmentException, EscapeRetryException, EscapeCompleteException {\n\t\treturn vm.readByte(address);\n\t}\n\tpublic void instructionWriteByte(int address, byte value, boolean privileged) throws BusErrorException, AlignmentException, EscapeRetryException, EscapeCompleteException {\n\t\tvm.writeByte(address, value);\n\t}\n\tpublic short instructionReadHalfword(int address, boolean privileged) throws BusErrorException, AlignmentException, EscapeRetryException, EscapeCompleteException {\n\t\treturn vm.readShort(address, inStrictAlignMode(), isBigEndian());\n\t}\n\tpublic void instructionWriteHalfword(int address, short value, boolean privileged) throws BusErrorException, AlignmentException, EscapeRetryException, EscapeCompleteException {\n\t\tvm.writeShort(address, value, inStrictAlignMode(), isBigEndian());\n\t}\n\tpublic int instructionReadWord(int address) throws BusErrorException, AlignmentException, EscapeRetryException, EscapeCompleteException {\n\t\treturn instructionReadWord(address, isPrivileged());\n\t}\n\tpublic void instructionWriteWord(int address, int value) throws BusErrorException, AlignmentException, EscapeRetryException, EscapeCompleteException {\n\t\tinstructionWriteWord(address, value, isPrivileged());\n\t}\n\tpublic byte instructionReadByte(int address) throws BusErrorException, AlignmentException, EscapeRetryException, EscapeCompleteException {\n\t\treturn instructionReadByte(address, isPrivileged());\n\t}\n\tpublic void instructionWriteByte(int address, byte value) throws BusErrorException, AlignmentException, EscapeRetryException, EscapeCompleteException {\n\t\tinstructionWriteByte(address, value, isPrivileged());\n\t}\n\tpublic short instructionReadHalfword(int address) throws BusErrorException, AlignmentException, EscapeRetryException, EscapeCompleteException {\n\t\treturn instructionReadHalfword(address);\n\t}\n\tpublic void instructionWriteHalfword(int address, short value) throws BusErrorException, AlignmentException, EscapeRetryException, EscapeCompleteException {\n\t\tinstructionWriteHalfword(address, value, isPrivileged());\n\t}\n\t/*** COPROCESSORS ***/\n\tprivate Coprocessor[] coprocessors = new Coprocessor[16];\n\tpublic void mapCoprocessor(int name, Coprocessor cop) {\n\t\tif(name >= 16 || name < 0) throw new ArrayIndexOutOfBoundsException(name);\n\t\tif(name >= 8) throw new ReservedCoprocessorNameException();\n\t\tcoprocessors[name] = cop;\n\t}\n\t/*** INTERRUPT VECTORS ***/\n\tpublic int getInterruptVector(int interrupt) {\n\t\t/* B1-1165 */\n\t\t/* TODO: SCTLR.V */\n\t\tif((cp15.SCTLR & (1<<CP15.SCTLR_BIT_V)) != 0) return (interrupt * 4) | 0xFFFF0000;\n\t\telse return interrupt * 4;\n\t}\n\t/*** SYSTEM CONTROL REGISTERS ***/\n\t/* debug (C6), ThumbEE (A2-95), Jazelle (A2-97) */\n\tprivate static class CP14 extends Coprocessor {\n\t\tCP14(CPU cpu) {}\n\t\t@Override\n\t\tpublic void executeInstruction(boolean unconditional, int iword) throws UndefinedException { throw new UndefinedException(); }\n\t\t@Override\n\t\tpublic void reset() {}\n\t}\n\tCP14 cp14;\n\tCP15 cp15;\n\tpublic boolean inStrictAlignMode() { return (cp15.SCTLR & (1<<CP15.SCTLR_BIT_A)) != 0; }\n\t/*** INITIALIZATION ***/\n\tpublic CPU() { this(null); }\n\tpublic CPU(Debugger debugger) {\n\t\tthis.debugger = debugger;\n\t\tvm = new VirtualMemorySpace(mem, debugger);\n\t\t\n\t\tcoprocessors[10] = new FPU(this);\n\t\tcoprocessors[11] = coprocessors[10];\n\t\tcoprocessors[14] = cp14 = new CP14(this);\n\t\tcoprocessors[15] = cp15 = new CP15(this);\n\t}\n\t/*** EXECUTION ***/\n\tprivate boolean haveReset = false;\n\tprivate int cycleBudget = 0;\n\t/**\n\t * Returns true if the cycle budget is fully spent, false if there are some unspent cycles left.\n\t */\n\tpublic boolean budgetFullySpent() { return cycleBudget <= 0; }\n\t/**\n\t * Spends any cycles that still remain in the budget.\n\t * @param soft If true, only zero the budget if there are unspent cycles. If false, also forgive debt.\n\t */\n\tpublic void zeroBudget(boolean soft) {\n\t\tif(cycleBudget > 0 || !soft) cycleBudget = 0;\n\t}\n\t/**\n\t * Fetch and execute enough instructions to meet a given cycle budget. Will go slightly over budget, and compensate exactly for this on the next call.\n\t * Throws an exception if exception debug mode is true.\n\t * @param budget Number of cycles\n\t * @return true if the budget was fully expended\n\t */\n\tpublic boolean execute(int budget) throws BusErrorException, AlignmentException, UndefinedException {\n\t\t// TODO: Define new, user-facing exceptions subclassing RuntimeException.\n\t\t// Hack: allow self-tail-call without bursting the whole stack\n\t\twhile(true) {\n\t\t\tcycleBudget += budget;\n\t\t\tint backupPC = pc;\n\t\t\tif(waitingForInterrupt && (haveIRQ() || haveFIQ())) waitingForInterrupt = false;\n\t\t\ttry {\n\t\t\t\twhile(cycleBudget > 0 && !waitingForInterrupt) {\n\t\t\t\t\tbackupPC = pc;\n\t\t\t\t\texecute();\n\t\t\t\t\t/* then settle and check the debt */\n\t\t\t\t\tcycleBudget -= mem.settleAccessBill();\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch(BusErrorException e) {\n\t\t\t\tif(exceptionDebugMode) throw e;\n\t\t\t\tgenerateDataAbortException();\n\t\t\t\tbudget = 0;\n\t\t\t\tcycleBudget -= mem.settleAccessBill();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcatch(AlignmentException e) {\n\t\t\t\tif(exceptionDebugMode) throw e;\n\t\t\t\tgenerateDataAbortException();\n\t\t\t\tbudget = 0;\n\t\t\t\tcycleBudget -= mem.settleAccessBill();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcatch(UndefinedException e) {\n\t\t\t\tif(exceptionDebugMode) throw e;\n\t\t\t\tgenerateUndefinedException();\n\t\t\t\tbudget = 0;\n\t\t\t\tcycleBudget -= mem.settleAccessBill();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcatch(EscapeRetryException e) {\n\t\t\t\tpc = backupPC;\n\t\t\t}\n\t\t\tcatch(EscapeCompleteException e) {}\n\t\t\t// don't hoard cycles in a low-power state\n\t\t\tcycleBudget -= mem.settleAccessBill();\n\t\t\tif(waitingForInterrupt && cycleBudget > 0) cycleBudget = 0;\n\t\t\treturn cycleBudget <= 0;\n\t\t}\n\t}\n\t/**\n\t * Fetch and execute a single instruction\n\t */\n\tpublic void execute() throws BusErrorException, AlignmentException, UndefinedException, EscapeRetryException, EscapeCompleteException {\n\t\tif(!haveReset) throw new FatalException(\"execute() called without first calling reset()\");\n\t\tif((cpsr & CPSR_BIT_F) == 0 && haveFIQ()) generateFIQException();\n\t\tif((cpsr & CPSR_BIT_I) == 0 && haveIRQ()) generateIRQException();\n\t\t\n\t\tif(debugger!=null) debugger.onInstruction(this, pc);\n\t\t\n\t\tif(isThumb()) throw new UndefinedException(); // Thumb not implemented\n\t\telse executeARM();\n\t}\n\t/* Fetch and execute a 32-bit ARM instruction */\n\tprivate void executeARM() throws BusErrorException, AlignmentException, UndefinedException, EscapeRetryException, EscapeCompleteException {\n\t\tint iword;\n\t\tif((pc&3) != 0) pc=pc&~3;\n\t\ttry { iword = vm.readInt(pc, true, false); }\n\t\tcatch(BusErrorException e) {\n\t\t\t// TODO: ugh\n\t\t\tif(exceptionDebugMode) throw e;\n\t\t\t// System.out.println(\"Prefetch abort! \"+Long.toHexString((long)pc & 0xFFFFFFFFL));\n\t\t\tgeneratePrefetchAbortException();\n\t\t\ttry { iword = vm.readInt(pc, true, false); }\n\t\t\tcatch(BusErrorException e2) { throw new FatalException(\"Prefetch abort vector is on invalid address\"); }\n\t\t}\n\t\t// System.out.printf(\"\\t%08X : %08X\\n\", pc, iword);\n\t\tpc += 4;\n\t\ttry { executeARM(iword); }\n\t\t/* if we experience an exception, restore as much state as possible to before the exception */\n\t\tcatch(BusErrorException e) { pc -= 4; throw e; }\n\t\tcatch(AlignmentException e) { pc -= 4; throw e; }\n\t\tcatch(UndefinedException e) { pc -= 4; throw e; }\n\t}\n\t/* used by executeDataProcessingOperation for operations that don't provide their own carry logic */\n\tprivate boolean shifterCarryOut;\n\tprivate int expandARMImmediate(int imm12) {\n\t\tint unrotated = imm12 & 255;\n\t\treturn applyOpShift(unrotated, 3, 2*((imm12>>>8)&15));\n\t}\n\tprivate int applyOpShift(int value, int type, int amount) {\n\t\tif(amount == 0) {\n\t\t\tshifterCarryOut = conditionC();\n\t\t\treturn value;\n\t\t}\n\t\tswitch(type) {\n\t\tcase 0: /* logical left */\n\t\t\tif(amount >= 33) shifterCarryOut = false;\n\t\t\telse shifterCarryOut = ((value >>> (32-amount)) & 1) != 0;\n\t\t\tif(amount >= 32) return 0;\n\t\t\telse return value << amount;\n\t\tcase 1: /* logical right */\n\t\t\tif(amount >= 33) shifterCarryOut = false;\n\t\t\telse shifterCarryOut = ((value >>> amount-1) & 1) != 0;\n\t\t\tif(amount >= 32) return 0;\n\t\t\telse return value >>> amount;\n\t\tcase 2: /* arithmetic right */\n\t\t\tif(amount > 32) {\n\t\t\t\tif(value < 0) { shifterCarryOut = true; return 0xFFFFFFFF; }\n\t\t\t\telse { shifterCarryOut = false; return 0; }\n\t\t\t}\n\t\t\telse if(amount == 32) shifterCarryOut = value < 0;\n\t\t\telse shifterCarryOut = ((value >> (amount-1)) & 1) != 0;\n\t\t\treturn value >> amount;\n\t\tcase 3: /* rotate right */\n\t\t{\n\t\t\tamount %= 32;\n\t\t\tint result = (value >>> amount) | (value << (32-amount));\n\t\t\tshifterCarryOut = (result & 0x80000000) != 0;\n\t\t\treturn result;\n\t\t}\n\t\tdefault:\n\t\t\tthrow new InternalError(); /* we technically shouldn't throw these */\n\t\t}\n\t}\n\tprivate int applyOpRRX(int value) {\n\t\tshifterCarryOut = (value & 1) != 0;\n\t\tif(conditionC())\n\t\t\treturn (value >>> 1) | 0x80000000;\n\t\telse\n\t\t\treturn (value >>> 1);\n\t}\n\tprivate int applyIRShift(int src, int type, int imm5) {\n\t\t/* A8-291 */\n\t\tswitch(type) {\n\t\tcase 0: /* logical left */\n\t\t\t/* optimize this particular case in a way the compiler probably won't\n\t\t\t * the vast majority of instructions will use this case */\n\t\t\tif(imm5 == 0) { shifterCarryOut = false; return src; }\n\t\t\telse return applyOpShift(src, type, imm5);\n\t\tcase 1: /* logical right */\n\t\tcase 2: /* arithmetic right */\n\t\t\tif(imm5 == 0) return applyOpShift(src, type, 32);\n\t\t\telse return applyOpShift(src, type, imm5);\n\t\tcase 3:\n\t\t\tif(imm5 == 0) return applyOpRRX(src);\n\t\t\telse return applyOpShift(src, type, imm5);\n\t\tdefault:\n\t\t\tthrow new InternalError(); /* we technically shouldn't throw these */\n\t\t}\n\t}\n\tprivate int applyRRShift(int src, int type, int Rs) {\n\t\treturn applyOpShift(src, type, readRegister(Rs) & 255);\n\t}\n\tprivate void executeDataProcessingOperation(int opcode, int n, int m, int Rd) throws UndefinedException {\n\t\t/* TODO: possibly speed this up by separating WriteFlags version out */\n\t\t/* TODO: ensure that all the data processing operation variants are correct */\n\t\tboolean writeFlags = (opcode & 1) != 0;\n\t\tboolean Cout, Vout;\n\t\tint result;\n\t\tswitch(opcode) {\n\t\tcase 0: case 1:\n\t\t\t/* AND (immediate at A8-324) */\n\t\t\twriteRegister(Rd, result = (n&m));\n\t\t\tCout = shifterCarryOut;\n\t\t\tVout = conditionV();\n\t\t\tbreak;\n\t\tcase 2: case 3:\n\t\t\t/* EOR (immediate at A8-382) */\n\t\t\twriteRegister(Rd, result = (n^m));\n\t\t\tCout = shifterCarryOut;\n\t\t\tVout = conditionV();\n\t\t\tbreak;\n\t\tcase 17:\n\t\t\t/* TST (immediate at A8-744)\n\t\t\t * same as AND but discard result */\n\t\t\tresult = (n&m);\n\t\t\tCout = shifterCarryOut;\n\t\t\tVout = conditionV();\n\t\t\tbreak;\n\t\tcase 19:\n\t\t\t/* TEQ (immediate at A8-738)\n\t\t\t * same as EOR but discard result */\n\t\t\tresult = (n^m);\n\t\t\tCout = shifterCarryOut;\n\t\t\tVout = conditionV();\n\t\t\tbreak;\n\t\tcase 24: case 25:\n\t\t\t/* OR (immediate [ORR] at A8-516) */\n\t\t\twriteRegister(Rd, result = (n|m));\n\t\t\tCout = shifterCarryOut;\n\t\t\tVout = conditionV();\n\t\t\tbreak;\n\t\tcase 26: case 27:\n\t\t\t/* MOV (immediate at A8-484) */\n\t\t\twriteRegister(Rd, result = m);\n\t\t\tCout = shifterCarryOut;\n\t\t\tVout = conditionV();\n\t\t\tbreak;\n\t\tcase 28: case 29:\n\t\t\t/* BIC (immediate at A8-340) */\n\t\t\twriteRegister(Rd, result = (n&~m));\n\t\t\tCout = shifterCarryOut;\n\t\t\tVout = conditionV();\n\t\t\tbreak;\n\t\tcase 30: case 31:\n\t\t\t/* MVN (immediate at A8-504) */\n\t\t\twriteRegister(Rd, result = ~m);\n\t\t\tCout = shifterCarryOut;\n\t\t\tVout = conditionV();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\t/* any instruction that is an AddWithCarry at heart */\n\t\t{\n\t\t\tint x, y, carry_in;\n\t\t\tboolean writeOut;\n\t\t\tswitch(opcode) {\n\t\t\tcase 4: case 5:\n\t\t\t\t/* SUB (immediate at A8-710) */\n\t\t\t\tx = n; y = ~m; carry_in = 1; writeOut = true;\n\t\t\t\tbreak;\n\t\t\tcase 6: case 7:\n\t\t\t\t/* RSB (immediate at A8-574) */\n\t\t\t\tx = ~n; y = m; carry_in = 1; writeOut = true;\n\t\t\t\tbreak;\n\t\t\tcase 8: case 9:\n\t\t\t\t/* ADD (immediate at A8-308) */\n\t\t\t\tx = n; y = m; carry_in = 0; writeOut = true;\n\t\t\t\tbreak;\n\t\t\tcase 10: case 11:\n\t\t\t\t/* ADC (immediate at A8-300) */\n\t\t\t\tx = n; y = m; carry_in = conditionC() ? 1 : 0; writeOut = true;\n\t\t\t\tbreak;\n\t\t\tcase 12: case 13:\n\t\t\t\t/* SBC (immediate, A8-592) */\n\t\t\t\tx = n; y = ~m; carry_in = conditionC() ? 1 : 0; writeOut = true;\n\t\t\t\tbreak;\n\t\t\tcase 14: case 15:\n\t\t\t\t/* RSC (immediate, A8-580) */\n\t\t\t\tx = ~n; y = m; carry_in = conditionC() ? 1 : 0; writeOut = true;\n\t\t\t\tbreak;\n\t\t\tcase 21:\n\t\t\t\t/* CMP (immediate, A8-370) */\n\t\t\t\tx = n; y = ~m; carry_in = 1; writeOut = false;\n\t\t\t\tbreak;\n\t\t\tcase 23:\n\t\t\t\t/* CMN (immediate, A8-364) */\n\t\t\t\tx = n; y = m; carry_in = 0; writeOut = false;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow new RuntimeException(\"unknown op: \"+opcode);\n\t\t\t}\n\t\t\t/* this is the way the spec specified it\n\t\t\t * TODO: work out a more efficient way */\n\t\t\tlong signedResult = (long)x + y + carry_in;\n\t\t\tlong unsignedResult = (x&0xFFFFFFFFL) + (y&0xFFFFFFFFL) + carry_in;\n\t\t\tresult = (int)unsignedResult;\n\t\t\tCout = unsignedResult != (result&0xFFFFFFFFL);\n\t\t\tVout = signedResult != result;\n\t\t\tif(writeOut) writeRegister(Rd, result);\n\t\t}\n\t\t}\n\t\tif(writeFlags) {\n\t\t\tif(Rd == 15) {\n\t\t\t\t/* when the destination register is the PC, the flag-setting versions are for PL1 and above only */\n\t\t\t\tif(!isPrivileged()) throw new UndefinedException();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcpsr &= CPSR_MASK_CLEAR_CONDITIONS;\n\t\t\t\tif(result < 0) cpsr |= 1<<CPSR_BIT_N;\n\t\t\t\tif(result == 0) cpsr |= 1<<CPSR_BIT_Z;\n\t\t\t\tif(Cout) cpsr |= 1<<CPSR_BIT_C;\n\t\t\t\tif(Vout) cpsr |= 1<<CPSR_BIT_V;\n\t\t\t}\n\t\t}\n\t}\n\tprivate void executeARMPage0(int iword) throws BusErrorException, AlignmentException, UndefinedException, EscapeRetryException, EscapeCompleteException {\n\t\t/* (op=0) Data-processing and miscellaneous instructions (A5-196) */\n\t\t/* TODO: page 0 decoding is wrong */\n\t\tint op1 = (iword >> 20) & 31;\n\t\tint op2 = (iword >> 4) & 15;\n\t\tif((op1 & 25) != 16) {\n\t\t\tif((op2 & 1) == 0) {\n\t\t\t\t/* Data-processing (register, A5-197) */\n\t\t\t\tint Rn = (iword >> 16) & 15;\n\t\t\t\tint Rd = (iword >> 12) & 15;\n\t\t\t\tint imm5 = (iword >> 7) & 31;\n\t\t\t\tint type = (iword >> 5) & 3;\n\t\t\t\tint Rm = iword & 15;\n\t\t\t\tint n = readRegister(Rn);\n\t\t\t\tint m = applyIRShift(readRegister(Rm), type, imm5);\n\t\t\t\texecuteDataProcessingOperation(op1, n, m, Rd);\n\t\t\t\t/* TODO: if S is set and Rd == 15, copy SPSR to CPSR */\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse if((op2 & 8) == 0) {\n\t\t\t\t/* static_assert((op2 & 1) == 1) */\n\t\t\t\t/* Data-processing (register-shifted register, A5-198) */\n\t\t\t\tint Rn = (iword >> 16) & 15;\n\t\t\t\tint Rd = (iword >> 12) & 15;\n\t\t\t\tint Rs = (iword >> 8) & 15;\n\t\t\t\tint type = (iword >> 5) & 3;\n\t\t\t\tint Rm = iword & 15;\n\t\t\t\tint n = readRegister(Rn);\n\t\t\t\tint m = applyRRShift(readRegister(Rm), type, Rs);\n\t\t\t\texecuteDataProcessingOperation(op1, n, m, Rd);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif((op2 & 8) == 0) {\n\t\t\t\t/* Miscellaneous instructions (A5-207) */\n\t\t\t\tint op = (iword >> 21) & 3;\n\t\t\t\top1 = (iword >> 16) & 15;\n\t\t\t\t/* op2 is still good */\n\t\t\t\tswitch(op2) {\n\t\t\t\tcase 0:\n\t\t\t\t\tif((iword & 512) != 0) {\n\t\t\t\t\t\tif((op & 1) == 0) {\n\t\t\t\t\t\t\t/* MRS (banked register, B9-1992) */\n\t\t\t\t\t\t\t/* We don't have Virtualization extensions */\n\t\t\t\t\t\t\tthrow new UndefinedException();\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t/* MSR (banked register, B9-1994) */\n\t\t\t\t\t\t\t/* We don't have Virtualization extensions */\n\t\t\t\t\t\t\tthrow new UndefinedException();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tswitch(op) {\n\t\t\t\t\t\tcase 0: case 2: {\n\t\t\t\t\t\t\t/* MRS (A8-496, B9-1990) */\n\t\t\t\t\t\t\tboolean readSPSR = (op & 2) != 0;\n\t\t\t\t\t\t\tint Rd = (iword >> 12) & 15;\n\t\t\t\t\t\t\tif(readSPSR) {\n\t\t\t\t\t\t\t\tif(mode == ProcessorMode.USER || mode == ProcessorMode.SYSTEM)\n\t\t\t\t\t\t\t\t\tthrow new UndefinedException();\n\t\t\t\t\t\t\t\twriteRegister(Rd, spsr[mode.spsrIndex]);\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tint red = cpsr;\n\t\t\t\t\t\t\t\tif(mode == ProcessorMode.USER) red &= CPSR_USER_READ_MASK;\n\t\t\t\t\t\t\t\twriteRegister(Rd, red);\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase 1:\n\t\t\t\t\t\tcase 3:\n\t\t\t\t\t\t\t/* MSR (register, A8-500, B9-1998) */\n\t\t\t\t\t\t\tint mask = (iword >> 16) & 15;\n\t\t\t\t\t\t\tboolean writingSPSR = (op & 2) != 0;\n\t\t\t\t\t\t\tif(writingSPSR || ((mask & 3) == 1) || ((mask & 2) != 0))\n\t\t\t\t\t\t\t\tif(!isPrivileged()) throw new UndefinedException();\n\t\t\t\t\t\t\tint imm32 = expandARMImmediate(iword & 4095);\n\t\t\t\t\t\t\tif(writingSPSR)\n\t\t\t\t\t\t\t\tinstrWriteCurSPSR(imm32, mask);\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tinstrWriteCurCPSR(imm32, mask, false);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1:\n\t\t\t\t\tswitch(op) {\n\t\t\t\t\tcase 1:\n\t\t\t\t\t\t/* BX (A8-352) */\n\t\t\t\t\t{\n\t\t\t\t\t\tint Rm = (iword) & 15;\n\t\t\t\t\t\tinterworkingBranch(readRegister(Rm));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tcase 3:\n\t\t\t\t\t\t/* CLZ (A8-362) */\n\t\t\t\t\t\tint Rm = (iword) & 15;\n\t\t\t\t\t\tint Rd = (iword >> 12) & 15;\n\t\t\t\t\t\twriteRegister(Rd, Integer.numberOfLeadingZeros(readRegister(Rm)));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tswitch(op) {\n\t\t\t\t\tcase 1:\n\t\t\t\t\t\t/* BXJ (A8-354) */\n\t\t\t\t\t\tthrow new UnimplementedInstructionException(iword, \"BXJ\");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 3:\n\t\t\t\t\tswitch(op) {\n\t\t\t\t\tcase 1:\n\t\t\t\t\t\t/* BLX (A8-350) */\n\t\t\t\t\t\tint Rm = iword&15;\n\t\t\t\t\t\twriteLR(readPC()-4);\n\t\t\t\t\t\tinterworkingBranch(readRegister(Rm));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 5:\n\t\t\t\t\t/* Saturating addition and subtraction (A5-202) */\n\t\t\t\t\t/* QADD/QSUB/QDADD/QDSUB (A8-540 and change) */\n\t\t\t\t\tboolean subtract = (op & 1) != 0;\n\t\t\t\t\tboolean doubleTrouble = (op & 2) != 0;\n\t\t\t\t\tint Rm = iword&15;\n\t\t\t\t\tint Rn = (iword>>16)&15;\n\t\t\t\t\tint Rd = (iword>>12)&15;\n\t\t\t\t\tlong n = readRegister(Rn);\n\t\t\t\t\tif(doubleTrouble) n *= 2L; // why only n? WHO KNOWS\n\t\t\t\t\tlong m = readRegister(Rm);\n\t\t\t\t\tlong result;\n\t\t\t\t\tif(subtract) result = n - m;\n\t\t\t\t\telse result = n + m;\n\t\t\t\t\tif(result > 0x7FFFFFFFL) {\n\t\t\t\t\t\twriteRegister(Rd, 0x7FFFFFFF);\n\t\t\t\t\t\tcpsr |= 1<<CPSR_BIT_Q;\n\t\t\t\t\t}\n\t\t\t\t\telse if(result < -0x80000000L) {\n\t\t\t\t\t\twriteRegister(Rd, 0x80000000);\n\t\t\t\t\t\tcpsr |= 1<<CPSR_BIT_Q;\n\t\t\t\t\t}\n\t\t\t\t\telse writeRegister(Rd, (int)result);\n\t\t\t\t\treturn;\n\t\t\t\tcase 6:\n\t\t\t\t\tswitch(op) {\n\t\t\t\t\tcase 3:\n\t\t\t\t\t\t/* ERET (B9-1982) */\n\t\t\t\t\t\tthrow new UnimplementedInstructionException(iword, \"ERET\");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 7:\n\t\t\t\t\tswitch(op) {\n\t\t\t\t\tcase 1:\n\t\t\t\t\t\t/* BKPT (A8-346) */\n\t\t\t\t\t\t/* TODO: Invasive debugging mode */\n\t\t\t\t\t\treturn;\n\t\t\t\t\tcase 2:\n\t\t\t\t\t\t/* HVC (B9-1984) but we do NOT have Virtualization Extensions */\n\t\t\t\t\tcase 3:\n\t\t\t\t\t\t/* SMC (B9-2002) but we do NOT have Security Extensions */\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthrow new UndefinedException();\n\t\t\t}\n\t\t\telse if((op2 & 1) == 0) {\n\t\t\t\t/* static_assert((op2 & 8) == 8) */\n\t\t\t\t/* Halfword multiply and multiply accumulate (A5-203) */\n\t\t\t\tswitch(op1) {\n\t\t\t\tcase 16:\n\t\t\t\t\t/* SMLABB/SMLABT/SMLATB/SMLATT (A8-620) */\n\t\t\t\t\tthrow new UnimplementedInstructionException(iword, \"SMLABB/SMLABT/SMLATB/SMLATT\");\n\t\t\t\tcase 18:\n\t\t\t\t\tif((op2 & 2) == 0)\n\t\t\t\t\t\t/* SMLAWB/SMLAWT (A8-630) */\n\t\t\t\t\t\tthrow new UnimplementedInstructionException(iword, \"SMLAWB/SMLAWT\");\n\t\t\t\t\telse\n\t\t\t\t\t\t/* SMULWB/SMULWT (A8-648) */\n\t\t\t\t\t\tthrow new UnimplementedInstructionException(iword, \"SMULWB/SMULWT\");\n\t\t\t\tcase 20:\n\t\t\t\t\t/* SMLALBB/SMLALBT/SMLALTB/SMLALTT (A8-626) */\n\t\t\t\t\tthrow new UnimplementedInstructionException(iword, \"SMLALBB/SMLALBT/SMLALTB/SMLALTT\");\n\t\t\t\tcase 22: {\n\t\t\t\t\t/* SMULBB/SMULBT/SMULTB/SMULTT (A8-644) */\n\t\t\t\t\tint Rn = iword & 15;\n\t\t\t\t\tint Rm = (iword>>8) & 15;\n\t\t\t\t\tint Rd = (iword>>16) & 15;\n\t\t\t\t\tint va, vb;\n\t\t\t\t\tif((op2 & 2) != 0) va = readRegister(Rn)>>16;\n\t\t\t\t\telse va = (short)readRegister(Rn);\n\t\t\t\t\tif((op2 & 4) != 0) vb = readRegister(Rm)>>16;\n\t\t\t\t\telse vb = (short)readRegister(Rm);\n\t\t\t\t\twriteRegister(Rd, va*vb);\n\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthrow new UndefinedException();\n\t\t\t}\n\t\t}\n\t\t/* still here... ugh, this is the most confusing part of the instruction space */\n\t\tif(op2 == 9) {\n\t\t\tswitch(op1) {\n\t\t\t/* Multiply and multiply accumulate (A5-202) */\n\t\t\tcase 0: case 1: case 2: case 3: {\n\t\t\t\t/* MUL (A8-502) */\n\t\t\t\t/* MLA (A8-480) */\n\t\t\t\tint Rn = iword&15;\n\t\t\t\tint Rm = (iword>>8)&15;\n\t\t\t\tint Ra = (iword>>12)&15;\n\t\t\t\tint Rd = (iword>>16)&15;\n\t\t\t\tboolean setFlags = (op1&1) != 0;\n\t\t\t\tboolean accumulate = (op1&2) != 0;\n\t\t\t\t// result is the same whether signed or unsigned\n\t\t\t\tint result = readRegister(Rn)*readRegister(Rm);\n\t\t\t\tif(accumulate) result += readRegister(Ra);\n\t\t\t\tif(setFlags) {\n\t\t\t\t\tsetConditionN(result < 0);\n\t\t\t\t\tsetConditionZ(result == 0);\n\t\t\t\t}\n\t\t\t\twriteRegister(Rd, result);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 4:\n\t\t\t\t/* UMAAL (A8-774) */\n\t\t\t\tthrow new UnimplementedInstructionException(iword, \"UMAAL\");\n\t\t\tcase 6: {\n\t\t\t\t/* MLS (A8-482) */\n\t\t\t\tint Rn = iword&15;\n\t\t\t\tint Rm = (iword>>8)&15;\n\t\t\t\tint Ra = (iword>>12)&15;\n\t\t\t\tint Rd = (iword>>16)&15;\n\t\t\t\t// result is the same whether signed or unsigned\n\t\t\t\tint result = readRegister(Rn)*readRegister(Rm);\n\t\t\t\tresult = readRegister(Ra) - result;\n\t\t\t\twriteRegister(Rd, result);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 8: case 9: {\n\t\t\t\t/* UMULL (A8-778) */\n\t\t\t\tint Rn = iword&15;\n\t\t\t\tint Rm = (iword>>8)&15;\n\t\t\t\tint RdLo = (iword>>12)&15;\n\t\t\t\tint RdHi = (iword>>16)&15;\n\t\t\t\tboolean setFlags = (op1&1) != 0;\n\t\t\t\tlong src1 = readRegister(Rn) & 0xFFFFFFFFL;\n\t\t\t\tlong src2 = readRegister(Rm) & 0xFFFFFFFFL;\n\t\t\t\tlong result = src1 * src2;\n\t\t\t\twriteRegister(RdLo, (int)(result & 0xFFFFFFFFL));\n\t\t\t\twriteRegister(RdHi, (int)(result >>> 32));\n\t\t\t\tif(setFlags) {\n\t\t\t\t\tsetConditionN(result < 0);\n\t\t\t\t\tsetConditionZ(result == 0);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 10: case 11:\n\t\t\t\t/* UMLAL (A8-776) */\n\t\t\t\tthrow new UnimplementedInstructionException(iword, \"UMLAL\");\n\t\t\tcase 12: case 13:\n\t\t\t\t/* SMULL (A8-646) */\n\t\t\t\tthrow new UnimplementedInstructionException(iword, \"SMULL\");\n\t\t\tcase 14: case 15:\n\t\t\t\t/* SMLAL (A8-624) */\n\t\t\t\tthrow new UnimplementedInstructionException(iword, \"SMLAL\");\n\t\t\t/* Synchronization primitives (A5-205) */\n\t\t\tcase 16: case 20:\n\t\t\t\t/* SWP/SWPB (A8-722) */\n\t\t\t\tthrow new UnimplementedInstructionException(iword, \"SWP/SWPB\");\n\t\t\tcase 24:\n\t\t\t\t/* STREX (A8-690) */\n\t\t\t\tthrow new UnimplementedInstructionException(iword, \"STREX\");\n\t\t\tcase 25:\n\t\t\t\t/* LDREX (A8-432) */\n\t\t\t\tthrow new UnimplementedInstructionException(iword, \"LDREX\");\n\t\t\tcase 26:\n\t\t\t\t/* STREXD (A8-694) */\n\t\t\t\tthrow new UnimplementedInstructionException(iword, \"STREXD\");\n\t\t\tcase 27:\n\t\t\t\t/* LDREXD (A8-436) */\n\t\t\t\tthrow new UnimplementedInstructionException(iword, \"LDREXD\");\n\t\t\tcase 28:\n\t\t\t\t/* STREXB (A8-692) */\n\t\t\t\tthrow new UnimplementedInstructionException(iword, \"STREXB\");\n\t\t\tcase 29:\n\t\t\t\t/* LDREXB (A8-434) */\n\t\t\t\tthrow new UnimplementedInstructionException(iword, \"LDREXB\");\n\t\t\tcase 30:\n\t\t\t\t/* STREXH (A8-696) */\n\t\t\t\tthrow new UnimplementedInstructionException(iword, \"STREXH\");\n\t\t\tcase 31:\n\t\t\t\t/* LDREXH (A8-438) */\n\t\t\t\tthrow new UnimplementedInstructionException(iword, \"LDREXH\");\n\t\t\tdefault:\n\t\t\t\t/* undefined, explicitly throw */\n\t\t\t\tthrow new UndefinedException();\n\t\t\t}\n\t\t}\n\t\telse if(op2 > 9) {\n\t\t\tboolean argh = (op2 & 4) != 0;\n\t\t\tif((op1 & 16) == 0) {\n\t\t\t\tif(((op2 == 11) && (op1 & 18) == 2)\n\t\t\t\t\t|| (op2 == 13 || op2 == 15) && (op1 & 19) == 3) {\n\t\t\t\t\t/* Extra load/store instructions, unprivileged (A5-204) */\n\t\t\t\t\tswitch(op2) {\n\t\t\t\t\tcase 11:\n\t\t\t\t\t\tif((op1 & 1) == 0) {\n\t\t\t\t\t\t\t/* STRHT (A8-704) */\n\t\t\t\t\t\t\tthrow new UnimplementedInstructionException(iword, \"STRHT\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t/* LDRHT (A8-448) */\n\t\t\t\t\t\t\tthrow new UnimplementedInstructionException(iword, \"LDRHT\");\n\t\t\t\t\t\t}\n\t\t\t\t\tcase 13:\n\t\t\t\t\t\t/* LDRSBT (A8-456) */\n\t\t\t\t\t\tthrow new UnimplementedInstructionException(iword, \"LDRSBT\");\n\t\t\t\t\tcase 15:\n\t\t\t\t\t\t/* LDRSHT (A8-464) */\n\t\t\t\t\t\tthrow new UnimplementedInstructionException(iword, \"LDRSHT\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t/* Extra load/store instructions (A5-203) */\n\t\t\tint Rn = (iword >> 16) & 15;\n\t\t\tswitch(op2) {\n\t\t\tcase 11:\n\t\t\t\tswitch(op1 & 5) {\n\t\t\t\tcase 0: \n\t\t\t\tcase 1:\n\t\t\t\tcase 4:\n\t\t\t\tcase 5: {\n\t\t\t\t\t/* LDRH (register, A8-446) */\n\t\t\t\t\t/* STRH (register, A8-702) */\n\t\t\t\t\t/* LDRH (immediate, ARM, A8-442) */\n\t\t\t\t\t/* LDRH (literal, A8-444) */\n\t\t\t\t\t/* STRH (immediate, ARM, A8-700) */\n\t\t\t\t\tboolean P = ((iword >> 24) & 1) != 0;\n\t\t\t\t\tboolean U = ((iword >> 23) & 1) != 0;\n\t\t\t\t\tboolean W = ((iword >> 21) & 1) != 0;\n\t\t\t\t\tboolean isLoad = ((op1 & 1) != 0);\n\t\t\t\t\tboolean registerForm = ((op1 & 4) == 0);\n\t\t\t\t\tint Rt = (iword >> 12) & 15;\n\t\t\t\t\tint offset;\n\t\t\t\t\tif(registerForm) offset = readRegister(iword & 15);\n\t\t\t\t\telse offset = ((iword >> 4)&240) | (iword&15);\n\t\t\t\t\tboolean writeback = !P || W;\n\t\t\t\t\tint base_addr = readRegisterAlignPC(Rn);\n\t\t\t\t\tint offset_addr;\n\t\t\t\t\tif(U) offset_addr = base_addr + offset;\n\t\t\t\t\telse offset_addr = base_addr - offset;\n\t\t\t\t\tint address = P ? offset_addr : base_addr;\n\t\t\t\t\tint value;\n\t\t\t\t\tif(isLoad) {\n\t\t\t\t\t\tvalue = instructionReadHalfword(address, isPrivileged()) & 0xFFFF;\n\t\t\t\t\t\twriteRegister(Rt, value);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tvalue = readRegister(Rt);\n\t\t\t\t\t\tinstructionWriteHalfword(address, (short)value, isPrivileged());\n\t\t\t\t\t}\n\t\t\t\t\tif(writeback) writeRegister(Rn, offset_addr);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase 13:\n\t\t\t\tswitch(op1 & 5) {\n\t\t\t\tcase 0:\n\t\t\t\tcase 1:\n\t\t\t\tcase 4:\n\t\t\t\tcase 5: {\n\t\t\t\t\t/* Load/store word and unsigned byte (A5-208) */\n\t\t\t\t\t/* LDRD (register, A8-430) */\n\t\t\t\t\t/* LDRSB (register, A8-454) */\n\t\t\t\t\t/* LDRD (immediate, A8-426) */\n\t\t\t\t\t/* LDRD (literal, A8-428) */\n\t\t\t\t\t/* LDRSB (immediate, A8-450) */\n\t\t\t\t\t/* LDRSB (literal, A8-452) */\n\t\t\t\t\tboolean registerForm = ((iword >> 22) & 1) == 0;\n\t\t\t\t\tboolean P = ((iword >> 24) & 1) != 0;\n\t\t\t\t\tboolean U = ((iword >> 23) & 1) != 0;\n\t\t\t\t\tboolean isByte = ((iword >> 20) & 1) != 0;\n\t\t\t\t\tboolean W = ((iword >> 21) & 1) != 0;\n\t\t\t\t\tint Rt = (iword >> 12) & 15;\n\t\t\t\t\tboolean unprivileged = (!P && W);\n\t\t\t\t\tboolean writeback = (!P ^ W);\n\t\t\t\t\tint offset;\n\t\t\t\t\tif(registerForm) offset = readRegister(iword & 15);\n\t\t\t\t\telse offset = (iword & 15) | ((iword >> 4) & 240);\n\t\t\t\t\tint base_addr = readRegisterAlignPC(Rn);\n\t\t\t\t\tint offset_addr;\n\t\t\t\t\tif(U) offset_addr = base_addr + offset;\n\t\t\t\t\telse offset_addr = base_addr - offset;\n\t\t\t\t\tint address = P ? offset_addr : base_addr;\n\t\t\t\t\tint value;\n\t\t\t\t\tif(isByte) {\n\t\t\t\t\t\tvalue = instructionReadByte(address, unprivileged ? false : isPrivileged());\n\t\t\t\t\t\twriteRegister(Rt, value);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tif((Rt&1)!=0 || Rt==14) throw new UndefinedException();\n\t\t\t\t\t\twriteRegister(Rt, instructionReadWord(address, unprivileged ? false : isPrivileged()));\n\t\t\t\t\t\twriteRegister(Rt+1, instructionReadWord(address+4, unprivileged ? false : isPrivileged()));\n\t\t\t\t\t}\n\t\t\t\t\tif(writeback) writeRegister(Rn, offset_addr);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase 15:\n\t\t\t\tswitch(op1 & 5) {\n\t\t\t\tcase 0:\n\t\t\t\t\t/* STRD (register, A8-688) */\n\t\t\t\t\tthrow new UnimplementedInstructionException(iword, \"STRD(688)\");\n\t\t\t\tcase 1:\n\t\t\t\t\t/* LDRSH (register, A8-462) */\n\t\t\t\t\tthrow new UnimplementedInstructionException(iword, \"LDRSH\");\n\t\t\t\tcase 4: {\n\t\t\t\t\t/* STRD (immediate, A8-686) */\n\t\t\t\t\tboolean P = ((iword >> 24) & 1) != 0;\n\t\t\t\t\tboolean U = ((iword >> 23) & 1) != 0;\n\t\t\t\t\tboolean W = ((iword >> 21) & 1) != 0;\n\t\t\t\t\tint Rt = (iword >> 12) & 15;\n\t\t\t\t\tint offset = ((iword >> 4)&240) | (iword&15);\n\t\t\t\t\tboolean writeback = !P || W;\n\t\t\t\t\tint base_addr = readRegisterAlignPC(Rn);\n\t\t\t\t\tint offset_addr;\n\t\t\t\t\tif(U) offset_addr = base_addr + offset;\n\t\t\t\t\telse offset_addr = base_addr - offset;\n\t\t\t\t\tint address = P ? offset_addr : base_addr;\n\t\t\t\t\tinstructionWriteWord(address, readRegister(Rt));\n\t\t\t\t\tinstructionWriteWord(address+4, readRegister(Rt+1));\n\t\t\t\t\tif(writeback) writeRegister(Rn, offset_addr);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcase 5: {\n\t\t\t\t\t/* LDRSH (immediate, A8-458) */\n\t\t\t\t\t/* LDRSH (literal, A8-460) */\n\t\t\t\t\tboolean P = ((iword >> 24) & 1) != 0;\n\t\t\t\t\tboolean U = ((iword >> 23) & 1) != 0;\n\t\t\t\t\tboolean W = ((iword >> 21) & 1) != 0;\n\t\t\t\t\tint Rt = (iword >> 12) & 15;\n\t\t\t\t\tint offset = ((iword >> 4)&240) | (iword&15);\n\t\t\t\t\tboolean writeback = !P || W;\n\t\t\t\t\tint base_addr = readRegisterAlignPC(Rn);\n\t\t\t\t\tint offset_addr;\n\t\t\t\t\tif(U) offset_addr = base_addr + offset;\n\t\t\t\t\telse offset_addr = base_addr - offset;\n\t\t\t\t\tint address = P ? offset_addr : base_addr;\n\t\t\t\t\tint value = instructionReadHalfword(address, isPrivileged());\n\t\t\t\t\twriteRegister(Rt, value);\n\t\t\t\t\tif(writeback) writeRegister(Rn, offset_addr);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthrow new UndefinedException();\n\t}\n\tprivate void executeARMPage1(int iword) throws BusErrorException, AlignmentException, UndefinedException {\n\t\t/* (op=1) Data-processing and miscellaneous instructions (A5-196) */\n\t\tint op1 = (iword >> 20) & 31;\n\t\tswitch(op1) {\n\t\tcase 16:\n\t\t\t/* MOVW (A8-484) */\n\t\t{\n\t\t\tint Rd = (iword >> 12) & 15;\n\t\t\tint imm16 = ((iword >> 4) & 0xF000) | (iword & 0xFFF);\n\t\t\twriteRegister(Rd, imm16);\n\t\t\treturn;\n\t\t}\n\t\tcase 20:\n\t\t\t/* MOVT (high half-word 16 bit immediate, A8-491) */\n\t\t{\n\t\t\tint Rd = (iword >> 12) & 15;\n\t\t\tint imm16 = ((iword >> 4) & 0xF000) | (iword & 0xFFF);\n\t\t\twriteRegister(Rd, (readRegister(Rd) & 0xFFFF) | (imm16 << 16));\n\t\t\treturn;\n\t\t}\n\t\tcase 18:\n\t\tcase 22:\n\t\t\t/* MSR/hints (immediate, A5-206) */\n\t\t{\n\t\t\tint mask = (iword >> 16) & 15;\n\t\t\tif(((iword >> 22) & 1) == 0 && mask == 0) {\n\t\t\t\tint hint = iword & 255;\n\t\t\t\tif(hint >= 240) {\n\t\t\t\t\t/* DBG (A8-377) */\n\t\t\t\t\tif(debugDumpMode) {\n\t\t\t\t\t\tSystem.err.println(\"DBG #\"+(hint&15));\n\t\t\t\t\t\tdumpState(System.err);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tswitch(hint) {\n\t\t\t\tcase 0: break; // NOP (A8-510)\n\t\t\t\tcase 1: break; // YIELD (A8-1108)\n\t\t\t\tcase 2: /* no SMP or events; TODO events */ break; // WFE (A8-1104)\n\t\t\t\tcase 3: // WFI (A8-1106)\n\t\t\t\t\tif(haveFIQ() || haveIRQ()) break;\n\t\t\t\t\twaitingForInterrupt = true;\n\t\t\t\t\treturn;\n\t\t\t\tcase 4: /* no SMP or events; see above */ break; // SEV (A8-606)\n\t\t\t\t}\n\t\t\t\t// do nothing\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tboolean writingSPSR = (op1 & 4) != 0;\n\t\t\t\tif(writingSPSR || ((mask & 3) == 1) || ((mask & 2) != 0))\n\t\t\t\t\t/* MSR (immediate, system-level, B9-1996 */\n\t\t\t\t\tif(!isPrivileged()) throw new UndefinedException();\n\t\t\t\tint imm32 = expandARMImmediate(iword & 4095);\n\t\t\t\tif(writingSPSR)\n\t\t\t\t\tinstrWriteCurSPSR(imm32, mask);\n\t\t\t\telse\n\t\t\t\t\tinstrWriteCurCPSR(imm32, mask, false);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\t}\n\t\t/* Data processing, immediate (A5-199) */\n\t\tint Rn = (iword >> 16) & 15;\n\t\tint Rd = (iword >> 12) & 15;\n\t\tint imm12 = iword & 4095;\n\t\tint n = readRegister(Rn);\n\t\texecuteDataProcessingOperation(op1, n, expandARMImmediate(imm12), Rd);\n\t\tif(Rd == 15 && (op1 & 1) == 1) {\n\t\t\t/* non-privileged flag-setting PC writes are already filtered out by eDPO */\n\t\t\tif(Rn == 14) {\n\t\t\t\t// <op>S PC, LR, #<const>\n\t\t\t\treturnFromProcessorMode();\n\t\t\t}\n\t\t\telse throw new UndefinedException();\n\t\t}\n\t}\n\tprivate void executeARMPage23(int iword) throws BusErrorException, AlignmentException, UndefinedException, EscapeRetryException, EscapeCompleteException {\n\t\tif((iword & (1<<25)) != 0 && (iword & 16) != 0) {\n\t\t\tint op1 = (iword >> 20) & 31;\n\t\t\tint op2 = (iword >> 5) & 7;\n\t\t\tint Rn = iword & 15;\n\t\t\t/* Media instructions (A5-209) */\n\t\t\tif(op1 == 31 && op2 == 7) {\n\t\t\t\t/* UDF (A8-758) */\n\t\t\t\t/* ALWAYS undefined. Worth EXPLICITLY throwing. */\n\t\t\t\tthrow new UndefinedException();\n\t\t\t}\n\t\t\telse if(op1 >= 30) {\n\t\t\t\tif((op2 & 3) == 2) {\n\t\t\t\t\t/* UBFX (A8-756) */\n\t\t\t\t\tint widthminus1 = (iword >> 16) & 31;\n\t\t\t\t\tint Rd = (iword >> 12) & 15;\n\t\t\t\t\tint lsbit = (iword >> 7) & 31;\n\t\t\t\t\twriteRegister(Rd, (readRegister(Rn) >>> lsbit) & (0xFFFFFFFF >>> (31-widthminus1)));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(op1 >= 28) {\n\t\t\t\tif((op2 & 3) == 0) {\n\t\t\t\t\tint lsb = (iword >> 7) & 31;\n\t\t\t\t\tint msb = (iword >> 16) & 31;\n\t\t\t\t\tint Rd = (iword >> 12) & 15;\n\t\t\t\t\tint value = readRegister(Rd);\n\t\t\t\t\tint mask = (0xFFFFFFFF << lsb) & (0xFFFFFFFF >>> (31-msb));\n\t\t\t\t\tif(Rn == 15) {\n\t\t\t\t\t\t/* BFC (A8-336) */\n\t\t\t\t\t\tvalue = (value & ~mask);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t/* BFI (A8-338) */\n\t\t\t\t\t\tvalue = (value & ~mask) | ((readRegister(Rn) << lsb) & mask);\n\t\t\t\t\t}\n\t\t\t\t\twriteRegister(Rd, value);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(op1 >= 26) {\n\t\t\t\tif((op2 & 3) == 2) {\n\t\t\t\t\t/* SBFX (A8-598) */\n\t\t\t\t\tint widthminus1 = (iword >> 16) & 31;\n\t\t\t\t\tint Rd = (iword >> 12) & 15;\n\t\t\t\t\tint lsbit = (iword >> 7) & 31;\n\t\t\t\t\tint value = (readRegister(Rn) >>> lsbit) & (0xFFFFFFFF >>> (31-widthminus1));\n\t\t\t\t\tif((value & (1<<widthminus1))!=0) value |= 0xFFFFFFFF << (widthminus1+1);\n\t\t\t\t\twriteRegister(Rd, value);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(op1 == 24) {\n\t\t\t\tif(op2 == 0) {\n\t\t\t\t\tint Rd = (iword >> 12) & 15;\n\t\t\t\t\tif(Rd == 15) {\n\t\t\t\t\t\t/* USADA8 (A8-794) */\n\t\t\t\t\t\tthrow new UnimplementedInstructionException(iword, \"USADA8\");\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t/* USAD8 (A8-792) */\n\t\t\t\t\t\tthrow new UnimplementedInstructionException(iword, \"USAD8\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(op1 < 24) {\n\t\t\t\tif((op1 & 16) != 0) {\n\t\t\t\t\tif((op1 & 8) == 0) {\n\t\t\t\t\t\t/* Signed multiply, signed and unsigned divide (A5-213) */\n\t\t\t\t\t\top1 &= 7;\n\t\t\t\t\t\tint A = (iword >> 12) & 15;\n\t\t\t\t\t\t/* high nibble is op1, low op2&~1 */\n\t\t\t\t\t\tswitch((op1 << 4) | (op2 & ~1)) {\n\t\t\t\t\t\tcase 0x00:\n\t\t\t\t\t\t\tif(A != 15) {\n\t\t\t\t\t\t\t\t/* SMLAD (A8-622) */\n\t\t\t\t\t\t\t\tthrow new UnimplementedInstructionException(iword, \"SMLAD\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t/* SMUAD (A8-642) */\n\t\t\t\t\t\t\t\tthrow new UnimplementedInstructionException(iword, \"SMUAD\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tcase 0x02:\n\t\t\t\t\t\t\tif(A != 15) {\n\t\t\t\t\t\t\t\t/* SMLSD (A8-632) */\n\t\t\t\t\t\t\t\tthrow new UnimplementedInstructionException(iword, \"SMLSD\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t/* SMUSD (A8-650) */\n\t\t\t\t\t\t\t\tthrow new UnimplementedInstructionException(iword, \"SMUSD\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tcase 0x10:\n\t\t\t\t\t\t\tif(op2 == 0) {\n\t\t\t\t\t\t\t\t/* SDIV (A8-600) */\n\t\t\t\t\t\t\t\tint Rm = (iword>>8)&15;\n\t\t\t\t\t\t\t\tint Rd = (iword>>16)&15;\n\t\t\t\t\t\t\t\tint n = readRegister(Rn);\n\t\t\t\t\t\t\t\tint m = readRegister(Rm);\n\t\t\t\t\t\t\t\tint d;\n\t\t\t\t\t\t\t\tif(m == 0) {\n\t\t\t\t\t\t\t\t\t/* TODO: if IntegerZeroDivideTrappingEnabled() then GenerateIntegerZeroDivide(); */\n\t\t\t\t\t\t\t\t\td = 0;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse if(m == -1 || n == -2147483648)\n\t\t\t\t\t\t\t\t\td = -2147483648;\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\td = n / m;\n\t\t\t\t\t\t\t\twriteRegister(Rd, d);\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse break;\n\t\t\t\t\t\tcase 0x30:\n\t\t\t\t\t\t\tif(op2 == 0) {\n\t\t\t\t\t\t\t\t/* UDIV (A8-760) */\n\t\t\t\t\t\t\t\tint Rm = (iword>>8)&15;\n\t\t\t\t\t\t\t\tint Rd = (iword>>16)&15;\n\t\t\t\t\t\t\t\tint n = readRegister(Rn);\n\t\t\t\t\t\t\t\tint m = readRegister(Rm);\n\t\t\t\t\t\t\t\tint d;\n\t\t\t\t\t\t\t\tif(m == 0) {\n\t\t\t\t\t\t\t\t\t/* TODO: if IntegerZeroDivideTrappingEnabled() then GenerateIntegerZeroDivide(); */\n\t\t\t\t\t\t\t\t\td = 0;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\td = (int)((n&0xFFFFFFFFL) / (m&0xFFFFFFFFL));\n\t\t\t\t\t\t\t\twriteRegister(Rd, d);\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse break;\n\t\t\t\t\t\tcase 0x40:\n\t\t\t\t\t\t\t/* SMLALD (A8-628) */\n\t\t\t\t\t\t\tthrow new UnimplementedInstructionException(iword, \"SMLALD\");\n\t\t\t\t\t\tcase 0x42:\n\t\t\t\t\t\t\t/* SMLSLD (A8-634) */\n\t\t\t\t\t\t\tthrow new UnimplementedInstructionException(iword, \"SMLSLD\");\n\t\t\t\t\t\tcase 0x50:\n\t\t\t\t\t\t\tif(A != 15) {\n\t\t\t\t\t\t\t\t/* SMMLA (A8-636) */\n\t\t\t\t\t\t\t\tthrow new UnimplementedInstructionException(iword, \"SMMLA\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t/* SMMUL (A8-640) */\n\t\t\t\t\t\t\t\tboolean round = ((iword >> 5) & 1) != 0;\n\t\t\t\t\t\t\t\tint Rd = (iword >> 16) & 15;\n\t\t\t\t\t\t\t\tint Rm = (iword >> 8) & 15;\n\t\t\t\t\t\t\t\tlong result = (long)readRegister(Rn) * readRegister(Rm);\n\t\t\t\t\t\t\t\t// System.out.printf(\"\\t%08X * %08X = %016X\\n\", readRegister(Rn), readRegister(Rm), result);\n\t\t\t\t\t\t\t\tif(round) result += 0x80000000L;\n\t\t\t\t\t\t\t\twriteRegister(Rd, (int)(result >> 32));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tcase 0x56:\n\t\t\t\t\t\t\t/* SMMLS (A8-638) */\n\t\t\t\t\t\t\tthrow new UnimplementedInstructionException(iword, \"SMMLS\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if((op1 & 8) != 0) {\n\t\t\t\t\t/* Packing, unpacking, saturation, and reversal (A5-212) */\n\t\t\t\t\top1 &= 7;\n\t\t\t\t\tint Radd = (iword >> 16) & 15;\n\t\t\t\t\tif(op1 == 0) {\n\t\t\t\t\t\tif((op2 & 1) == 0) {\n\t\t\t\t\t\t\t/* PKH (A8-522) */\n\t\t\t\t\t\t\tint Rn_real = (iword >> 16) & 15;\n\t\t\t\t\t\t\tint Rd = (iword >> 12) & 15;\n\t\t\t\t\t\t\tint Rm = iword & 15;\n\t\t\t\t\t\t\tboolean isTB = (iword&64)!=0;\n\t\t\t\t\t\t\tint m = applyIRShift(readRegister(Rm), isTB ? 2 : 0, (iword>>7)&31);\n\t\t\t\t\t\t\tint n = readRegister(Rn_real);\n\t\t\t\t\t\t\tif(isTB)\n\t\t\t\t\t\t\t\twriteRegister(Rd, (m&0x0000FFFF)|(n&0xFFFF0000));\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\twriteRegister(Rd, (m&0xFFFF0000)|(n&0x0000FFFF));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(op2 == 3) {\n\t\t\t\t\t\t\tif(Radd != 15) {\n\t\t\t\t\t\t\t\t/* SXTAB16 (A8-726) */\n\t\t\t\t\t\t\t\tthrow new UnimplementedInstructionException(iword, \"SXTAB16\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t/* SXTB16 (A8-732) */\n\t\t\t\t\t\t\t\tthrow new UnimplementedInstructionException(iword, \"SXTB16\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(op2 == 5) {\n\t\t\t\t\t\t\t/* SEL (A8-602) */\n\t\t\t\t\t\t\tthrow new UnimplementedInstructionException(iword, \"SEL\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if(op1 == 1) {\n\t\t\t\t\t\t/* no valid instructions */\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tboolean unsigned = (op1 & 4) != 0;\n\t\t\t\t\t\t/* high nibble is low bits of op1, low nibble is op2, for ease of reading\n\t\t\t\t\t\t * wish I were compiling against Java 7 so I could use binary literals... */\n\t\t\t\t\t\tswitch(op2 | ((op1 & 3) << 4)) {\n\t\t\t\t\t\tcase 0x21:\n\t\t\t\t\t\t\t/* SSAT16 (A8-654), USAT16 (A8-798) */\n\t\t\t\t\t\t\tthrow new UnimplementedInstructionException(iword, \"*SAT16\");\n\t\t\t\t\t\tcase 0x23: {\n\t\t\t\t\t\t\t/* SXTAB (A8-724), UXTAB (A8-806) */\n\t\t\t\t\t\t\t/* SXTB (A8-730), UXTB (A8-812) */\n\t\t\t\t\t\t\tint Rd = (iword >> 12) & 15;\n\t\t\t\t\t\t\tint rotation = (iword >> 7) & 24;\n\t\t\t\t\t\t\tint result = Integer.rotateRight(readRegister(Rn), rotation);\n\t\t\t\t\t\t\tif(unsigned) result &= 0xFF;\n\t\t\t\t\t\t\telse result = (int)(byte)result;\n\t\t\t\t\t\t\twriteRegister(Rd, Radd == 15 ? result : result + readRegister(Radd));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase 0x31:\n\t\t\t\t\t\t\t/* the unsigned/signed symmetry breaks down here */\n\t\t\t\t\t\t\tif(!unsigned) {\n\t\t\t\t\t\t\t\t/* REV (A8-562) */\n\t\t\t\t\t\t\t\tint Rm = iword&15;\n\t\t\t\t\t\t\t\tint Rd = (iword>>12)&15;\n\t\t\t\t\t\t\t\twriteRegister(Rd, Integer.reverseBytes(readRegister(Rm)));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t/* RBIT (A8-560) */\n\t\t\t\t\t\t\t\tint Rm = iword&15;\n\t\t\t\t\t\t\t\tint Rd = (iword>>12)&15;\n\t\t\t\t\t\t\t\twriteRegister(Rd, Integer.reverse(readRegister(Rm)));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tcase 0x33: {\n\t\t\t\t\t\t\t/* SXTAH (A8-728), UXTAH (A8-810) */\n\t\t\t\t\t\t\t/* SXTH (A8-734), UXTH (A8-816) */\n\t\t\t\t\t\t\tint Rd = (iword >> 12) & 15;\n\t\t\t\t\t\t\tint rotation = (iword >> 7) & 24;\n\t\t\t\t\t\t\tint result = Integer.rotateRight(readRegister(Rn), rotation);\n\t\t\t\t\t\t\tif(unsigned) result &= 0xFFFF;\n\t\t\t\t\t\t\telse result = (int)(short)result;\n\t\t\t\t\t\t\twriteRegister(Rd, Radd == 15 ? result : result + readRegister(Radd));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase 0x35:\n\t\t\t\t\t\t\t/* breaks down here too */\n\t\t\t\t\t\t\tif(!unsigned) {\n\t\t\t\t\t\t\t\t/* REV16 (A8-564) */\n\t\t\t\t\t\t\t\tint Rm = iword&15;\n\t\t\t\t\t\t\t\tint Rd = (iword>>12)&15;\n\t\t\t\t\t\t\t\twriteRegister(Rd, (Short.reverseBytes((short)readRegister(Rm))&0xFFFF)\n\t\t\t\t\t\t\t\t\t\t|(Short.reverseBytes((short)(readRegister(Rm)>>16))<<16));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t/* REVSH (A8-566) */\n\t\t\t\t\t\t\t\tint Rm = iword&15;\n\t\t\t\t\t\t\t\tint Rd = (iword>>12)&15;\n\t\t\t\t\t\t\t\twriteRegister(Rd, Short.reverseBytes((short)readRegister(Rm)));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tif((op1 & 6) == 2 && (op2 & 1) == 0) {\n\t\t\t\t\t\t\t\t/* SSAT (A8-652), USAT (A8-796) */\n\t\t\t\t\t\t\t\tthrow new UnimplementedInstructionException(iword, \"*SAT\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t/* Parallel addition and subtraction, signed (A5-210) */\n\t\t\t\t\t/* Parallel addition and subtraction, unsigned (A5-211) */\n\t\t\t\t\tboolean unsigned = (op1 & 4) != 0;\n\t\t\t\t\tboolean saturate = (op1 & 3) == 2;\n\t\t\t\t\tboolean half = (op1 & 3) == 3;\n\t\t\t\t\tint Rn_real = (iword>>16)&15;\n\t\t\t\t\tint Rd = (iword>>12)&15;\n\t\t\t\t\tint Rm = iword&15;\n\t\t\t\t\tint n = readRegister(Rn_real);\n\t\t\t\t\tint m = readRegister(Rm);\n\t\t\t\t\tswitch(op2) {\n\t\t\t\t\tcase 0: {\n\t\t\t\t\t\t/* SADD16 (A8-586), QADD16 (A8-542), SHADD16 (A5-608), UADD16 (A8-750), UQADD16 (A8-780), UHADD16 (A8-762) */\n\t\t\t\t\t\tint loN = (short)n;\n\t\t\t\t\t\tint hiN = (short)(n>>16);\n\t\t\t\t\t\tint loM = (short)m;\n\t\t\t\t\t\tint hiM = (short)(m>>16);\n\t\t\t\t\t\tif(unsigned) {\n\t\t\t\t\t\t\tloN &= 0xFFFF;\n\t\t\t\t\t\t\thiN &= 0xFFFF;\n\t\t\t\t\t\t\tloM &= 0xFFFF;\n\t\t\t\t\t\t\thiM &= 0xFFFF;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tint loD = loN + loM;\n\t\t\t\t\t\tint hiD = hiN + hiM;\n\t\t\t\t\t\tif(half) {\n\t\t\t\t\t\t\tloD >>= 1;\n\t\t\t\t\t\t\thiD >>= 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(saturate) {\n\t\t\t\t\t\t\tif(unsigned) {\n\t\t\t\t\t\t\t\tloD = clamp(loD, 0, 0xFFFF);\n\t\t\t\t\t\t\t\thiD = clamp(hiD, 0, 0xFFFF);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tloD = clamp(loD, -0x8000, 0x7FFF);\n\t\t\t\t\t\t\t\thiD = clamp(hiD, -0x8000, 0x7FFF);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\twriteRegister(Rd, (loD&0xFFFF)|(hiD<<16));\n\t\t\t\t\t} return;\n\t\t\t\t\tcase 1: {\n\t\t\t\t\t\t/* SASX (A8-590), QASX (A8-546), SHASX (A8-612), UASX (A8-754), UQASX (A8-784), UHASX (A8-766) */\n\t\t\t\t\t\tint loN = (short)n;\n\t\t\t\t\t\tint hiN = (short)(n>>16);\n\t\t\t\t\t\tint loM = (short)m;\n\t\t\t\t\t\tint hiM = (short)(m>>16);\n\t\t\t\t\t\tif(unsigned) {\n\t\t\t\t\t\t\tloN &= 0xFFFF;\n\t\t\t\t\t\t\thiN &= 0xFFFF;\n\t\t\t\t\t\t\tloM &= 0xFFFF;\n\t\t\t\t\t\t\thiM &= 0xFFFF;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tint loD = loN - hiM;\n\t\t\t\t\t\tint hiD = hiN + loM;\n\t\t\t\t\t\tif(half) {\n\t\t\t\t\t\t\tloD >>= 1;\n\t\t\t\t\t\t\thiD >>= 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(saturate) {\n\t\t\t\t\t\t\tif(unsigned) {\n\t\t\t\t\t\t\t\tloD = clamp(loD, 0, 0xFFFF);\n\t\t\t\t\t\t\t\thiD = clamp(hiD, 0, 0xFFFF);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tloD = clamp(loD, -0x8000, 0x7FFF);\n\t\t\t\t\t\t\t\thiD = clamp(hiD, -0x8000, 0x7FFF);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\twriteRegister(Rd, (loD&0xFFFF)|(hiD<<16));\n\t\t\t\t\t} return;\n\t\t\t\t\tcase 2: {\n\t\t\t\t\t\t/* SSAX (A8-656), QSAX (A8-552), SHSAX (A8-614), USAX (A8-800), UQSAX (A8-786), UHSAX (A8-768) */\n\t\t\t\t\t\tint loN = (short)n;\n\t\t\t\t\t\tint hiN = (short)(n>>16);\n\t\t\t\t\t\tint loM = (short)m;\n\t\t\t\t\t\tint hiM = (short)(m>>16);\n\t\t\t\t\t\tif(unsigned) {\n\t\t\t\t\t\t\tloN &= 0xFFFF;\n\t\t\t\t\t\t\thiN &= 0xFFFF;\n\t\t\t\t\t\t\tloM &= 0xFFFF;\n\t\t\t\t\t\t\thiM &= 0xFFFF;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tint loD = loN + hiM;\n\t\t\t\t\t\tint hiD = hiN - loM;\n\t\t\t\t\t\tif(half) {\n\t\t\t\t\t\t\tloD >>= 1;\n\t\t\t\t\t\t\thiD >>= 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(saturate) {\n\t\t\t\t\t\t\tif(unsigned) {\n\t\t\t\t\t\t\t\tloD = clamp(loD, 0, 0xFFFF);\n\t\t\t\t\t\t\t\thiD = clamp(hiD, 0, 0xFFFF);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tloD = clamp(loD, -0x8000, 0x7FFF);\n\t\t\t\t\t\t\t\thiD = clamp(hiD, -0x8000, 0x7FFF);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\twriteRegister(Rd, (loD&0xFFFF)|(hiD<<16));\n\t\t\t\t\t} return;\n\t\t\t\t\tcase 3: {\n\t\t\t\t\t\t/* SSUB16 (A8-658), QSUB16 (A8-556), SHSUB16 (A8-616), USUB16 (A8-802), UQSUB16 (A8-788), UHSUB16 (A8-770) */\n\t\t\t\t\t\tint loN = (short)n;\n\t\t\t\t\t\tint hiN = (short)(n>>16);\n\t\t\t\t\t\tint loM = (short)m;\n\t\t\t\t\t\tint hiM = (short)(m>>16);\n\t\t\t\t\t\tif(unsigned) {\n\t\t\t\t\t\t\tloN &= 0xFFFF;\n\t\t\t\t\t\t\thiN &= 0xFFFF;\n\t\t\t\t\t\t\tloM &= 0xFFFF;\n\t\t\t\t\t\t\thiM &= 0xFFFF;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tint loD = loN - loM;\n\t\t\t\t\t\tint hiD = hiN - hiM;\n\t\t\t\t\t\tif(half) {\n\t\t\t\t\t\t\tloD >>= 1;\n\t\t\t\t\t\t\thiD >>= 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(saturate) {\n\t\t\t\t\t\t\tif(unsigned) {\n\t\t\t\t\t\t\t\tloD = clamp(loD, 0, 0xFFFF);\n\t\t\t\t\t\t\t\thiD = clamp(hiD, 0, 0xFFFF);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tloD = clamp(loD, -0x8000, 0x7FFF);\n\t\t\t\t\t\t\t\thiD = clamp(hiD, -0x8000, 0x7FFF);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\twriteRegister(Rd, (loD&0xFFFF)|(hiD<<16));\n\t\t\t\t\t} return;\n\t\t\t\t\tcase 4: {\n\t\t\t\t\t\t/* SADD8 (A8-588), QADD8 (A8-544), SHADD8 (A8-610), UADD8 (A8-752), UQADD8 (A8-782), UHADD8 (A8-764) */\n\t\t\t\t\t\tint n0 = (byte)n;\n\t\t\t\t\t\tint n1 = (byte)(n>>8);\n\t\t\t\t\t\tint n2 = (byte)(n>>16);\n\t\t\t\t\t\tint n3 = (byte)(n>>24);\n\t\t\t\t\t\tint m0 = (byte)m;\n\t\t\t\t\t\tint m1 = (byte)(m>>8);\n\t\t\t\t\t\tint m2 = (byte)(m>>16);\n\t\t\t\t\t\tint m3 = (byte)(m>>24);\n\t\t\t\t\t\tif(unsigned) {\n\t\t\t\t\t\t\tn0 &= 0xFF;\n\t\t\t\t\t\t\tn1 &= 0xFF;\n\t\t\t\t\t\t\tn2 &= 0xFF;\n\t\t\t\t\t\t\tn3 &= 0xFF;\n\t\t\t\t\t\t\tm0 &= 0xFF;\n\t\t\t\t\t\t\tm1 &= 0xFF;\n\t\t\t\t\t\t\tm2 &= 0xFF;\n\t\t\t\t\t\t\tm3 &= 0xFF;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tint d0 = n0+m0;\n\t\t\t\t\t\tint d1 = n1+m1;\n\t\t\t\t\t\tint d2 = n2+m2;\n\t\t\t\t\t\tint d3 = n3+m3;\n\t\t\t\t\t\tif(half) {\n\t\t\t\t\t\t\td0 >>= 1;\n\t\t\t\t\t\t\td1 >>= 1;\n\t\t\t\t\t\t\td2 >>= 1;\n\t\t\t\t\t\t\td3 >>= 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(saturate) {\n\t\t\t\t\t\t\tif(unsigned) {\n\t\t\t\t\t\t\t\td0 = clamp(d0, 0, 0xFF);\n\t\t\t\t\t\t\t\td1 = clamp(d1, 0, 0xFF);\n\t\t\t\t\t\t\t\td2 = clamp(d2, 0, 0xFF);\n\t\t\t\t\t\t\t\td3 = clamp(d3, 0, 0xFF);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\td0 = clamp(d0, -0x80, 0x7F);\n\t\t\t\t\t\t\t\td1 = clamp(d1, -0x80, 0x7F);\n\t\t\t\t\t\t\t\td2 = clamp(d2, -0x80, 0x7F);\n\t\t\t\t\t\t\t\td3 = clamp(d3, -0x80, 0x7F);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\twriteRegister(Rd, (d0&0xFF)|((d1&0xFF)<<8)|((d2&0xFF)<<16)|(d3<<24));\n\t\t\t\t\t} return;\n\t\t\t\t\tcase 7: {\n\t\t\t\t\t\t/* SSUB8 (A8-660), QSUB8 (A8-558), SHSUB8 (A8-618), USUB8 (A8-804), UQSUB8 (A8-790), UHSUB8 (A8-772) */\n\t\t\t\t\t\tint n0 = (byte)n;\n\t\t\t\t\t\tint n1 = (byte)(n>>8);\n\t\t\t\t\t\tint n2 = (byte)(n>>16);\n\t\t\t\t\t\tint n3 = (byte)(n>>24);\n\t\t\t\t\t\tint m0 = (byte)m;\n\t\t\t\t\t\tint m1 = (byte)(m>>8);\n\t\t\t\t\t\tint m2 = (byte)(m>>16);\n\t\t\t\t\t\tint m3 = (byte)(m>>24);\n\t\t\t\t\t\tif(unsigned) {\n\t\t\t\t\t\t\tn0 &= 0xFF;\n\t\t\t\t\t\t\tn1 &= 0xFF;\n\t\t\t\t\t\t\tn2 &= 0xFF;\n\t\t\t\t\t\t\tn3 &= 0xFF;\n\t\t\t\t\t\t\tm0 &= 0xFF;\n\t\t\t\t\t\t\tm1 &= 0xFF;\n\t\t\t\t\t\t\tm2 &= 0xFF;\n\t\t\t\t\t\t\tm3 &= 0xFF;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tint d0 = n0-m0;\n\t\t\t\t\t\tint d1 = n1-m1;\n\t\t\t\t\t\tint d2 = n2-m2;\n\t\t\t\t\t\tint d3 = n3-m3;\n\t\t\t\t\t\tif(half) {\n\t\t\t\t\t\t\td0 >>= 1;\n\t\t\t\t\t\t\td1 >>= 1;\n\t\t\t\t\t\t\td2 >>= 1;\n\t\t\t\t\t\t\td3 >>= 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(saturate) {\n\t\t\t\t\t\t\tif(unsigned) {\n\t\t\t\t\t\t\t\td0 = clamp(d0, 0, 0xFF);\n\t\t\t\t\t\t\t\td1 = clamp(d1, 0, 0xFF);\n\t\t\t\t\t\t\t\td2 = clamp(d2, 0, 0xFF);\n\t\t\t\t\t\t\t\td3 = clamp(d3, 0, 0xFF);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\td0 = clamp(d0, -0x80, 0x7F);\n\t\t\t\t\t\t\t\td1 = clamp(d1, -0x80, 0x7F);\n\t\t\t\t\t\t\t\td2 = clamp(d2, -0x80, 0x7F);\n\t\t\t\t\t\t\t\td3 = clamp(d3, -0x80, 0x7F);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\twriteRegister(Rd, (d0&0xFF)|((d1&0xFF)<<8)|((d2&0xFF)<<16)|(d3<<24));\n\t\t\t\t\t} return;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t/* Load/store word and unsigned byte (A5-208) */\n\t\t\t/* STR (immediate, ARM, A8-674) */\n\t\t\t/* STR (register, A8-676) */\n\t\t\t/* STRT (A8-706) */\n\t\t\t/* LDR (immediate, ARM, A8-408) */\n\t\t\t/* LDR (literal, A8-410) */\n\t\t\t/* LDR (register, ARM, A8-414) */\n\t\t\t/* LDRT (A8-466) */\n\t\t\t/* after hours of banging my head against the wall, the relationship between them becomes clear */\n\t\t\tboolean registerForm = ((iword >> 25) & 1) != 0;\n\t\t\tboolean P = ((iword >> 24) & 1) != 0;\n\t\t\tboolean U = ((iword >> 23) & 1) != 0;\n\t\t\tboolean isByte = ((iword >> 22) & 1) != 0;\n\t\t\tboolean W = ((iword >> 21) & 1) != 0;\n\t\t\tboolean isLoad = ((iword >> 20) & 1) != 0;\n\t\t\tint Rn = (iword >> 16) & 15;\n\t\t\tint Rt = (iword >> 12) & 15;\n\t\t\tboolean unprivileged = (!P && W);\n\t\t\tboolean writeback = (!P ^ W);\n\t\t\tint offset;\n\t\t\tif(registerForm) offset = applyIRShift(readRegister(iword & 15), (iword >> 5) & 3, (iword >> 7) & 31);\n\t\t\telse offset = iword & 4095;\n\t\t\tint base_addr = readRegisterAlignPC(Rn);\n\t\t\tint offset_addr;\n\t\t\tif(U) offset_addr = base_addr + offset;\n\t\t\telse offset_addr = base_addr - offset;\n\t\t\tint address = P ? offset_addr : base_addr;\n\t\t\tint value;\n\t\t\tif(isLoad) {\n\t\t\t\tif(isByte) value = instructionReadByte(address, unprivileged ? false : isPrivileged()) & 0xFF;\n\t\t\t\telse value = instructionReadWord(address, unprivileged ? false : isPrivileged());\n\t\t\t\twriteRegister(Rt, value);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tvalue = readRegister(Rt);\n\t\t\t\tif(isByte) instructionWriteByte(address, (byte)value, unprivileged ? false : isPrivileged());\n\t\t\t\telse instructionWriteWord(address, value, unprivileged ? false : isPrivileged());\n\t\t\t}\n\t\t\tif(writeback) writeRegister(Rn, offset_addr);\n\t\t\treturn;\n\t\t}\n\t\tthrow new UndefinedException();\n\t}\n\tprivate void executeARMPage45(int iword) throws BusErrorException, AlignmentException, UndefinedException, EscapeRetryException, EscapeCompleteException {\n\t\t/* Branch, branch with link, and block data transfer (A5-214) */\n\t\tint op = (iword >> 20) & 63;\n\t\tif(op >= 32) {\n\t\t\t/* B, BL (A8-334, A8-348) */\n\t\t\tboolean link = (op & 16) != 0;\n\t\t\tint imm32 = iword << 8 >> 6;\n\t\t\tif(link) writeLR(readPC()-4);\n\t\t\tbranch(readPC()+imm32);\n\t\t\treturn;\n\t\t}\n /* LDMDA/LDMFA (A8-400) */\n /* LDM/LDMIA/LDMFD (ARM, A8-398) */\n /* LDMDB/LDMEA (A8-402) */\n /* LDMIB/LDMED (A8-404) */\n /* STMDA/STMED (A8-666) */\n /* STM/STMIA/STMEA (A8-664) */\n /* STMDB/STMFD (A8-668) */\n /* STMIB/STMFA (A8-670) */\n /* POP (ARM, A8-536) */\n /* PUSH (A8-538) */\n\t\tboolean isLoad = (op & 1) != 0;\n\t\tboolean W = (op & 2) != 0;\n\t\tboolean userReg = (op & 4) != 0; // TODO: userReg\n\t\tboolean increment = (op & 8) != 0;\n\t\tboolean before = (op & 16) != 0;\n\t\tint Rn = (iword >> 16) & 15;\n\t\tint base_addr = readRegisterAlignPC(Rn);\n\t\tint register_list = iword & 65535;\n\t\tint register_count = Integer.bitCount(register_list);\n\t\t// System.out.printf(\"%s%s%s r%d%s, {%04X}\\n\", isLoad?\"LDM\":\"STM\", increment?\"I\":\"D\", before?\"B\":\"A\", Rn, W?\"!\":\"\", register_list);\n\t\tif(!increment) base_addr -= 4 * register_count;\n\t\tint addr = base_addr;\n\t\tif(increment == before) addr += 4;\n\t\tfor(int n = 0; n < 16; n++) {\n\t\t\tif((register_list & (1<<n)) != 0) {\n\t\t\t\tif(isLoad) writeRegister(n, instructionReadWord(addr));\n\t\t\t\telse instructionWriteWord(addr, readRegister(n));\n\t\t\t\taddr += 4;\n\t\t\t}\n\t\t}\n\t\tif(increment) base_addr += 4 * register_count;\n\t\tif(W) writeRegister(Rn, base_addr);\n\t\treturn;\n\t}\n\tprivate void executeARMPage67(int iword, boolean unconditional) throws BusErrorException, AlignmentException, UndefinedException, EscapeRetryException, EscapeCompleteException {\n\t\t/* Coprocessor instructions, and Supervisor Call (A5-215) */\n\t\tint op1 = (iword >> 20) & 63;\n\t\tif((op1 & 62) == 0) throw new UndefinedException();\n\t\telse if((op1 & 48) == 48) {\n\t\t\tif(unconditional) throw new UndefinedException();\n\t\t\t/* SVC (previously known as SWI, A8-720) */\n\t\t\tperformSVC();\n\t\t\treturn;\n\t\t}\n\t\tint coproc = (iword >> 8) & 15;\n\t\t/* TODO: throw UndefinedException when a coprocessor is masked out */\n\t\tCoprocessor cop = coprocessors[coproc];\n\t\tif(cop == null) throw new UndefinedException();\n\t\telse cop.executeInstruction(unconditional, iword);\n\t}\n\tprivate void executeARMUnconditional(int iword) throws BusErrorException, AlignmentException, UndefinedException, EscapeRetryException, EscapeCompleteException {\n\t\t/* Unconditional instructions (A5-216) */\n\t\tswitch((iword >> 26) & 3) {\n\t\tcase 0: case 1:\n\t\t\t/* TODO: Memory hints, Advanced SIMD instructions, and miscellaneous instructions (A5-217) */\n\t\t\tint op1 = (iword >> 20) & 127;\n\t\t\tint op2 = (iword >> 4) & 15;\n\t\t\tint Rn = (iword >> 16) & 15;\n\t\t\tswitch(op1) {\n\t\t\tcase 16:\n\t\t\t\tif((Rn&1) == 0) {\n\t\t\t\t\tif((op2&2) == 0) {\n\t\t\t\t\t\t/* CPS (B9-1980) */\n\t\t\t\t\t\tif(!mode.privileged) return; // act as NOP\n\t\t\t\t\t\tswitch(Rn&12) {\n\t\t\t\t\t\tcase 8:\n\t\t\t\t\t\t\tcpsr = cpsr | (iword & 0x1C0);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 12:\n\t\t\t\t\t\t\tcpsr = cpsr & (~0 ^ (iword & 0x1C0));\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif((Rn&2) == 2) {\n\t\t\t\t\t\t\tsetProcessorMode(iword & 0x1F);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif(op2 == 0) {\n\t\t\t\t\t\t/* SETEND (A8-604) */\n\t\t\t\t\t\tcpsr &= ~(1<<CPSR_BIT_E);\n\t\t\t\t\t\tcpsr |= iword&(1<<CPSR_BIT_E);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 18:\n\t\t\t\tif(op2 == 7) {\n\t\t\t\t\t/* Unpredictable? Why would you SPECIFICALLY encode Unpredictable?!!?! */\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 64:\n\t\t\tcase 66:\n\t\t\tcase 68:\n\t\t\tcase 70:\n\t\t\tcase 72:\n\t\t\tcase 74:\n\t\t\tcase 76:\n\t\t\tcase 78:\n\t\t\t\t/* Advanced SIMD element or structure load/store instructions (A7-275) */\n\t\t\t\tthrow new UnimplementedInstructionException(iword, \"A7-275\");\n\t\t\tcase 97:\n\t\t\tcase 105:\n\t\t\t\t/* Unallocated memory hint (treat as NOP) */\n\t\t\t\tif((op2&1) == 0) return;\n\t\t\tcase 65:\n\t\t\tcase 73:\n\t\t\t\t/* Unallocated memory hint (treat as NOP) */\n\t\t\t\treturn;\n\t\t\tcase 69:\n\t\t\tcase 77:\n\t\t\t\t/* Preload Instruction (A8-530) */\n\t\t\t\t/* TODO: When MMU is implemented, preload the page table cache */\n\t\t\t\t/* TODO: When JIT is implemented, discard the instruction cace */\n\t\t\t\treturn;\n\t\t\t/* 0b100xx11 = unpredictable */\n\t\t\tcase 81:\n\t\t\tcase 85:\n\t\t\tcase 89:\n\t\t\tcase 93:\n\t\t\t\t/* PLD, PLDW (A8-524) */\n\t\t\t\t/* TODO: When MMU is implemented, preload the page table cache */\n\t\t\t\tbreak;\n\t\t\tcase 87:\n\t\t\t\tswitch(op2) {\n\t\t\t\tcase 1:\n\t\t\t\t\t/* CLREX (A8-360) */\n\t\t\t\t\t/* We have no multiprocessing, so this is a no-op */\n\t\t\t\t\treturn;\n\t\t\t\tcase 4:\n\t\t\t\t\t/* DSB (A8-380) */\n\t\t\t\t\t/* We have no multiprocessing, so this is a no-op */\n\t\t\t\t\treturn;\n\t\t\t\tcase 5:\n\t\t\t\t\t/* DMB (A8-378) */\n\t\t\t\t\t/* We have no multiprocessing, so this is a no-op */\n\t\t\t\t\treturn;\n\t\t\t\tcase 6:\n\t\t\t\t\t/* ISB (A8-389) */\n\t\t\t\t\t/* TODO: When MMU / JIT are implemented, this will be important */\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 101:\n\t\t\tcase 109:\n\t\t\t\tif((op2 & 1) == 0) {\n\t\t\t\t\t/* PLI (A8-532) */\n\t\t\t\t\tthrow new UnimplementedInstructionException(iword, \"PLI\");\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 113:\n\t\t\tcase 117:\n\t\t\tcase 121:\n\t\t\tcase 125:\n\t\t\t\tif((op2 & 1) == 0) {\n\t\t\t\t\t/* PLD (A8-528) */\n\t\t\t\t\tthrow new UnimplementedInstructionException(iword, \"PLD/PLDW\");\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 127:\n\t\t\t\tif(op2 == 15) {\n\t\t\t\t\t/* Permanently UNDEFINED */\n\t\t\t\t\tthrow new UndefinedException();\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tif((op1 & 96) == 32) {\n\t\t\t\t\t/* Advanced SIMD data-processing intructions (A7-261) */\n\t\t\t\t\tthrow new UnimplementedInstructionException(iword, \"A7-261\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tif(((iword >> 25) & 1) == 0) {\n\t\t\t\tint op1ish = (iword >> 20) & 31;\n\t\t\t\tif((op1ish & 5) == 4)\n\t\t\t\t\t/* SRS (ARM, B9-2006) */\n\t\t\t\t\tthrow new UnimplementedInstructionException(iword, \"SRS\");\n\t\t\t\telse if((op1ish & 5) == 1) {\n\t\t\t\t\t/* RFE (ARM, A8-568, B9-2000) */\n\t\t\t\t\tif(!isPrivileged()) throw new UndefinedException();\n\t\t\t\t\tboolean P = ((iword >> 24) & 1) != 0;\n\t\t\t\t\tboolean U = ((iword >> 23) & 1) != 0;\n\t\t\t\t\tboolean W = ((iword >> 21) & 1) != 0;\n\t\t\t\t\tint Rn_real = (iword >> 16) & 15;\n\t\t\t\t\tboolean writeback = W;\n\t\t\t\t\tboolean wordhigher = (P == U);\n\t\t\t\t\tint base_addr = readRegisterAlignPC(Rn_real);\n\t\t\t\t\tint offset_addr;\n\t\t\t\t\tif(wordhigher) offset_addr = base_addr + 4;\n\t\t\t\t\telse offset_addr = base_addr;\n\t\t\t\t\tint address = P ? offset_addr : base_addr;\n\t\t\t\t\twritePC(instructionReadWord(address+4, isPrivileged()));\n\t\t\t\t\tinstrWriteCurCPSR(instructionReadWord(address+4, isPrivileged()), 0xF, true);\n\t\t\t\t\tif(writeback) {\n\t\t\t\t\t\tif(U) writeRegister(Rn_real, base_addr + 8);\n\t\t\t\t\t\telse writeRegister(Rn_real, base_addr - 8);\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\t/* BLX (A8-348) */\n\t\t\t\tint imm32 = (iword << 8 >> 6) | (iword << 7 >> 7) | 1;\n\t\t\t\twriteLR(readPC()-4);\n\t\t\t\t// always switches instruction sets; set the low bit to achieve Thumb enlightenment\n\t\t\t\tinterworkingBranch((readPC()&~3)+imm32);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\texecuteARMPage67(iword, true);\n\t\t\treturn;\n\t\t}\n\t\tthrow new UndefinedException();\n\t}\n\tprivate void executeARM(int iword) throws BusErrorException, AlignmentException, UndefinedException, EscapeRetryException, EscapeCompleteException {\n\t\tint condition = (iword >> 28) & 15;\n\t\tif(condition != 15) {\n\t\t\t/* condition codes (A5-288) */\n\t\t\tboolean execute = true;\n\t\t\tswitch(condition >> 1) {\n\t\t\tcase 0: execute = conditionZ(); break;\n\t\t\tcase 1: execute = conditionC(); break;\n\t\t\tcase 2: execute = conditionN(); break;\n\t\t\tcase 3: execute = conditionV(); break;\n\t\t\tcase 4: execute = conditionC() && !conditionZ(); break;\n\t\t\tcase 5: execute = conditionN() == conditionV(); break;\n\t\t\tcase 6: execute = conditionZ() == false && conditionN() == conditionV(); break;\n\t\t\t/* case 7: execute = true; */\n\t\t\t}\n\t\t\tif((condition & 1) != 0) execute = !execute;\n\t\t\tif(!execute) return;\n\t\t\tswitch((iword >> 25) & 7) {\n\t\t\tcase 0:\n\t\t\t\texecuteARMPage0(iword);\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\texecuteARMPage1(iword);\n\t\t\t\tbreak;\n\t\t\tcase 2: case 3:\n\t\t\t\texecuteARMPage23(iword);\n\t\t\t\tbreak;\n\t\t\tcase 4: case 5:\n\t\t\t\texecuteARMPage45(iword);\n\t\t\t\tbreak;\n\t\t\tcase 6:\n\t\t\tcase 7:\n\t\t\t\texecuteARMPage67(iword, false);\n\t\t\t}\n\t\t}\n\t\telse executeARMUnconditional(iword);\n\t}\n\tprivate void performSVC() { generateException(ProcessorMode.SUPERVISOR, (1<<CPSR_BIT_I), EXCEPTION_VECTOR_SUPERVISOR_CALL, isThumb()?pc-2:pc-4); }\n\tprivate void generateUndefinedException() { generateException(ProcessorMode.UNDEFINED, (1<<CPSR_BIT_I), EXCEPTION_VECTOR_UNDEFINED, pc); }\n\tprivate void generatePrefetchAbortException() { generateException(ProcessorMode.ABORT, (1<<CPSR_BIT_I)|(1<<CPSR_BIT_A), EXCEPTION_VECTOR_PREFETCH_ABORT, pc); }\n\tprivate void generateDataAbortException() { generateException(ProcessorMode.ABORT, (1<<CPSR_BIT_I)|(1<<CPSR_BIT_A), EXCEPTION_VECTOR_DATA_ABORT, pc+8); }\n\tprivate void generateIRQException() { generateException(ProcessorMode.IRQ, (1<<CPSR_BIT_I)|(1<<CPSR_BIT_A), EXCEPTION_VECTOR_IRQ, pc+4); }\n\tprivate void generateFIQException() { generateException(ProcessorMode.FIQ, (1<<CPSR_BIT_I)|(1<<CPSR_BIT_A)|(1<<CPSR_BIT_F), EXCEPTION_VECTOR_FIQ, pc+4); }\n\tprivate void generateException(ProcessorMode targetMode, int interruptMask, int vector, int preferredReturn) {\n\t\tenterProcessorModeByException(targetMode);\n\t\tlr[cur_lr] = preferredReturn;\n\t\tcpsr |= interruptMask;\n\t\t/* zero J/E/T/IT<7:0> */\n\t\tcpsr &= ~((1<<CPSR_BIT_J) | (1<<CPSR_BIT_E) | (1<<CPSR_BIT_T) | (CPSR_MASK_ITLO << CPSR_SHIFT_ITLO) | (CPSR_MASK_ITHI << CPSR_SHIFT_ITHI));\n\t\tif((cp15.SCTLR & (1<<CP15.SCTLR_BIT_TE)) != 0) cpsr |= (1<<CPSR_BIT_T);\n\t\telse cpsr &= ~(1<<CPSR_BIT_T);\n\t\tif((cp15.SCTLR & (1<<CP15.SCTLR_BIT_EE)) != 0) cpsr |= (1<<CPSR_BIT_E);\n\t\telse cpsr &= ~(1<<CPSR_BIT_E);\n\t\tbranch(getInterruptVector(vector));\n\t}\n\t/* B1-1206 */\n\t/**\n\t * Reset the CPU. This must be called at least once before any execution occurs.\n\t * @param thumb_exceptions Whether the TE bit in SCTLR is initially set. (i.e. whether the exception vectors are Thumb code rather than ARM code)\n\t * @param big_endian Whether the EE bit in SCTLR is initially set. (i.e. whether exceptions begin execution in big-endian mode)\n\t * @param high_vectors Whether the V bit in SCTLR is initially set. (i.e. whether the exception vectors are at 0xFFFFxxxx instead of 0x0000xxxx)\n\t */\n\tpublic void reset(boolean thumb_exceptions, boolean big_endian, boolean high_vectors) {\n\t\thaveReset = true;\n\t\tcpsr = ProcessorMode.SUPERVISOR.modeRepresentation;\n\t\t// ResetControlRegisters()\n\t\tfor(int n = 0; n < 8; ++n) {\n\t\t\tif(coprocessors[n] != null) coprocessors[n].reset();\n\t\t}\n\t\tcp15.reset(thumb_exceptions, big_endian, high_vectors);\n\t\t// TODO: for FP: FPEXC.EN = 0\n\t\tgenerateException(ProcessorMode.SUPERVISOR, (1<<CPSR_BIT_I) | (1<<CPSR_BIT_A) | (1<<CPSR_BIT_F), EXCEPTION_VECTOR_RESET, 0xDEADBEEF);\n\t}\n\t/*** INTERRUPTS ***/\n\tprivate boolean waitingForInterrupt = false;\n\tpublic boolean isWaitingForInterrupt() {\n\t\treturn waitingForInterrupt;\n\t}\n\tprivate TreeSet<Object> irqs = new TreeSet<Object>();\n\tprivate TreeSet<Object> fiqs = new TreeSet<Object>();\n\tpublic boolean haveIRQ() { return !irqs.isEmpty(); }\n\tpublic boolean haveFIQ() { return !fiqs.isEmpty(); }\n\t/**\n\t * TODO: document the interrupt functions\n\t * @param who\n\t */\n\tpublic void setIRQ(Object who) {\n\t\tirqs.add(who);\n\t}\n\t/**\n\t * \n\t * @param who\n\t */\n\tpublic void clearIRQ(Object who) {\n\t\tirqs.remove(who);\n\t}\n\t/**\n\t * \n\t * @param who\n\t */\n\tpublic void setFIQ(Object who) {\n\t\tfiqs.add(who);\n\t}\n\t/**\n\t * \n\t * @param who\n\t */\n\tpublic void clearFIQ(Object who) {\n\t\tfiqs.remove(who);\n\t}\n\t/*** DEBUGGING ***/\n\tprivate boolean exceptionDebugMode = false;\n\tprivate boolean debugDumpMode = false;\n\t/**\n\t * This mode defaults to false. When true, exceptions are thrown to Java rather than processed by the emulated CPU.\n\t * @param nu The new mode.\n\t */\n\tpublic void setExceptionDebugMode(boolean nu) { exceptionDebugMode = nu; }\n\t/**\n\t * This mode defaults to false. When true, DBG #xxx instructions will result in a register dump to System.err.\n\t * @param nu The new mode.\n\t */\n\tpublic void setDebugDumpMode(boolean nu) { debugDumpMode = nu; }\n\tstatic final String[] regnames = new String[]{\"r0\",\"r1\",\"r2\",\"r3\",\"r4\",\"r5\",\"r6\",\"r7\",\"r8\",\"r9\",\"r10\",\"r11\",\"r12\",\"sp\",\"lr\",\"pc\"};\n\tstatic final String[] banked_states = new String[]{};\n\tprivate String toBinary32(int in) {\n\t\tchar out[] = new char[32];\n\t\tfor(int n = 0; n < 32; ++n) {\n\t\t\tout[n] = (((in) >> (31-n)) & 1) != 0 ? '1' : '0';\n\t\t}\n\t\treturn String.copyValueOf(out);\n\t}\n\tpublic void dumpState(PrintStream out) {\n\t\t// modified to use only println to be friendlier to Minecraft's logging diversion\n\t\tout.println(String.format(\"The running instruction would be (roughly) %08X\", pc));\n\t\tout.println(\"Registers:\");\n\t\tString line = null;\n\t\tfor(int n = 0; n < 16; ++n) {\n\t\t\tif(n % 4 == 0) line = \" \";\n\t\t\tline = line + String.format(\"%3s: %08X \", regnames[n], readRegister(n));\n\t\t\tif(n % 4 == 3) out.println(line);\n\t\t}\n\t\tout.println(\"CPSR:\");\n\t\tout.println(\" NZCVQitJ....<ge><.it.>EAIFT<.m.>\");\n\t\tout.println(\" \"+toBinary32(readCPSR()));\n\t}\n\tpublic void dumpExtraState(PrintStream out) {\n\t\tout.println(\"Banked Registers:\");\n\t\tout.println(\" <MODE> <..SP..> NZCVQitJ....<ge><.it.>EAIFT<.m.>\");\n\t\tfor(ProcessorMode mode : ProcessorMode.values()) {\n\t\t\tif(mode.spsrIndex >= 0)\n\t\t\t\tout.printf(\" %6.6s %08X %s\\n\", mode.toString(), sp[mode.spIndex], toBinary32(spsr[mode.spsrIndex]));\n\t\t\telse\n\t\t\t\tout.printf(\" %6.6s %08X xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\\n\", mode.toString(), sp[mode.spIndex]);\n\t\t}\n\t}\n\tpublic Coprocessor getCoprocessor(int id){\n\t\treturn coprocessors[id];\n\t}\n\tprivate int clamp(int x, int min, int max) {\n\t\tif(x < min) return min;\n\t\telse if(x > max) return max;\n\t\telse return x;\n\t}\n}", "public final class PhysicalMemorySpace {\n\tpublic static final class MappedRegion {\n\t\tpublic MappedRegion(long base, MemoryRegion region) {\n\t\t\tthis.base = base;\n\t\t\tthis.end = base + region.getRegionSize();\n\t\t\tthis.region = region;\n\t\t}\n\t\tprivate final long base, end;\n\t\tprivate MemoryRegion region;\n\n\t\tpublic long getBase() {\n\t\t\treturn base;\n\t\t}\n\n\t\tpublic long getEnd() {\n\t\t\treturn end;\n\t\t}\n\n\t\tpublic MemoryRegion getRegion() {\n\t\t\treturn region;\n\t\t}\n\n\t\tpublic void setRegion(MemoryRegion region) {\n\t\t\tthis.region = region;\n\t\t}\n\t}\n\tprivate MappedRegion[] memoryMap = new MappedRegion[0];\n\tprivate MappedRegion getRegion(long address) throws BusErrorException {\n\t\tint t = 0, b = memoryMap.length;\n\t\twhile(b > t) {\n\t\t\tint c = (b - t) / 2 + t;\n\t\t\tMappedRegion region = memoryMap[c];\n\t\t\tif(address >= region.base && address < region.end) return region;\n\t\t\telse if(address < region.base) b = c;\n\t\t\telse t = c + 1;\n\t\t}\n\t\tthrow new BusErrorException(\"failed to get physical region\" , address, BusErrorException.AccessType.UNKNOWN);\n\t}\n\tprivate int accessCycleBill;\n\tpublic final byte readByte(long address) throws BusErrorException, EscapeRetryException {\n\t\tMappedRegion mapping = getRegion(address);\n\t\tbyte ret = mapping.region.readByte(this, address - mapping.base);\n\t\treturn ret;\n\t}\n\tpublic final void writeByte(long address, byte value) throws BusErrorException, EscapeRetryException {\n\t\tMappedRegion mapping = getRegion(address);\n\t\tmapping.region.writeByte(this, address - mapping.base, value);\n\t}\n\tpublic final short readShort(long address, boolean bigEndian) throws BusErrorException, EscapeRetryException {\n\t\tassert((address&1)==0);\n\t\tMappedRegion mapping = getRegion(address);\n\t\tshort ret;\n\t\tif(bigEndian) ret = mapping.region.readShortBE(this, address - mapping.base);\n\t\telse ret = mapping.region.readShortLE(this, address - mapping.base);\n\t\treturn ret;\n\t}\n\tpublic final void writeShort(long address, short value, boolean bigEndian) throws BusErrorException, EscapeRetryException {\n\t\tassert((address&1)==0);\n\t\tMappedRegion mapping = getRegion(address);\n\t\tif(bigEndian) mapping.region.writeShortBE(this, address - mapping.base, value);\n\t\telse mapping.region.writeShortLE(this, address - mapping.base, value);\n\t}\n\tpublic final int readInt(long address, boolean bigEndian) throws BusErrorException, EscapeRetryException {\n\t\tassert((address&3)==0);\n\t\tMappedRegion mapping = getRegion(address);\n\t\tint ret;\n\t\tif(bigEndian) ret = mapping.region.readIntBE(this, address - mapping.base);\n\t\telse ret = mapping.region.readIntLE(this, address - mapping.base);\n\t\treturn ret;\n\t}\n\tpublic final void writeInt(long address, int value, boolean bigEndian) throws BusErrorException, EscapeRetryException {\n\t\tassert((address&3)==0);\n\t\tMappedRegion mapping = getRegion(address);\n\t\tif(bigEndian) mapping.region.writeIntBE(this, address - mapping.base, value);\n\t\telse mapping.region.writeIntLE(this, address - mapping.base, value);\n\t}\n\tpublic final int settleAccessBill() {\n\t\tint ret = accessCycleBill;\n\t\taccessCycleBill = 0;\n\t\treturn ret;\n\t}\n\tpublic final void addToBill(int i) {\n\t\tassert(i > 0);\n\t\taccessCycleBill += i;\n\t}\n\tpublic final void mapRegion(int _address, MemoryRegion region) {\n\t\tlong address = _address & 0xFFFFFFFFL;\n\t\tMappedRegion[] newMap = new MappedRegion[memoryMap.length+1];\n\t\tint i = 0;\n\t\tfor(; i < memoryMap.length; ++i) {\n\t\t\tMappedRegion it = memoryMap[i];\n\t\t\tif(it.base > address) break;\n\t\t\tnewMap[i] = it;\n\t\t}\n\t\tnewMap[i] = new MappedRegion(address, region);\n\t\tfor(; i < memoryMap.length; ++i) {\n\t\t\tMappedRegion it = memoryMap[i];\n\t\t\tnewMap[i+1] = it;\n\t\t}\n\t\tmemoryMap = newMap;\n\t}\n\tpublic final void unmapRegion(int _address, MemoryRegion region) {\n\t\tlong address = _address & 0xFFFFFFFFL;\n\t\tArrayList<MappedRegion> newMap = new ArrayList<MappedRegion>(memoryMap.length);\n\t\tfor(MappedRegion it : memoryMap) {\n\t\t\tif(it.base != address || (region == null || it.region != region)) newMap.add(it);\n\t\t}\n\t\tmemoryMap = newMap.toArray(new MappedRegion[newMap.size()]);\n\t}\n\tpublic final void unmapAllRegions() {\n\t\tmemoryMap = new MappedRegion[0];\n\t}\n\t\n\tpublic List<MappedRegion> getMappedRegions() {\n\t\treturn Arrays.asList(memoryMap);\n\t}\n}", "public class UndefinedException extends Exception {\n\tstatic final long serialVersionUID = 1;\n\tpublic UndefinedException() { super(); }\n\tpublic UndefinedException(Throwable e) { super(e); }\n}", "public class UnimplementedInstructionException extends RuntimeException {\n\tstatic final long serialVersionUID = 1;\n\tprivate String insn;\n\tprivate int iword;\n\tprivate short iword1, iword2;\n\tpublic static enum Type {\n\t\tARM, THUMB16, THUMB32, NONE\n\t}\n\tprivate Type type;\n\tpublic UnimplementedInstructionException(String insn) {\n\t\tthis.insn = insn;\n\t\tthis.type = Type.NONE;\n\t}\n\tpublic UnimplementedInstructionException(int iword, String insn) {\n\t\tthis.insn = insn;\n\t\tthis.iword = iword;\n\t\tthis.type = Type.ARM;\n\t}\n\tpublic UnimplementedInstructionException(short iword, String insn) {\n\t\tthis.insn = insn;\n\t\tthis.iword1 = iword;\n\t\tthis.type = Type.THUMB16;\n\t}\n\tpublic UnimplementedInstructionException(short iword1, short iword2, String insn) {\n\t\tthis.insn = insn;\n\t\tthis.iword1 = iword1;\n\t\tthis.iword2 = iword2;\n\t\tthis.type = Type.THUMB32;\n\t}\n\t@Override\n\tpublic String toString() {\n\t\tswitch(type) {\n\t\tdefault: return \"Unimplemented instruction\";\n\t\tcase NONE: return String.format(\"Unimplemented instruction: %s\", insn);\n\t\tcase ARM: return String.format(\"Unimplemented ARM instruction: %s (%08X)\", insn, iword);\n\t\tcase THUMB16: return String.format(\"Unimplemented Thumb16 instruction: %s (%04X)\", insn, iword1);\n\t\tcase THUMB32: return String.format(\"Unimplemented Thumb32 instruction: %s (%04X %04X)\", insn, iword1, iword2);\n\t\t}\n\t}\n\tpublic String getInstruction() { return insn; }\n\tpublic Type getType() { return type; }\n\tpublic int getARMWord() { if(type != Type.ARM) throw new NullPointerException(); return iword; }\n\tpublic short getThumbWord() { if(type != Type.THUMB16) throw new NullPointerException(); return iword1; }\n\tpublic short getThumbWord1() { if(type != Type.THUMB32) throw new NullPointerException(); return iword1; }\n\tpublic short getThumbWord2() { if(type != Type.THUMB32) throw new NullPointerException(); return iword2; }\n}", "public static class InvalidSpecException extends Exception {\n\tpublic static final long serialVersionUID = 1;\n}" ]
import java.io.EOFException; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.List; import name.bizna.jarm.AlignmentException; import name.bizna.jarm.BusErrorException; import name.bizna.jarm.ByteArrayRegion; import name.bizna.jarm.CPU; import name.bizna.jarm.PhysicalMemorySpace; import name.bizna.jarm.UndefinedException; import name.bizna.jarm.UnimplementedInstructionException; import name.bizna.jarmtest.TestSpec.InvalidSpecException;
package name.bizna.jarmtest; public class TestDirectory { public static final String CODE_FILENAME = "code.elf"; public static final int MAX_PROGRAM_SPACE = 1<<30; private File path; private String name; private byte[] programBytes = null, hiBytes = null; private boolean littleEndian = false, hasEntryPoint = false; private int entryPoint = 0; private static class ProgramHeaderEntry { int p_type; int p_offset; int p_vaddr; // int p_paddr; int p_filesz; int p_memsz; // int p_flags; // int p_align; public ProgramHeaderEntry(ByteBuffer buf) { p_type = buf.getInt(); p_offset = buf.getInt(); p_vaddr = buf.getInt(); /*p_paddr =*/ buf.getInt(); p_filesz = buf.getInt(); p_memsz = buf.getInt(); /*p_flags = buf.getInt();*/ /*p_align = buf.getInt();*/ } } private void loadProgram(File path, String id) throws NonLoadableFileException { RandomAccessFile f = null; programBytes = null; hiBytes = null; littleEndian = false; entryPoint = 0; hasEntryPoint = false; try { f = new RandomAccessFile(path, "r"); byte[] headerReadArray = new byte[52]; ByteBuffer headerReadBuf = ByteBuffer.wrap(headerReadArray); f.read(headerReadArray); /*** Read the Elf32_Ehdr ***/ /* EI_MAG0-3 = backspace, ELF */ if(headerReadBuf.getInt() != 0x7F454C46) throw new NonLoadableFileException("not an ELF file", id); /* EI_CLASS = ELFCLASS32 */ if(headerReadBuf.get() != 1) throw new NonLoadableFileException("not 32-bit", id); /* EI_DATA = ELFDATA2LSB or ELFDATA2MSB */ final byte EI_DATA = headerReadBuf.get(); switch(EI_DATA) { case 1: // ELFDATA2LSB littleEndian = true; break; case 2: // ELFDATA2MSB // big endian by default break; default: throw new NonLoadableFileException("neither little-endian nor big-endian", id); } /* EI_VERSION = 1 */ if(headerReadBuf.get() != 1) throw new NonLoadableFileException("not version 1", id); /* Remainder of e_ident ignored */ if(littleEndian) headerReadBuf.order(ByteOrder.LITTLE_ENDIAN); headerReadBuf.position(16); /* e_type = ET_EXEC */ if(headerReadBuf.getShort() != 2) throw new NonLoadableFileException("not executable", id); /* e_machine = EM_ARM */ if(headerReadBuf.getShort() != 40) throw new NonLoadableFileException("not ARM", id); /* e_version = 1 */ if(headerReadBuf.getInt() != 1) throw new NonLoadableFileException("not version 1", id); /* e_entry */ entryPoint = headerReadBuf.getInt(); /* e_phoff */ int e_phoff = headerReadBuf.getInt(); if(e_phoff < 52) throw new NonLoadableFileException("impossibly small e_phoff", id); /* e_shoff ignored */ headerReadBuf.getInt(); /* e_flags */ int e_flags = headerReadBuf.getInt(); /* only accept a zero entry point if e_flags contains EF_ARM_HASENTRY (0x00000002) */ if((e_flags & 2) != 0 && entryPoint == 0) hasEntryPoint = false; else hasEntryPoint = true; /* e_ehsize */ int e_ehsize = headerReadBuf.getShort() & 0xFFFF; if(e_ehsize < 52) throw new NonLoadableFileException("has an invalid e_ehsize field", id); /* e_phentsize */ int e_phentsize = headerReadBuf.getShort() & 0xFFFF; if(e_phentsize < 32) throw new NonLoadableFileException("has an invalid e_phentsize field", id); /* e_phnum */ int e_phnum = headerReadBuf.getShort() & 0xFFFF; if(e_phnum == 0 || e_phnum == 65535) throw new NonLoadableFileException("contains no program entries", id); /* e_shentsize, e_shnum, e_shstrndx are ignored */ ProgramHeaderEntry phents[] = new ProgramHeaderEntry[e_phnum]; for(int n = 0; n < e_phnum; ++n) { f.seek(e_phoff + n * e_phentsize); headerReadBuf.rewind(); f.read(headerReadArray, 0, 32); phents[n] = new ProgramHeaderEntry(headerReadBuf); } int memtop = 0; for(ProgramHeaderEntry phent : phents) { // PT_LOAD = 1 if(phent.p_type != 1) continue; if(phent.p_vaddr < 0 && phent.p_vaddr >= -65536) { // it's a high section if(phent.p_memsz > -phent.p_vaddr) throw new NonLoadableFileException("high section is too long", id); if(hiBytes == null) { try { hiBytes = new byte[65536]; } catch(OutOfMemoryError e) { throw new NonLoadableFileException("can't even allocate 64k for hiBytes, please increase the maximum memory size of the Java VM", id); } } } else { if(phent.p_vaddr < 0 || phent.p_vaddr >= MAX_PROGRAM_SPACE) throw new NonLoadableFileException("virtual address out of range", id); if(phent.p_memsz >= MAX_PROGRAM_SPACE) throw new NonLoadableFileException("absurdly long section", id); int phent_top = phent.p_vaddr + phent.p_memsz; if(phent_top < 0 || phent_top > MAX_PROGRAM_SPACE) throw new NonLoadableFileException("absurdly long section", id); if(phent_top > memtop) memtop = phent_top; } } assert(memtop <= MAX_PROGRAM_SPACE); try { programBytes = new byte[memtop]; } catch(OutOfMemoryError e) { throw new NonLoadableFileException("too big to fit in memory, please increase the maximum memory size of the Java VM", id); } for(ProgramHeaderEntry phent : phents) { if(phent.p_type != 1) continue; if(phent.p_filesz > 0) { f.seek(phent.p_offset); if(phent.p_vaddr >= -65536 && phent.p_vaddr < 0) f.read(hiBytes, phent.p_vaddr + 65536, phent.p_filesz); else f.read(programBytes, phent.p_vaddr, phent.p_filesz); } /* byte arrays are zero-filled when created, so we don't have to zero-fill */ } } catch(EOFException e) { throw new NonLoadableFileException("unexpected EOF", id); } catch(FileNotFoundException e) { throw new NonLoadableFileException("file not found", id); } catch(IOException e) { throw new NonLoadableFileException("IO error", id); } finally { if(f != null) try { f.close(); } catch(IOException e) { e.printStackTrace(); } } } public TestDirectory(File path, String name) { this.path = path; this.name = name; } public static boolean isValidTestDir(File dir) { return new File(dir, CODE_FILENAME).exists(); } public boolean runTestWithSpec(CPU cpu, File specFile, String specId, List<String> subtestFailureList) { try { TestSpec spec; try { spec = new TestSpec(specFile); } catch(InvalidSpecException e) { throw new NonLoadableFileException("invalid spec", specId); } catch(EOFException e) { throw new NonLoadableFileException("unexpected EOF", specId); } catch(FileNotFoundException e) { throw new NonLoadableFileException("file not found", specId); } catch(IOException e) { throw new NonLoadableFileException("IO error", specId); } spec.applyInitialStateAndReset(cpu, littleEndian); if(hasEntryPoint) cpu.loadPC(entryPoint); cpu.zeroBudget(false); try { cpu.execute(1<<30); }
catch(BusErrorException e) { /* NOTREACHED */ }
1
janrain/engage.android
Jump/src/com/janrain/android/engage/JREngage.java
[ "public class JRProvider implements Serializable {\n public static final String KEY_FRIENDLY_NAME = \"friendly_name\";\n public static final String KEY_INPUT_PROMPT = \"input_prompt\";\n public static final String KEY_OPENID_IDENTIFIER = \"openid_identifier\";\n public static final String KEY_URL = \"url\";\n public static final String KEY_REQUIRES_INPUT = \"requires_input\";\n public static final String KEY_SOCIAL_SHARING_PROPERTIES = \"social_sharing_properties\";\n public static final String KEY_COOKIE_DOMAINS = \"cookie_domains\";\n public static final String KEY_ANDROID_WEBVIEW_OPTIONS = \"android_webview_options\";\n\n private static final String TAG = JRProvider.class.getSimpleName();\n\n private static Map<String, SoftReference<Drawable>> provider_list_icon_drawables =\n Collections.synchronizedMap(new HashMap<String, SoftReference<Drawable>>());\n\n // Suppressed because this inner class is not expected to be serialized\n @SuppressWarnings(\"serial\")\n private final static Map<String, Integer> provider_list_icon_resources =\n new HashMap<String, Integer>() {\n {\n put(\"icon_bw_facebook\", R.drawable.jr_icon_bw_facebook);\n put(\"icon_bw_linkedin\", R.drawable.jr_icon_bw_linkedin);\n put(\"icon_bw_myspace\", R.drawable.jr_icon_bw_myspace);\n put(\"icon_bw_twitter\", R.drawable.jr_icon_bw_twitter);\n put(\"icon_bw_yahoo\", R.drawable.jr_icon_bw_yahoo);\n\n put(\"icon_aol\", R.drawable.jr_icon_aol);\n put(\"icon_blogger\", R.drawable.jr_icon_blogger);\n put(\"icon_facebook\", R.drawable.jr_icon_facebook);\n put(\"icon_flickr\", R.drawable.jr_icon_flickr);\n put(\"icon_foursquare\", R.drawable.jr_icon_foursquare);\n put(\"icon_google\", R.drawable.jr_icon_google);\n put(\"icon_hyves\", R.drawable.jr_icon_hyves);\n put(\"icon_linkedin\", R.drawable.jr_icon_linkedin);\n put(\"icon_live_id\", R.drawable.jr_icon_live_id);\n put(\"icon_livejournal\", R.drawable.jr_icon_livejournal);\n put(\"icon_myopenid\", R.drawable.jr_icon_myopenid);\n put(\"icon_myspace\", R.drawable.jr_icon_myspace);\n put(\"icon_netlog\", R.drawable.jr_icon_netlog);\n put(\"icon_openid\", R.drawable.jr_icon_openid);\n put(\"icon_orkut\", R.drawable.jr_icon_orkut);\n put(\"icon_paypal\", R.drawable.jr_icon_paypal);\n put(\"icon_salesforce\", R.drawable.jr_icon_salesforce);\n put(\"icon_twitter\", R.drawable.jr_icon_twitter);\n put(\"icon_verisign\", R.drawable.jr_icon_verisign);\n put(\"icon_vzn\", R.drawable.jr_icon_vzn);\n put(\"icon_wordpress\", R.drawable.jr_icon_wordpress);\n put(\"icon_yahoo\", R.drawable.jr_icon_yahoo);\n }\n };\n\n private static Map<String, SoftReference<Drawable>> provider_logo_drawables =\n Collections.synchronizedMap(new HashMap<String, SoftReference<Drawable>>());\n\n // Suppressed because this inner class is not expected to be serialized\n @SuppressWarnings(\"serial\")\n private final static HashMap<String, Integer> provider_logo_resources =\n new HashMap<String, Integer>() {\n {\n put(\"logo_aol\", R.drawable.jr_logo_aol);\n put(\"logo_blogger\", R.drawable.jr_logo_blogger);\n put(\"logo_facebook\", R.drawable.jr_logo_facebook);\n put(\"logo_flickr\", R.drawable.jr_logo_flickr);\n put(\"logo_foursquare\", R.drawable.jr_logo_foursquare);\n put(\"logo_google\", R.drawable.jr_logo_google);\n put(\"logo_hyves\", R.drawable.jr_logo_hyves);\n put(\"logo_linkedin\", R.drawable.jr_logo_linkedin);\n put(\"logo_live_id\", R.drawable.jr_logo_live_id);\n put(\"logo_livejournal\", R.drawable.jr_logo_livejournal);\n put(\"logo_myopenid\", R.drawable.jr_logo_myopenid);\n put(\"logo_myspace\", R.drawable.jr_logo_myspace);\n put(\"logo_netlog\", R.drawable.jr_logo_netlog);\n put(\"logo_openid\", R.drawable.jr_logo_openid);\n put(\"logo_orkut\", R.drawable.jr_logo_orkut);\n put(\"logo_paypal\", R.drawable.jr_logo_paypal);\n put(\"logo_salesforce\", R.drawable.jr_logo_salesforce);\n put(\"logo_twitter\", R.drawable.jr_logo_twitter);\n put(\"logo_verisign\", R.drawable.jr_logo_verisign);\n put(\"logo_vzn\", R.drawable.jr_logo_vzn);\n put(\"logo_yahoo\", R.drawable.jr_logo_yahoo);\n }\n };\n\n private String mName;\n private String mFriendlyName;\n private String mInputHintText;\n private String mUserInputDescriptor;\n private boolean mRequiresInput;\n private String mOpenIdentifier;\n private String mStartAuthenticationUrl;\n private List<String> mCookieDomains;\n private JRDictionary mSocialSharingProperties;\n private JRDictionary mWebViewOptions;\n\n private transient boolean mForceReauth; // <- these two user parameters get preserved\n private transient String mUserInput = \"\"; // <- across cached provider reloads\n private transient boolean mCurrentlyDownloading;\n\n public JRProvider(String name, JRDictionary dictionary) {\n mName = name;\n mFriendlyName = dictionary.getAsString(KEY_FRIENDLY_NAME);\n mInputHintText = dictionary.getAsString(KEY_INPUT_PROMPT);\n mOpenIdentifier = dictionary.getAsString(KEY_OPENID_IDENTIFIER);\n mStartAuthenticationUrl = dictionary.getAsString(KEY_URL);\n mRequiresInput = dictionary.getAsBoolean(KEY_REQUIRES_INPUT);\n mCookieDomains = dictionary.getAsListOfStrings(KEY_COOKIE_DOMAINS, true);\n mSocialSharingProperties = dictionary.getAsDictionary(KEY_SOCIAL_SHARING_PROPERTIES);\n mWebViewOptions = dictionary.getAsDictionary(KEY_ANDROID_WEBVIEW_OPTIONS, true);\n\n loadDynamicVariables();\n\n if (mRequiresInput) {\n String[] arr = mInputHintText.split(\" \");\n ArrayList<String> shortList = new ArrayList<String>();\n shortList.addAll(Arrays.asList(arr).subList((arr.length - 2), arr.length));\n mUserInputDescriptor = TextUtils.join(\" \", shortList);\n } else {\n mUserInputDescriptor = \"\";\n }\n\n // Called in the constructor to preemptively download missing icons\n getProviderLogo(JREngage.getApplicationContext());\n }\n\n /**\n * Not null\n */\n public List<String> getCookieDomains() {\n return mCookieDomains;\n }\n\n public String getName() {\n return mName;\n }\n\n public String getFriendlyName() {\n return mFriendlyName;\n }\n\n public String getUserInputHint() {\n return mInputHintText;\n }\n\n public String getUserInputDescriptor() {\n return mUserInputDescriptor;\n }\n\n public boolean requiresInput() {\n return mRequiresInput;\n }\n\n public String getOpenIdentifier() {\n return mOpenIdentifier;\n }\n\n public String getStartAuthenticationUrl() {\n return mStartAuthenticationUrl;\n }\n\n public JRDictionary getSocialSharingProperties() {\n return mSocialSharingProperties;\n }\n\n public JRDictionary getWebViewOptions() {\n return mWebViewOptions;\n }\n\n public boolean getForceReauth() {\n return mForceReauth;\n }\n\n public void setForceReauth(boolean forceReauth) {\n this.mForceReauth = forceReauth;\n\n PrefUtils.putBoolean(PrefUtils.KEY_JR_FORCE_REAUTH + this.mName, this.mForceReauth);\n }\n\n public String getUserInput() {\n return mUserInput;\n }\n\n public void setUserInput(String userInput) {\n mUserInput = userInput;\n\n PrefUtils.putString(PrefUtils.KEY_JR_USER_INPUT + this.mName, this.mUserInput);\n }\n\n private Drawable getDrawable(Context c,\n String drawableName,\n Map<String, SoftReference<Drawable>> drawableMap,\n Map<String, Integer> resourceMap) {\n if (drawableMap.containsKey(drawableName)) {\n Drawable d = drawableMap.get(drawableName).get();\n if (d != null) {\n return d;\n } else {\n drawableMap.remove(drawableName);\n }\n }\n\n if (resourceMap.containsKey(drawableName)) {\n Drawable r = c.getResources().getDrawable(resourceMap.get(drawableName));\n drawableMap.put(drawableName, new SoftReference<Drawable>(r));\n return r;\n }\n\n if (AndroidUtils.isCupcake()) {\n // 1.5 can't handle programmatic XHDPI resource instantiation\n return c.getResources().getDrawable(R.drawable.jr_icon_unknown);\n }\n\n try {\n String iconFileName = \"providericon~\" + drawableName + \".png\";\n\n Bitmap icon = BitmapFactory.decodeStream(c.openFileInput(iconFileName));\n if (icon != null) {\n // Downloaded icons are all at xhdpi, but Android 2.1 doesn't have the\n // DENSITY_XHIGH constant defined yet. But it does the right thing\n // if you pass in the DPI as an int\n\n AndroidUtils.bitmapSetDensity(icon, 320);\n return AndroidUtils.newBitmapDrawable(c, icon);\n } else {\n c.deleteFile(iconFileName);\n }\n } catch (FileNotFoundException ignore) {\n }\n\n downloadIcons(c);\n return c.getResources().getDrawable(R.drawable.jr_icon_unknown);\n }\n\n public Drawable getProviderIcon(Context c) {\n return getDrawable(c, \"icon_\" + mName, provider_list_icon_drawables, provider_list_icon_resources);\n }\n\n public Drawable getProviderLogo(Context c) {\n return getDrawable(c, \"logo_\" + mName, provider_logo_drawables, provider_logo_resources);\n }\n\n public Drawable getTabSpecIndicatorDrawable(Context c) {\n Drawable colorIcon = getDrawable(c,\n \"icon_\" + mName,\n provider_list_icon_drawables,\n provider_list_icon_resources);\n\n Drawable bwIcon = getDrawable(c,\n \"icon_bw_\" + mName,\n provider_list_icon_drawables,\n provider_list_icon_resources);\n\n StateListDrawable sld = new StateListDrawable();\n sld.addState(new int[]{android.R.attr.state_selected}, colorIcon);\n sld.addState(new int[]{}, bwIcon);\n\n return sld;\n }\n\n @SuppressWarnings({\"unchecked\"})\n private void downloadIcons(final Context c) {\n LogUtils.logd(TAG, \"downloadIcons: \" + mName);\n\n synchronized (this) {\n if (mCurrentlyDownloading) return;\n else mCurrentlyDownloading = true;\n }\n\n final String[] iconFileNames = {\n \"icon_\" + mName + \".png\",\n \"icon_bw_\" + mName + \".png\",\n \"logo_\" + mName + \".png\"\n };\n\n ThreadUtils.executeInBg(new Runnable() {\n public void run() {\n for (String iconFileName : iconFileNames) {\n FileOutputStream fos = null;\n if (Arrays.asList(c.fileList()).contains(\"providericon~\" + iconFileName)) continue;\n\n try {\n URL url = new URL(JRSession.getInstance().getEngageBaseUrl()\n + \"/cdn/images/mobile_icons/android/\" + iconFileName);\n InputStream is = url.openStream();\n fos = c.openFileOutput(\"providericon~\" + iconFileName, Context.MODE_PRIVATE);\n\n byte buffer[] = new byte[1000];\n int code;\n while ((code = is.read(buffer, 0, buffer.length)) > 0) fos.write(buffer, 0, code);\n\n fos.close();\n } catch (MalformedURLException e) {\n LogUtils.logd(TAG, e.toString(), e);\n } catch (IOException e) {\n LogUtils.logd(TAG, e.toString(), e);\n } finally {\n if (fos != null) {\n try {\n fos.close();\n } catch (IOException ignore) {\n }\n }\n }\n }\n mCurrentlyDownloading = false;\n }\n });\n }\n\n public void loadDynamicVariables() {\n mUserInput = PrefUtils.getString(PrefUtils.KEY_JR_USER_INPUT + mName, \"\");\n mForceReauth = PrefUtils.getBoolean(PrefUtils.KEY_JR_FORCE_REAUTH + mName, false);\n }\n\n public String toString() {\n return mName;\n }\n\n private Resources getResources() {\n return JREngage.getApplicationContext().getResources();\n }\n\n /**\n * @param lighter If true then return the blend of the providers color at 20% alpha over a white\n * background\n * @return The color\n * @internal\n */\n public int getProviderColor(boolean lighter) {\n Exception error;\n try {\n List colorList = (List) getSocialSharingProperties().get(\"color_values\");\n\n int finalColor = 255; // Full alpha\n for (int i = 0; i < 3; i++) {\n finalColor <<= 8;\n int newByte = (int) (((Double) colorList.get(i)) * 255.0);\n if (lighter) newByte = (int) (newByte * 0.2d + 255 * 0.8d);\n\n // protect against floating point imprecision overflowing one byte:\n finalColor += Math.min(newByte, 255);\n }\n\n return finalColor;\n } catch (ClassCastException e) {\n error = e;\n } catch (IndexOutOfBoundsException e) {\n error = e;\n }\n\n throwDebugException(new RuntimeException(\"Error parsing provider color\", error));\n return getResources().getColor(R.color.jr_janrain_darkblue_lightened);\n }\n\n public static String getLocalizedName(String conflictingIdentityProvider) {\n if (conflictingIdentityProvider.equals(\"capture\")) {\n return JREngage.getApplicationContext().getString(R.string.jr_traditional_account_name);\n }\n return JRSession.getInstance().getProviderByName(conflictingIdentityProvider).getFriendlyName();\n }\n}", "public class JRSession implements JRConnectionManagerDelegate {\n private static final String ARCHIVE_ALL_PROVIDERS = \"allProviders\";\n private static final String ARCHIVE_AUTH_PROVIDERS = \"authProviders\";\n private static final String ARCHIVE_SHARING_PROVIDERS = \"sharingProviders\";\n private static final String ARCHIVE_AUTH_USERS_BY_PROVIDER = \"jrAuthenticatedUsersByProvider\";\n\n private static final String RPXNOW_BASE_URL = \"https://rpxnow.com\";\n private static String mEngageBaseUrl = RPXNOW_BASE_URL;\n private static final String UNFORMATTED_CONFIG_URL =\n \"%s/openid/mobile_config_and_baseurl?appId=%s&device=android&app_name=%s&version=%s\";\n private static final String TAG_GET_CONFIGURATION = \"getConfiguration\";\n\n private static JRSession sInstance;\n public static final String USERDATA_ACTION_KEY = \"action\";\n public static final String USERDATA_ACTION_CALL_TOKEN_URL = \"callTokenUrl\";\n public static final String USERDATA_TOKEN_URL_KEY = \"tokenUrl\";\n public static final String USERDATA_PROVIDER_NAME_KEY = \"providerName\";\n public static final String USERDATA_ACTIVITY_KEY = \"activity\";\n public static final String USERDATA_ACTION_SHARE_ACTIVITY = \"shareActivity\";\n\n private List<JRSessionDelegate> mDelegates;\n\n private JRProvider mCurrentlyAuthenticatingProvider;\n private JRProvider mCurrentlyPublishingProvider;\n\n private String mReturningAuthProvider;\n private String mReturningSharingProvider;\n\n private Map<String, JRProvider> mAllProviders;\n private List<String> mAuthProviders;\n private List<String> mEnabledAuthenticationProviders;\n private List<String> mEnabledSharingProviders;\n private List<String> mSharingProviders;\n private Map<String, JRAuthenticatedUser> mAuthenticatedUsersByProvider;\n\n private JRActivityObject mActivity;\n private String mTokenUrl;\n private String mAppId;\n private String mRpBaseUrl;\n private String mUrlEncodedAppName;\n private String mUniqueIdentifier;\n\n private boolean mConfigDone = false;\n private String mOldEtag;\n private String mSavedConfigurationBlock;\n private String mSavedEtag;\n private String mNewEtag;\n private String mUrlEncodedLibraryVersion;\n\n private boolean mHidePoweredBy;\n private boolean mAlwaysForceReauth;\n private boolean mSkipLandingPage;\n private int mUiShowingCount;\n\n private JREngageError mError;\n\n public static JRSession getInstance() {\n return sInstance;\n }\n\n public static JRSession getInstance(String appId, String tokenUrl, JRSessionDelegate delegate) {\n if (sInstance != null) {\n if (sInstance.isUiShowing()) {\n LogUtils.loge(\"Cannot reinitialize JREngage while its UI is showing\");\n } else {\n LogUtils.logd(\"reinitializing, registered delegates will be unregistered\");\n sInstance.initialize(appId, tokenUrl, delegate);\n }\n } else {\n LogUtils.logd(\"returning new instance.\");\n sInstance = new JRSession(appId, tokenUrl, delegate);\n }\n\n return sInstance;\n }\n\n private JRSession(String appId, String tokenUrl, JRSessionDelegate delegate) {\n initialize(appId, tokenUrl, delegate);\n }\n\n /* We runtime type check the deserialized generics so we can safely ignore these unchecked\n * assignment warnings. */\n @SuppressWarnings(\"unchecked\")\n private void initialize(String appId, String tokenUrl, JRSessionDelegate delegate) {\n LogUtils.logd(\"initializing instance.\");\n\n // for configurability to test against e.g. staging\n String t = StringUtils.trim(AndroidUtils.readAsset(getApplicationContext(), \"engage_base_url.txt\"));\n if (t != null) mEngageBaseUrl = t;\n\n mDelegates = new ArrayList<JRSessionDelegate>();\n mDelegates.add(delegate);\n\n mAppId = appId;\n mTokenUrl = tokenUrl;\n mUniqueIdentifier = this.getUniqueIdentifier();\n\n ApplicationInfo ai = AndroidUtils.getApplicationInfo();\n String appName = getApplicationContext().getPackageManager().getApplicationLabel(ai).toString();\n appName += \":\" + getApplicationContext().getPackageName();\n mUrlEncodedAppName = AndroidUtils.urlEncode(appName);\n mUrlEncodedLibraryVersion =\n AndroidUtils.urlEncode(getApplicationContext().getString(R.string.jr_git_describe));\n\n try {\n if (!mUrlEncodedLibraryVersion.equals(PrefUtils.getString(PrefUtils.KEY_JR_ENGAGE_LIBRARY_VERSION,\n \"\"))) {\n // If the library versions don't match start with fresh state in order to break out of\n // any invalid state.\n throw new Archiver.LoadException(\"New library version with old serialized state\");\n }\n\n /* load the last used auth and social providers */\n mReturningSharingProvider = PrefUtils.getString(PrefUtils.KEY_JR_LAST_USED_SHARING_PROVIDER, \"\");\n mReturningAuthProvider = PrefUtils.getString(PrefUtils.KEY_JR_LAST_USED_AUTH_PROVIDER, \"\");\n\n /* Load the library state from disk */\n mAuthenticatedUsersByProvider = Archiver.load(ARCHIVE_AUTH_USERS_BY_PROVIDER);\n mAllProviders = Archiver.load(ARCHIVE_ALL_PROVIDERS);\n\n /* Fix up the provider objects with data that isn't serialized along with them */\n for (Object provider : mAllProviders.values()) ((JRProvider)provider).loadDynamicVariables();\n\n /* Load the list of auth providers */\n mAuthProviders = Archiver.load(ARCHIVE_AUTH_PROVIDERS);\n for (Object v : mAuthProviders) {\n if (!(v instanceof String)) throw new Archiver.LoadException(\"Non String in mAuthProviders\");\n }\n LogUtils.logd(\"auth providers: [\" + TextUtils.join(\",\", mAuthProviders) + \"]\");\n\n /* Load the list of social providers */\n mSharingProviders = Archiver.load(ARCHIVE_SHARING_PROVIDERS);\n for (Object v : mSharingProviders) {\n if (!(v instanceof String)) {\n throw new Archiver.LoadException(\"Non String in mSharingProviders\");\n }\n }\n LogUtils.logd(\"sharing providers: [\" + TextUtils.join(\",\", mSharingProviders) + \"]\");\n\n /* Load the RP's base url */\n mRpBaseUrl = PrefUtils.getString(PrefUtils.KEY_JR_RP_BASE_URL, \"\");\n\n /* Figure out of we're suppose to hide the powered by line */\n mHidePoweredBy = PrefUtils.getBoolean(PrefUtils.KEY_JR_HIDE_POWERED_BY, false);\n\n /* If the configuration for this RP has changed, the etag will have changed, and we need\n * to update our current configuration information. */\n mOldEtag = PrefUtils.getString(PrefUtils.KEY_JR_CONFIGURATION_ETAG, \"\");\n //throw new Archiver.LoadException(null);\n } catch (Archiver.LoadException e) {\n //LogUtils.logd(\"LoadException loading serialized configuration, initializing from empty state. \" +\n // \" Version: \" + mUrlEncodedLibraryVersion + \" LoadException: \" +\n // e.getStackTrace()[0].toString() + \" Nested exception: \" + e.getCause());\n /* Blank slate */\n mAuthenticatedUsersByProvider = new HashMap<String, JRAuthenticatedUser>();\n Archiver.asyncSave(ARCHIVE_AUTH_USERS_BY_PROVIDER, mAuthenticatedUsersByProvider);\n\n // Note that these values are removed from the settings when resetting state to prevent\n // uninitialized state from being read on startup as valid state\n mAllProviders = new HashMap<String, JRProvider>();\n Archiver.delete(ARCHIVE_ALL_PROVIDERS);\n mAuthProviders = new ArrayList<String>();\n Archiver.delete(ARCHIVE_AUTH_PROVIDERS);\n mSharingProviders = new ArrayList<String>();\n Archiver.delete(ARCHIVE_SHARING_PROVIDERS);\n mRpBaseUrl = \"\";\n PrefUtils.remove(PrefUtils.KEY_JR_RP_BASE_URL);\n mHidePoweredBy = true;\n PrefUtils.remove(PrefUtils.KEY_JR_HIDE_POWERED_BY);\n mOldEtag = \"\";\n PrefUtils.remove(PrefUtils.KEY_JR_CONFIGURATION_ETAG);\n \n // Note that these values are not removed from the Prefs, they can't result in invalid state\n // (The library is accepting of values not belonging to the set of enabled providers.)\n mReturningAuthProvider = PrefUtils.getString(PrefUtils.KEY_JR_LAST_USED_AUTH_PROVIDER, null);\n mReturningSharingProvider = PrefUtils.getString(PrefUtils.KEY_JR_LAST_USED_SHARING_PROVIDER,\n null);\n //mConfigDone = false;\n }\n\n mError = startGetConfiguration();\n }\n\n public JREngageError getError() {\n return mError;\n }\n\n public JRActivityObject getJRActivity() {\n return mActivity;\n }\n\n public void setJRActivity(JRActivityObject activity) {\n mActivity = activity;\n }\n\n public void setSkipLandingPage(boolean skipLandingPage) {\n mSkipLandingPage = skipLandingPage;\n }\n\n public boolean getSkipLandingPage() {\n return mSkipLandingPage;\n }\n\n public boolean getAlwaysForceReauth() {\n return mAlwaysForceReauth;\n }\n\n public void setAlwaysForceReauth(boolean force) {\n mAlwaysForceReauth = force;\n }\n\n public void setTokenUrl(String tokenUrl) {\n mTokenUrl = tokenUrl;\n }\n\n public JRProvider getCurrentlyAuthenticatingProvider() {\n return mCurrentlyAuthenticatingProvider;\n }\n\n public void setCurrentlyAuthenticatingProvider(JRProvider provider) {\n mCurrentlyAuthenticatingProvider = provider;\n }\n\n public ArrayList<JRProvider> getAuthProviders() {\n ArrayList<JRProvider> providerList = new ArrayList<JRProvider>();\n\n if ((mAuthProviders != null) && (mAuthProviders.size() > 0)) {\n for (String name : mAuthProviders) {\n // Filter by enabled provider list if available\n if (mEnabledAuthenticationProviders != null &&\n !mEnabledAuthenticationProviders.contains(name)) continue;\n providerList.add(mAllProviders.get(name));\n }\n }\n\n return providerList;\n }\n\n /**\n * Gets the configured and enabled sharing providers\n *\n * @return an ArrayList&lt;Provider>, does not return null.\n */\n public ArrayList<JRProvider> getSharingProviders() {\n ArrayList<JRProvider> providerList = new ArrayList<JRProvider>();\n\n if ((mSharingProviders != null) && (mSharingProviders.size() > 0)) {\n for (String name : mSharingProviders) {\n // Filter by enabled provider list if available\n if (mEnabledSharingProviders != null &&\n !mEnabledSharingProviders.contains(name)) continue;\n providerList.add(mAllProviders.get(name));\n }\n }\n\n return providerList;\n }\n\n public String getReturningAuthProvider() {\n /* This is here so that when a calling application sets mSkipLandingPage, the dialog always opens\n * to the providers list. (See JRProviderListFragment.onCreate for an explanation of the flow control\n * when there's a \"returning provider.\") */\n if (mSkipLandingPage)\n return null;\n\n return mReturningAuthProvider;\n }\n\n public void setReturningAuthProvider(String returningAuthProvider) {\n if (TextUtils.isEmpty(returningAuthProvider)) returningAuthProvider = \"\"; // nulls -> \"\"s\n if (!getAuthProviders().contains(getProviderByName(returningAuthProvider))) {\n returningAuthProvider = \"\";\n }\n\n mReturningAuthProvider = returningAuthProvider;\n PrefUtils.putString(PrefUtils.KEY_JR_LAST_USED_AUTH_PROVIDER, returningAuthProvider);\n }\n\n public String getReturningSharingProvider() {\n return mReturningSharingProvider;\n }\n\n public void setReturningSharingProvider(String returningSharingProvider) {\n if (TextUtils.isEmpty(returningSharingProvider)) returningSharingProvider = \"\"; // nulls -> \"\"s\n if (!getSharingProviders().contains(getProviderByName(returningSharingProvider))) {\n returningSharingProvider = \"\";\n }\n\n mReturningSharingProvider = returningSharingProvider;\n PrefUtils.putString(PrefUtils.KEY_JR_LAST_USED_SHARING_PROVIDER, returningSharingProvider);\n }\n\n public String getRpBaseUrl() {\n return mRpBaseUrl;\n }\n\n public boolean getHidePoweredBy() {\n return mHidePoweredBy;\n }\n\n public void setUiIsShowing(boolean uiIsShowing) {\n if (uiIsShowing) {\n mUiShowingCount++;\n } else {\n mUiShowingCount--;\n }\n\n if (mUiShowingCount == 0 && mSavedConfigurationBlock != null) {\n String s = mSavedConfigurationBlock;\n mSavedConfigurationBlock = null;\n mNewEtag = mSavedEtag;\n finishGetConfiguration(s);\n }\n }\n\n public void connectionDidFail(Exception ex, HttpResponseHeaders responseHeaders, byte[] payload,\n String requestUrl, Object tag) {\n if (tag == null) {\n LogUtils.loge(\"unexpected null tag\");\n } else if (tag instanceof String) {\n if (tag.equals(TAG_GET_CONFIGURATION)) {\n LogUtils.loge(\"failure for getConfiguration\");\n mError = new JREngageError(\n getApplicationContext().getString(R.string.jr_getconfig_network_failure_message),\n ConfigurationError.CONFIGURATION_INFORMATION_ERROR,\n JREngageError.ErrorType.CONFIGURATION_FAILED,\n ex);\n triggerConfigDidFinish();\n } else {\n LogUtils.loge(\"unrecognized ConnectionManager tag: \" + tag, ex);\n }\n } else if (tag instanceof JRDictionary) {\n JRDictionary tagAsDict = (JRDictionary) tag;\n if (tagAsDict.getAsString(USERDATA_ACTION_KEY).equals(USERDATA_ACTION_CALL_TOKEN_URL)) {\n LogUtils.loge(\"call to token url failed: \", ex);\n JREngageError error = new JREngageError(\n \"Error: \" + ex.getLocalizedMessage(),\n JREngageError.AuthenticationError.AUTHENTICATION_TOKEN_URL_FAILED,\n \"Failed to reach authentication token URL\",\n ex);\n for (JRSessionDelegate delegate : getDelegatesCopy()) {\n delegate.authenticationCallToTokenUrlDidFail(\n tagAsDict.getAsString(USERDATA_TOKEN_URL_KEY),\n error,\n tagAsDict.getAsString(USERDATA_PROVIDER_NAME_KEY));\n }\n } else if (tagAsDict.getAsString(USERDATA_ACTION_KEY).equals(USERDATA_ACTION_SHARE_ACTIVITY)) {\n // set status uses this same connection handler.\n processShareActivityResponse(new String(payload), tagAsDict);\n }\n }\n }\n\n private void processShareActivityResponse(String payload, JRDictionary userDataTag) {\n String providerName = userDataTag.getAsString(USERDATA_PROVIDER_NAME_KEY);\n\n JRDictionary responseDict;\n try {\n responseDict = JRDictionary.fromJsonString(payload);\n } catch (JSONException e) {\n // No JSON response\n setCurrentlyPublishingProvider(null);\n triggerPublishingJRActivityDidFail(\n new JREngageError(payload, SocialPublishingError.FAILED, ErrorType.PUBLISH_FAILED),\n (JRActivityObject) userDataTag.get(USERDATA_ACTIVITY_KEY), providerName);\n return;\n }\n\n if (!\"ok\".equals(responseDict.get(\"stat\"))) {\n // Bad or missing stat value\n setCurrentlyPublishingProvider(null);\n JRDictionary errorDict = responseDict.getAsDictionary(\"err\");\n JREngageError publishError;\n\n if (errorDict != null) {\n // report the error as found in the err dict\n publishError = processShareActivityFailureResponse(errorDict);\n } else {\n // bad api response\n publishError = new JREngageError(\n getApplicationContext().getString(R.string.jr_problem_sharing),\n SocialPublishingError.FAILED,\n ErrorType.PUBLISH_FAILED);\n }\n\n triggerPublishingJRActivityDidFail(publishError,\n (JRActivityObject) userDataTag.get(USERDATA_ACTIVITY_KEY), providerName);\n return;\n }\n\n // No error\n setReturningSharingProvider(getCurrentlyPublishingProvider().getName());\n setCurrentlyPublishingProvider(null);\n triggerPublishingJRActivityDidSucceed(mActivity, providerName);\n }\n\n private JREngageError processShareActivityFailureResponse(JRDictionary errorDict) {\n JREngageError publishError;\n int code = (errorDict.containsKey(\"code\")) ? errorDict.getAsInt(\"code\") : 1000;\n\n String errorMessage = errorDict.getAsString(\"msg\", \"\");\n\n switch (code) {\n case 0: /* \"Missing parameter: apiKey\" */\n publishError = new JREngageError(\n errorMessage,\n SocialPublishingError.MISSING_API_KEY,\n ErrorType.PUBLISH_NEEDS_REAUTHENTICATION);\n break;\n case 4: /* \"Facebook Error: Invalid OAuth 2.0 Access Token\" */\n if (errorMessage.matches(\".*nvalid ..uth.*\") ||\n errorMessage.matches(\".*session.*invalidated.*\") ||\n errorMessage.matches(\".*rror validating access token.*\")) {\n publishError = new JREngageError(\n errorMessage,\n SocialPublishingError.INVALID_OAUTH_TOKEN,\n ErrorType.PUBLISH_NEEDS_REAUTHENTICATION);\n } else if (errorMessage.matches(\".*eed action request limit.*\")) {\n publishError = new JREngageError(\n errorMessage,\n SocialPublishingError.FEED_ACTION_REQUEST_LIMIT,\n ErrorType.PUBLISH_FAILED);\n } else {\n publishError = new JREngageError(\n errorMessage,\n SocialPublishingError.FAILED,\n ErrorType.PUBLISH_FAILED);\n }\n break;\n case 100: // TODO LinkedIn character limit error\n publishError = new JREngageError(\n errorMessage,\n SocialPublishingError.LINKEDIN_CHARACTER_EXCEEDED,\n ErrorType.PUBLISH_INVALID_ACTIVITY);\n break;\n case 6:\n if (errorMessage.matches(\".witter.*uplicate.*\")) {\n publishError = new JREngageError(\n errorMessage,\n SocialPublishingError.DUPLICATE_TWITTER,\n ErrorType.PUBLISH_INVALID_ACTIVITY);\n } else {\n publishError = new JREngageError(\n errorMessage,\n SocialPublishingError.FAILED,\n ErrorType.PUBLISH_INVALID_ACTIVITY);\n }\n break;\n case 1000: /* Extracting code failed; Fall through. */\n default:\n publishError = new JREngageError(\n getApplicationContext().getString(R.string.jr_problem_sharing),\n SocialPublishingError.FAILED,\n ErrorType.PUBLISH_FAILED);\n break;\n }\n\n return publishError;\n }\n\n public void connectionDidFinishLoading(HttpResponseHeaders headers, byte[] payload,\n String requestUrl, Object tag) {\n String payloadString = new String(payload);\n\n if (tag instanceof JRDictionary) {\n JRDictionary dictionary = (JRDictionary) tag;\n if (dictionary.getAsString(USERDATA_ACTION_KEY).equals(USERDATA_ACTION_SHARE_ACTIVITY)) {\n processShareActivityResponse(payloadString, dictionary);\n } else if (dictionary.containsKey(USERDATA_TOKEN_URL_KEY)) {\n for (JRSessionDelegate delegate : getDelegatesCopy()) {\n delegate.authenticationDidReachTokenUrl(\n dictionary.getAsString(USERDATA_TOKEN_URL_KEY),\n headers,\n payloadString,\n dictionary.getAsString(USERDATA_PROVIDER_NAME_KEY));\n }\n } else {\n LogUtils.loge(\"unexpected userdata found in ConnectionDidFinishLoading: \" + dictionary);\n }\n } else if (tag instanceof String) {\n if (tag.equals(TAG_GET_CONFIGURATION)) {\n if (headers.getResponseCode() == HttpStatus.SC_NOT_MODIFIED) {\n /* If the ETag matched, we're done. */\n LogUtils.logd(\"[connectionDidFinishLoading] HTTP_NOT_MODIFIED -> matched ETag\");\n triggerConfigDidFinish();\n return;\n }\n\n finishGetConfiguration(payloadString, headers.getETag());\n } else {\n LogUtils.loge(\"unexpected userData found in ConnectionDidFinishLoading full\");\n }\n }\n }\n\n public void addDelegate(JRSessionDelegate delegate) {\n mDelegates.add(delegate);\n }\n\n public void removeDelegate(JRSessionDelegate delegate) {\n mDelegates.remove(delegate);\n }\n\n public void tryToReconfigureLibrary() {\n mConfigDone = false;\n mError = null;\n mError = startGetConfiguration();\n }\n\n private JREngageError startGetConfiguration() {\n String urlString = String.format(UNFORMATTED_CONFIG_URL,\n mEngageBaseUrl,\n mAppId,\n mUrlEncodedAppName,\n mUrlEncodedLibraryVersion);\n BasicNameValuePair eTagHeader = new BasicNameValuePair(\"If-None-Match\", mOldEtag);\n List<NameValuePair> headerList = new ArrayList<NameValuePair>();\n headerList.add(eTagHeader);\n\n JRConnectionManager.createConnection(urlString, this, TAG_GET_CONFIGURATION, headerList, null, false);\n\n return null;\n }\n\n private void finishGetConfiguration(String dataStr) {\n JRDictionary jsonDict;\n try {\n jsonDict = JRDictionary.fromJsonString(dataStr);\n } catch (JSONException e) {\n LogUtils.loge(\"failed\", e);\n mError = new JREngageError(\n getApplicationContext().getString(R.string.jr_getconfig_parse_error_message),\n ConfigurationError.JSON_ERROR, ErrorType.CONFIGURATION_FAILED, e);\n return;\n }\n\n mRpBaseUrl = StringUtils.chomp(jsonDict.getAsString(\"baseurl\", \"\"), \"/\");\n PrefUtils.putString(PrefUtils.KEY_JR_RP_BASE_URL, mRpBaseUrl);\n\n mAllProviders = new HashMap<String, JRProvider>();\n JRDictionary providerInfo = jsonDict.getAsDictionary(\"provider_info\");\n for (String name : providerInfo.keySet()) {\n mAllProviders.put(name, new JRProvider(name, providerInfo.getAsDictionary(name)));\n }\n Archiver.asyncSave(ARCHIVE_ALL_PROVIDERS, mAllProviders);\n\n mAuthProviders = jsonDict.getAsListOfStrings(\"enabled_providers\");\n mSharingProviders = jsonDict.getAsListOfStrings(\"social_providers\");\n Archiver.asyncSave(ARCHIVE_AUTH_PROVIDERS, mAuthProviders);\n Archiver.asyncSave(ARCHIVE_SHARING_PROVIDERS, mSharingProviders);\n\n mHidePoweredBy = jsonDict.getAsBoolean(\"hide_tagline\", false);\n PrefUtils.putBoolean(PrefUtils.KEY_JR_HIDE_POWERED_BY, mHidePoweredBy);\n\n /* Ensures that the returning auth and sharing providers,\n * if set, are members of the configured set of providers. */\n setReturningAuthProvider(mReturningAuthProvider);\n setReturningSharingProvider(mReturningSharingProvider);\n\n PrefUtils.putString(PrefUtils.KEY_JR_CONFIGURATION_ETAG, mNewEtag);\n PrefUtils.putString(PrefUtils.KEY_JR_ENGAGE_LIBRARY_VERSION, mUrlEncodedLibraryVersion);\n\n mError = null;\n triggerConfigDidFinish();\n }\n\n private void finishGetConfiguration(String dataStr, String eTag) {\n /* Only update all the config if the UI isn't currently displayed / using that\n * information. Otherwise, the library may crash/behave inconsistently. In the case\n * where a dialog is showing but there isn't any config data that it could be using (that\n * is, the lists of auth and sharing providers are empty), update the config. */\n if (!isUiShowing() ||\n (CollectionUtils.isEmpty(mAuthProviders) && CollectionUtils.isEmpty(mSharingProviders))) {\n mNewEtag = eTag;\n finishGetConfiguration(dataStr);\n return;\n }\n\n /* Otherwise, we have to save all this information for later. When no UI is displayed\n * mSavedConfigurationBlock is checked and the config is updated then. */\n mSavedConfigurationBlock = dataStr;\n mSavedEtag = eTag;\n\n mError = null;\n }\n\n private boolean isUiShowing() {\n return mUiShowingCount != 0;\n }\n\n private String getWelcomeMessageFromCookieString() {\n String cookies = CookieManager.getInstance().getCookie(getRpBaseUrl());\n String cookieString = cookies.replaceAll(\".*welcome_info=([^;]*).*\", \"$1\");\n\n if (!TextUtils.isEmpty(cookieString)) {\n String[] parts = cookieString.split(\"%22\");\n if (parts.length > 5) return \"Sign in as \" + AndroidUtils.urlDecode(parts[5]);\n }\n\n return null;\n }\n\n public void saveLastUsedAuthProvider() {\n setReturningAuthProvider(mCurrentlyAuthenticatingProvider.getName());\n }\n\n public URL startUrlForCurrentlyAuthenticatingProvider() {\n // can happen on Android process restart:\n if (mCurrentlyAuthenticatingProvider == null) return null;\n\n String oid; /* open identifier */\n\n if (!TextUtils.isEmpty(mCurrentlyAuthenticatingProvider.getOpenIdentifier())) {\n oid = String.format(\"openid_identifier=%s&\",\n mCurrentlyAuthenticatingProvider.getOpenIdentifier());\n if (mCurrentlyAuthenticatingProvider.requiresInput()) {\n oid = oid.replaceAll(\"%@\", mCurrentlyAuthenticatingProvider.getUserInput());\n } else {\n oid = oid.replaceAll(\"%@\", \"\");\n }\n } else {\n oid = \"\";\n }\n\n String fullStartUrl;\n\n boolean forceReauth = mAlwaysForceReauth || mCurrentlyAuthenticatingProvider.getForceReauth();\n if (forceReauth) {\n deleteWebViewCookiesForDomains(getApplicationContext(),\n mCurrentlyAuthenticatingProvider.getCookieDomains());\n }\n\n fullStartUrl = String.format(\"%s%s?%s%sdevice=android&extended=true&installation_id=%s\",\n mRpBaseUrl,\n mCurrentlyAuthenticatingProvider.getStartAuthenticationUrl(),\n oid,\n (forceReauth ? \"force_reauth=true&\" : \"\"),\n AndroidUtils.urlEncode(mUniqueIdentifier)\n );\n\n LogUtils.logd(\"startUrl: \" + fullStartUrl);\n\n URL url = null;\n try {\n url = new URL(fullStartUrl);\n } catch (MalformedURLException e) {\n throwDebugException(new RuntimeException(\"URL create failed for string: \" + fullStartUrl, e));\n }\n return url;\n }\n\n private String getUniqueIdentifier() {\n String idString = PrefUtils.getString(PrefUtils.KEY_JR_UNIVERSALLY_UNIQUE_ID, null);\n\n if (idString == null) {\n UUID id = UUID.randomUUID();\n idString = id.toString();\n\n PrefUtils.putString(PrefUtils.KEY_JR_UNIVERSALLY_UNIQUE_ID, idString);\n }\n\n return idString;\n }\n\n public JRAuthenticatedUser getAuthenticatedUserForProvider(JRProvider provider) {\n return mAuthenticatedUsersByProvider.get(provider.getName());\n }\n\n public void signOutUserForProvider(String providerName) {\n if (mAllProviders == null) throwDebugException(new IllegalStateException());\n JRProvider provider = mAllProviders.get(providerName);\n if (provider == null) {\n throwDebugException(new IllegalStateException(\"Unknown provider name:\" + providerName));\n } else {\n List<String> cookieDomains = provider.getCookieDomains();\n if (cookieDomains.size() == 0) {\n provider.setForceReauth(true); // MOB-135\n } else {\n deleteWebViewCookiesForDomains(getApplicationContext(), cookieDomains);\n }\n }\n\n if (mAuthenticatedUsersByProvider == null) throwDebugException(new IllegalStateException());\n\n if (mAuthenticatedUsersByProvider.containsKey(providerName)) {\n mAuthenticatedUsersByProvider.get(providerName).deleteCachedProfilePic();\n mAuthenticatedUsersByProvider.remove(providerName);\n Archiver.asyncSave(ARCHIVE_AUTH_USERS_BY_PROVIDER, mAuthenticatedUsersByProvider);\n triggerUserWasSignedOut(providerName);\n }\n }\n\n public void signOutAllAuthenticatedUsers() {\n for (String p : mAllProviders.keySet()) signOutUserForProvider(p);\n }\n\n public JRProvider getProviderByName(String name) {\n return mAllProviders.get(name);\n }\n\n public void notifyEmailSmsShare(String method) {\n StringBuilder body = new StringBuilder();\n body.append(\"method=\").append(method);\n body.append(\"&device=\").append(\"android\");\n body.append(\"&appId=\").append(mAppId);\n\n String url = mEngageBaseUrl + \"/social/record_activity\";\n\n JRConnectionManagerDelegate jrcmd = new SimpleJRConnectionManagerDelegate() {\n @Override\n public void connectionDidFinishLoading(HttpResponseHeaders headers,\n byte[] payload,\n String requestUrl,\n Object tag) {\n }\n\n @Override\n public void connectionDidFail(Exception ex,\n HttpResponseHeaders responseHeaders,\n byte[] payload, String requestUrl,\n Object tag) {\n LogUtils.loge(\"notify failure\", ex);\n }\n };\n\n JRConnectionManager.createConnection(url, jrcmd, null, null, body.toString().getBytes(), false);\n }\n\n public void shareActivityForUser(JRAuthenticatedUser user) {\n setCurrentlyPublishingProvider(user.getProviderName());\n\n /* Truncate the resource description if necessary */\n int descMaxChars = getCurrentlyPublishingProvider().getSocialSharingProperties()\n .getAsInt(JRDictionary.KEY_DESC_MAX_CHARS, -1);\n if (descMaxChars > 0 && mActivity.getDescription().length() > descMaxChars) {\n mActivity.setDescription(mActivity.getDescription().substring(0, 255));\n }\n\n String deviceToken = user.getDeviceToken();\n String activityJson = mActivity.toJRDictionary().toJson();\n String urlEncodedActivityJson = AndroidUtils.urlEncode(activityJson);\n\n StringBuilder body = new StringBuilder();\n\n body.append(\"activity=\").append(urlEncodedActivityJson);\n /* These are undocumented parameters for the mobile library's use */\n body.append(\"&device_token=\").append(deviceToken);\n body.append(\"&url_shortening=true\");\n body.append(\"&provider=\").append(user.getProviderName());\n body.append(\"&device=android\");\n body.append(\"&app_name=\").append(mUrlEncodedAppName);\n\n String url = mEngageBaseUrl + \"/api/v2/activity\";\n\n JRDictionary tag = new JRDictionary();\n tag.put(USERDATA_ACTION_KEY, USERDATA_ACTION_SHARE_ACTIVITY);\n tag.put(USERDATA_ACTIVITY_KEY, mActivity);\n tag.put(USERDATA_PROVIDER_NAME_KEY, mCurrentlyPublishingProvider.getName());\n JRConnectionManager.createConnection(url, this, tag, null, body.toString().getBytes(), false);\n }\n\n public void setStatusForUser(JRAuthenticatedUser user) {\n setCurrentlyPublishingProvider(user.getProviderName());\n\n String deviceToken = user.getDeviceToken();\n String status = mActivity.getUserGeneratedContent();\n // TODO: this should also include other pieces of the activity\n\n StringBuilder body = new StringBuilder();\n // TODO: include truncate parameter here?\n body.append(\"status=\").append(status);\n\n /* These are [undocumented] parameters available for use by the mobile library when\n * making calls to the Engage API. */\n body.append(\"&device_token=\").append(deviceToken);\n body.append(\"&device=android\");\n body.append(\"&app_name=\").append(mUrlEncodedAppName);\n\n String url = mEngageBaseUrl + \"/api/v2/set_status\";\n\n // TODO: same callback handler for status as activity?\n JRDictionary tag = new JRDictionary();\n tag.put(USERDATA_ACTION_KEY, USERDATA_ACTION_SHARE_ACTIVITY);\n tag.put(USERDATA_ACTIVITY_KEY, mActivity);\n tag.put(USERDATA_PROVIDER_NAME_KEY, mCurrentlyPublishingProvider.getName());\n JRConnectionManager.createConnection(url, this, tag, null, body.toString().getBytes(), false);\n }\n\n private void makeCallToTokenUrl(String tokenUrl, String token, String providerName) {\n String body = \"token=\" + token;\n byte[] postData = body.getBytes();\n\n JRDictionary tag = new JRDictionary();\n tag.put(USERDATA_ACTION_KEY, USERDATA_ACTION_CALL_TOKEN_URL);\n tag.put(USERDATA_TOKEN_URL_KEY, tokenUrl);\n tag.put(USERDATA_PROVIDER_NAME_KEY, providerName);\n\n JRConnectionManager.createConnection(tokenUrl, this, tag, null, postData, false);\n }\n\n public void triggerAuthenticationDidCompleteWithPayload(JRDictionary rpx_result) {\n JRAuthenticatedUser user = new JRAuthenticatedUser(\n rpx_result,\n mCurrentlyAuthenticatingProvider.getName(),\n getWelcomeMessageFromCookieString());\n mAuthenticatedUsersByProvider.put(mCurrentlyAuthenticatingProvider.getName(), user);\n Archiver.asyncSave(ARCHIVE_AUTH_USERS_BY_PROVIDER, mAuthenticatedUsersByProvider);\n\n String authInfoToken = rpx_result.getAsString(\"token\");\n JRDictionary authInfoDict = rpx_result.getAsDictionary(\"auth_info\");\n authInfoDict.put(\"token\", authInfoToken);\n authInfoDict.put(\"device_token\", user.getDeviceToken());\n\n for (JRSessionDelegate delegate : getDelegatesCopy()) {\n delegate.authenticationDidComplete(\n authInfoDict,\n mCurrentlyAuthenticatingProvider.getName());\n }\n\n if (!TextUtils.isEmpty(mTokenUrl)) {\n makeCallToTokenUrl(mTokenUrl, authInfoToken, mCurrentlyAuthenticatingProvider.getName());\n }\n\n mCurrentlyAuthenticatingProvider.setForceReauth(false);\n setCurrentlyAuthenticatingProvider(null);\n }\n\n public void triggerAuthenticationDidFail(JREngageError error) {\n if (mCurrentlyAuthenticatingProvider == null) {\n throwDebugException(new RuntimeException(\"Unexpected state\"));\n }\n\n String providerName = mCurrentlyAuthenticatingProvider.getName();\n signOutUserForProvider(providerName);\n\n setCurrentlyAuthenticatingProvider(null);\n mReturningAuthProvider = null;\n mReturningSharingProvider = null;\n\n for (JRSessionDelegate delegate : getDelegatesCopy()) {\n delegate.authenticationDidFail(error, providerName);\n }\n }\n\n public void triggerAuthenticationDidCancel() {\n setCurrentlyAuthenticatingProvider(null);\n setReturningAuthProvider(null);\n\n for (JRSessionDelegate delegate : getDelegatesCopy()) delegate.authenticationDidCancel();\n }\n\n public void triggerAuthenticationDidRestart() {\n for (JRSessionDelegate delegate : getDelegatesCopy()) delegate.authenticationDidRestart();\n }\n\n public void triggerUserWasSignedOut(String provider) {\n for (JRSessionDelegate d : getDelegatesCopy()) d.userWasSignedOut(provider);\n }\n\n public void triggerPublishingDidComplete() {\n for (JRSessionDelegate delegate : getDelegatesCopy()) delegate.publishingDidComplete();\n }\n\n public void triggerPublishingJRActivityDidFail(JREngageError error,\n JRActivityObject activity,\n String providerName) {\n for (JRSessionDelegate delegate : getDelegatesCopy()) {\n delegate.publishingJRActivityDidFail(activity, error, providerName);\n }\n }\n\n private void triggerPublishingJRActivityDidSucceed(JRActivityObject mActivity, String providerName) {\n for (JRSessionDelegate delegate : getDelegatesCopy()) {\n delegate.publishingJRActivityDidSucceed(mActivity, providerName);\n }\n }\n\n /**\n * Informs delegates that the publishing dialog failed to display.\n * @param err\n * The error to send to delegates\n */\n public void triggerPublishingDialogDidFail(JREngageError err) {\n for (JRSessionDelegate delegate : getDelegatesCopy()) delegate.publishingDialogDidFail(err);\n }\n\n public void triggerPublishingDidCancel() {\n for (JRSessionDelegate delegate : getDelegatesCopy()) delegate.publishingDidCancel();\n }\n\n private void triggerConfigDidFinish() {\n mConfigDone = true;\n for (JRSessionDelegate d : getDelegatesCopy()) d.configDidFinish();\n }\n\n private synchronized List<JRSessionDelegate> getDelegatesCopy() {\n return (mDelegates == null)\n ? new ArrayList<JRSessionDelegate>()\n : new ArrayList<JRSessionDelegate>(mDelegates);\n }\n\n public JRProvider getCurrentlyPublishingProvider() {\n return mCurrentlyPublishingProvider;\n }\n\n public void setCurrentlyPublishingProvider(String provider) {\n mCurrentlyPublishingProvider = getProviderByName(provider);\n }\n\n public boolean isConfigDone() {\n return mConfigDone;\n }\n\n public String getUrlEncodedAppName() {\n return mUrlEncodedAppName;\n }\n\n public void setEnabledAuthenticationProviders(List<String> enabledProviders) {\n mEnabledAuthenticationProviders = enabledProviders;\n\n // redundantly call the setter to ensure the provider is still available\n setReturningAuthProvider(mReturningAuthProvider);\n }\n\n public List<String> getEnabledAuthenticationProviders() {\n if (mEnabledAuthenticationProviders == null) {\n return mAuthProviders;\n } else {\n return mEnabledAuthenticationProviders;\n }\n }\n\n public void setEnabledSharingProviders(List<String> enabledSharingProviders) {\n mEnabledSharingProviders = enabledSharingProviders;\n\n // redundantly call the setter to ensure the provider is still available\n setReturningSharingProvider(mReturningSharingProvider);\n }\n \n //public List<String> getEnabledSharingProviders() {\n // if (mEnabledSharingProviders == null) {\n // return mSharingProviders;\n // } else {\n // return mEnabledSharingProviders;\n // }\n //}\n\n private Context getApplicationContext() {\n return JREngage.getApplicationContext();\n }\n\n /* package */ String getEngageBaseUrl() {\n return mEngageBaseUrl;\n }\n\n public String getTokenUrl() {\n return mTokenUrl;\n }\n}", "public interface JRSessionDelegate {\n\n /**\n * Triggered when the authentication restarts because:\n * - the user presses the back button from the landing screen, or the webview\n * - the user presses the switch accounts button on the landing screen\n * - the webview receives a ~\"result canceled\" response from Engage\n */\n void authenticationDidRestart();\n\n /**\n * Triggered by the calling application via JREngage.cancelAuthentication\n */\n void authenticationDidCancel();\n\n /**\n * Triggered when JRWebViewActivity recieves a success message from Engage.\n * @param profile\n * The profile received for the user from Engage\n * @param provider\n * The provider the user authenticated with\n */\n void authenticationDidComplete(JRDictionary profile, String provider);\n\n /**\n * Triggered when the Engage authentication flow completes with an Engage error, or when there\n * is an error loading a URL during that authentication flow.\n * @param error\n * The error the library failed with\n * @param provider\n * The provider the library was attempting to authenticate the user with at the time of failure\n */\n void authenticationDidFail(JREngageError error, String provider);\n\n /**\n * Triggered when\n * @param tokenUrl\n * The token URL posted to\n * @param responseHeaders\n * The headers received in the response\n * @param payload\n * The body of the received response\n * @param provider\n * The provider the user authenticated with\n */\n void authenticationDidReachTokenUrl(String tokenUrl,\n HttpResponseHeaders responseHeaders,\n String payload,\n String provider);\n\n /**\n * Triggered when the call to the token URL fails -- due to network error\n * @param tokenUrl\n * The token URL posted to\n * @param error\n * The error generated by the failure\n * @param provider\n * The provider the user authenticated with that preceded the failed token URL post\n */\n void authenticationCallToTokenUrlDidFail(String tokenUrl, JREngageError error, String provider);\n\n /**\n * Triggered when the user is signed out via JREngage#forgetAuthenticatedUser and it's variant\n * @param provider\n * The provider the user was signed out of\n */\n void userWasSignedOut(String provider);\n\n /**\n * Triggered triggered by the calling application via JREngage.cancelPublishing\n */\n void publishingDidCancel();\n\n /**\n * Triggered when the publishing dialog closes\n */\n void publishingDidComplete();\n\n /**\n * Triggered when a success response is received from Engage from the activity API\n * @param activity\n * The JRActivityObject that was published\n * @param provider\n * The provider by which the JRActivityObject was published\n */\n void publishingJRActivityDidSucceed(JRActivityObject activity, String provider);\n\n /**\n * Triggered when an error is encountered while publishing the activity via Engage\n * @param activity\n * The activity that failed to be shared\n * @param error\n * The error produced by the failure\n * @param provider\n * The provider that the activity was attempting to be shared via\n */\n void publishingJRActivityDidFail(JRActivityObject activity, JREngageError error, String provider);\n\n /**\n * Triggered when the publishing UI fails to load\n * @param error\n * The error produced by the failure of the publishing dialog to display\n */\n void publishingDialogDidFail(JREngageError error);\n\n /**\n * Triggered when JRSession has finished loading the mobile configuration\n */\n void configDidFinish();\n\n /**\n * @internal\n * An empty implementation of JRSessionDelegate. Handy for subclassing, and overriding only\n * desirable message handlers.\n */\n public static abstract class SimpleJRSessionDelegate implements JRSessionDelegate {\n public void authenticationDidRestart() {}\n public void authenticationDidCancel() {}\n public void authenticationDidComplete(JRDictionary profile, String provider) {}\n public void authenticationDidFail(JREngageError error, String provider) {}\n public void authenticationDidReachTokenUrl(String tokenUrl,\n HttpResponseHeaders responseHeaders,\n String payload,\n String provider) {}\n public void authenticationCallToTokenUrlDidFail(String tokenUrl,\n JREngageError error,\n String provider) {}\n public void userWasSignedOut(String provider) {}\n public void publishingDidCancel() {}\n public void publishingDidComplete() {}\n public void publishingJRActivityDidSucceed(JRActivityObject activity, String provider) {}\n public void publishingDialogDidFail(JREngageError error) {}\n public void publishingJRActivityDidFail(JRActivityObject activity,\n JREngageError error,\n String provider) {}\n public void configDidFinish() {}\n }\n}", "public final class JRDictionary extends HashMap<String, Object> {\n private static final String TAG = JRDictionary.class.getSimpleName();\n\n public static final String DEFAULT_VALUE_STRING = \"\";\n public static final int DEFAULT_VALUE_INT = -1;\n public static final boolean DEFAULT_VALUE_BOOLEAN = false;\n\n public static final String KEY_DESC_MAX_CHARS = \"desc_max_chars\";\n public static final String KEY_JS_INJECTIONS = \"js_injections\";\n public static final String KEY_SHOW_ZOOM_CONTROL = \"show_zoom_control\";\n public static final String KEY_USER_AGENT = \"user_agent\";\n public static final String KEY_USES_SET_STATUS = \"uses_set_status_if_no_url\";\n\n/**\n * @name JSON Serialization\n * Methods that serialize/deserialize the JRDictionary to/from JSON\n **/\n/*@{*/\n\n /**\n * Encodes the JRDictionary into a JSON string.\n *\n * @return JSON representation of the specified JRDictionary object\n */\n public String toJson() {\n JSONStringer jsonStringer = new JSONStringer();\n\n try {\n jsonify(this, jsonStringer);\n return jsonStringer.toString();\n } catch (JSONException e) {\n throw new RuntimeException(e);\n }\n }\n\n /**\n * Encodes the JRDictionary into a JSON string.\n *\n * @return JSON representation of the specified JRDictionary object\n */\n public String toJSON() {\n return toJson();\n }\n\n /**\n * Decodes the JSON string into a JRDictionary instance.\n *\n * @param json The JSON string to be decoded.\n * @return A JRDictionary object representation of the JSON string, never null\n * @throws JSONException When the JSON couldn't be parsed.\n */\n public static JRDictionary fromJsonString(String json) throws JSONException {\n JSONTokener jsonTokener = new JSONTokener(json);\n\n Object jsonObject = jsonTokener.nextValue();\n\n try {\n return (JRDictionary) unjsonify(jsonObject);\n } catch (ClassCastException e) {\n throw new JSONException(e.toString());\n }\n }\n/*@}*/\n\n private static void jsonify(Object object, JSONStringer jsonStringer) throws JSONException {\n if (object instanceof JRDictionary) {\n jsonStringer.object();\n for (String key : ((JRDictionary) object).keySet()) {\n jsonStringer.key(key);\n jsonify(((JRDictionary) object).get(key), jsonStringer);\n }\n jsonStringer.endObject();\n } else if (object instanceof Object[]) {\n jsonStringer.array();\n for (Object o : (Object[]) object) jsonify(o, jsonStringer);\n jsonStringer.endArray();\n } else if (object instanceof Collection) {\n jsonify(((Collection) object).toArray(), jsonStringer);\n } else if (object instanceof String) {\n jsonStringer.value(object);\n } else if (object instanceof Boolean) {\n jsonStringer.value(object);\n } else if (object instanceof Integer) {\n jsonStringer.value(object);\n } else if (object instanceof Double) {\n jsonStringer.value(object);\n } else if (object instanceof Long) {\n jsonStringer.value(object);\n } else if (object instanceof JRJsonifiable) {\n jsonify(((JRJsonifiable) object).toJRDictionary(), jsonStringer);\n } else if (object == null) {\n jsonStringer.value(JSONObject.NULL);\n } else {\n throw new RuntimeException(\"Unexpected jsonify value: \" + object);\n }\n }\n\n private static Object unjsonify(Object jsonValue) throws JSONException {\n if (jsonValue instanceof JSONArray) {\n ArrayList returnArray = new ArrayList();\n for (int i = 0; i < ((JSONArray) jsonValue).length(); i++) {\n returnArray.add(unjsonify(((JSONArray) jsonValue).get(i)));\n }\n return returnArray;\n }\n if (jsonValue instanceof JSONObject) {\n JRDictionary returnDictionary = new JRDictionary();\n Iterator<String> i = ((JSONObject) jsonValue).keys();\n while (i.hasNext()) {\n String key = i.next();\n Object value = ((JSONObject) jsonValue).get(key);\n returnDictionary.put(key, unjsonify(value));\n }\n return returnDictionary;\n }\n if (jsonValue instanceof Boolean) {\n return jsonValue;\n }\n if (jsonValue == JSONObject.NULL) {\n return null;\n }\n if (jsonValue == null) {\n Log.e(TAG, \"unexpected null primitive non-sentinel non-JSONObject.NULL\");\n return null;\n }\n if (jsonValue instanceof Double) {\n return jsonValue;\n }\n if (jsonValue instanceof Integer) {\n return jsonValue;\n }\n if (jsonValue instanceof Long) {\n return ((Long) jsonValue).doubleValue();\n }\n if (jsonValue instanceof String) {\n return jsonValue;\n } else {\n throw new RuntimeException(\"unexpected unjsonify class: \" + jsonValue.getClass());\n }\n }\n\n @Deprecated\n @Override\n public Object put(String key, Object value) {\n if (value instanceof JRDictionary || value instanceof String || value instanceof Number ||\n value instanceof Collection || value instanceof Object[] || value == null\n || value instanceof Boolean) {\n return super.put(key, value);\n } else {\n throw new IllegalArgumentException(\"Non-jsonifiable object could not be added to JRDictionary\");\n //Log.e(TAG, \"Non-jsonifiable object added to JRDictionary\");\n //return super.put(key, value);\n }\n }\n\n @Deprecated\n @Override\n public void putAll(Map<? extends String, ?> map) {\n throw new UnsupportedOperationException();\n //super.putAll(map);\n }\n\n public Object put(String key, String value) {\n return super.put(key, value);\n }\n\n public Object put(String key, Integer value) {\n return super.put(key, value);\n }\n\n public Object put(String key, Long value) {\n return super.put(key, value);\n }\n\n public Object put(String key, Double value) {\n return super.put(key, value);\n }\n\n public Object put(String key, JRDictionary value) {\n return super.put(key, value);\n }\n\n public Object put(String key, Object[] value) {\n return super.put(key, value);\n }\n\n public Object put(String key, Boolean value) {\n return super.put(key, value);\n }\n\n public Object put(String key, Collection value) {\n return super.put(key, value);\n }\n\n public Object put(String key, JRJsonifiable value) {\n return super.put(key, value);\n }\n\n/**\n * @name Getting Dictionary Content\n * Methods that return typed values given a \\e String key\n **/\n/*@{*/\n\n /**\n * Convenience method used to retrieve a named value as a \\e String object.\n *\n * @param key The key of the value to be retrieved\n * @return The \\e String object if found, empty string otherwise\n */\n public String getAsString(String key) {\n return getAsString(key, DEFAULT_VALUE_STRING);\n }\n\n /**\n * Convenience method used to retrieve a named value as a \\e String object.\n *\n * @param key The key of the value to be retrieved\n * @param defaultValue The value to be returned if the key is not found\n * @return The \\e String value if found, value of \\e defaultValue otherwise\n */\n public String getAsString(String key, String defaultValue) {\n return (containsKey(key)) ? (String) get(key) : defaultValue;\n }\n\n /**\n * Convenience method used to retrieve a named value as an \\e int.\n *\n * @param key The key of the value to be retrieved\n * @return The \\e int value if found, \\c -1 otherwise\n */\n public int getAsInt(String key) {\n return getAsInt(key, DEFAULT_VALUE_INT);\n }\n\n /**\n * Convenience method used to retrieve a named value as an \\e Integer.\n *\n * @param key The key of the value to be retrieved\n * @return The \\e Integer value if found, null otherwise\n */\n public Integer getAsInteger(String key) {\n return containsKey(key) ? (Integer) get(key) : null;\n }\n\n /**\n * Convenience method used to retrieve a named value as an \\e int.\n *\n * @param key The key of the value to be retrieved\n * @param defaultValue The value to be returned if the key is not found\n * @return The \\e int value if found, value of \\e defaultValue otherwise\n */\n public int getAsInt(String key, int defaultValue) {\n int retval = defaultValue;\n if ((!TextUtils.isEmpty(key)) && (containsKey(key))) {\n Object value = get(key);\n if (value instanceof Integer) {\n retval = (Integer) value;\n } else if (value instanceof String) {\n String strValue = (String) value;\n if (!TextUtils.isEmpty(strValue)) {\n try {\n retval = Integer.parseInt(strValue);\n } catch (Exception ignore) {\n // string value is not an integer...return default value...\n }\n }\n }\n }\n return retval;\n }\n\n /**\n * Convenience method used to retrieve a named value as a \\e boolean.\n *\n * @param key The key of the value to be retrieved\n * @return The \\e boolean value if found, \\c false otherwise\n */\n public boolean getAsBoolean(String key) {\n return getAsBoolean(key, DEFAULT_VALUE_BOOLEAN);\n }\n\n /**\n * Convenience method used to retrieve a named value as a \\e boolean.\n *\n * @param key The key of the value to be retrieved\n * @param defaultValue The value to be returned if the key is not found\n * @return The \\e boolean value if found, value of \\e defaultValue otherwise\n */\n public boolean getAsBoolean(String key, boolean defaultValue) {\n boolean retval = defaultValue;\n if ((!TextUtils.isEmpty(key)) && (containsKey(key))) {\n Object value = get(key);\n if (value instanceof Boolean) {\n retval = (Boolean) value;\n } else if (value instanceof String) {\n String strValue = (String) value;\n retval = StringUtils.stringToBoolean(strValue, false);\n }\n }\n return retval;\n }\n\n /**\n * Convenience method used to retrieve a named value as a JRDictionary.\n *\n * @param key The key of the value to be retrieved\n * @return The JRDictionary value if key is found, null otherwise\n */\n public JRDictionary getAsDictionary(String key) {\n return getAsDictionary(key, false);\n }\n\n /**\n * Convenience method used to retrieve a named value as a JRDictionary.\n *\n * @param key The key of the value to be retrieved\n * @param shouldCreateIfNotFound Flag indicating whether or not a new JRDictionary object should be\n * created if the specified key does not exist\n * @return The JRDictionary value if key is found, empty object or null otherwise (based on value of the\n * \\e shouldCreateIfNotFound flag)\n */\n public JRDictionary getAsDictionary(String key, boolean shouldCreateIfNotFound) {\n JRDictionary retval = null;\n if ((!TextUtils.isEmpty(key)) && (containsKey(key))) {\n Object value = get(key);\n if (value instanceof JRDictionary) {\n retval = (JRDictionary) value;\n } else {\n throw new RuntimeException(\"Unexpected type in JRDictionary\");\n }\n }\n\n return ((retval == null) && shouldCreateIfNotFound) ? new JRDictionary() : retval;\n }\n\n /**\n * Convenience method used to retrieve a named value as an array of strings.\n *\n * @param key The key of the value to be retrieved\n * @return The \\e ArrayList<String> value if key is found, null otherwise\n */\n public ArrayList<String> getAsListOfStrings(String key) {\n return getAsListOfStrings(key, false);\n }\n\n /**\n * Convenience method used to retrieve a named value as an array of strings.\n *\n * @param key The key of the value to be retrieved\n * @param shouldCreateIfNotFound Flag indicating whether or not a new \\e ArrayList<String> object should\n * be created if the specified key does not exist\n * @return The \\e ArrayList<String> value if key is found, empty array or null otherwise (based on value\n * of the \\e shouldCreateIfNotFound flag)\n */\n // We runtime type check the return value so we can safely ignore this unchecked\n // assignment error.\n @SuppressWarnings(\"unchecked\")\n public ArrayList<String> getAsListOfStrings(String key, boolean shouldCreateIfNotFound) {\n ArrayList<String> retval = null;\n if ((!TextUtils.isEmpty(key)) && (containsKey(key))) {\n Object value = get(key);\n if (value instanceof ArrayList) {\n for (Object v : (ArrayList) value) assert v instanceof String;\n retval = (ArrayList<String>) value;\n }\n }\n\n return ((retval == null) && shouldCreateIfNotFound)\n ? new ArrayList<String>()\n : retval;\n }\n\n /**\n * Convenience method used to retrieve a named value as an array of dictionaries.\n *\n * @param key The key of the value to be retrieved\n * @return The \\e ArrayList<JRDictionary> value if key is found, null otherwise\n */\n public List<JRDictionary> getAsListOfDictionaries(String key) {\n return getAsListOfDictionaries(key, false);\n }\n\n /**\n * Convenience method used to retrieve a named value as an array of dictionaries.\n *\n * @param key The key of the value to be retrieved\n * @param shouldCreateIfNotFound Flag indicating whether or not a new \\e ArrayList<String> object should\n * be created if the specified key does not exist\n * @return The \\e ArrayList<JRDictionary> value if key is found, empty array or null otherwise (based on\n * value of the \\e shouldCreateIfNotFound flag)\n */\n\n // We runtime type check the return value so we can safely ignore this unchecked\n // assignment error.\n @SuppressWarnings(\"unchecked\")\n public List<JRDictionary> getAsListOfDictionaries(String key, boolean shouldCreateIfNotFound) {\n List<JRDictionary> retval = null;\n if ((!TextUtils.isEmpty(key)) && (containsKey(key))) {\n Object value = get(key);\n if (value instanceof List) {\n for (Object v : (ArrayList) value) assert v instanceof JRDictionary;\n retval = (ArrayList<JRDictionary>) value;\n } else {\n\n }\n }\n\n return ((retval == null) && shouldCreateIfNotFound) ? new ArrayList<JRDictionary>() : retval;\n }\n/*@}*/\n\n /**\n * @param key The key of the value to be retrieved\n * @return The JRProvider object if found, null otherwise\n * @internal Convenience method used to retrieve a named value as a JRProvider\n */\n public JRProvider getAsProvider(String key) {\n JRProvider retval = null;\n if ((!TextUtils.isEmpty(key)) && (containsKey(key))) {\n Object value = get(key);\n if (value instanceof JRProvider) {\n retval = (JRProvider) value;\n }\n }\n\n return retval;\n }\n\n/**\n * @name Miscellaneous\n * Miscellaneous methods\n **/\n/*@{*/\n\n /**\n * Utility method used to check if a dictionary object is \"empty\", that is, it is null or contains zero\n * items\n *\n * @param dictionary The dictionary object to be tested\n * @return \\c true if the dictionary is null or contains zero items, \\c false otherwise\n */\n public static boolean isEmpty(JRDictionary dictionary) {\n return ((dictionary == null) || (dictionary.size() == 0));\n }\n/*@}*/\n}", "public class JRFragmentHostActivity extends FragmentActivity {\n private static final String TAG = JRFragmentHostActivity.class.getSimpleName();\n\n public static final String JR_UI_CUSTOMIZATION_CLASS = \"jr_ui_customization_class\";\n public static final String JR_FRAGMENT_ID = \"com.janrain.android.engage.JR_FRAGMENT_ID\";\n public static final String JR_PROVIDER = \"JR_PROVIDER\";\n public static final int JR_PROVIDER_LIST = 4;\n public static final int JR_LANDING = 1;\n public static final int JR_WEBVIEW = 2;\n public static final int JR_PUBLISH = 3;\n private static final String JR_OPERATION_MODE = \"JR_OPERATION_MODE\";\n private static final int JR_DIALOG = 0;\n private static final int JR_FULLSCREEN = 1;\n private static final int JR_FULLSCREEN_NO_TITLE = 2;\n\n public static final String ACTION_FINISH_FRAGMENT = \"com.janrain.android.engage.ACTION_FINISH_FRAGMENT\";\n public static final String EXTRA_FINISH_FRAGMENT_TARGET =\n \"com.janrain.android.engage.EXTRA_FINISH_FRAGMENT_TARGET\";\n public static final String FINISH_TARGET_ALL = \"JR_FINISH_ALL\";\n\n public static final IntentFilter FINISH_INTENT_FILTER = new IntentFilter(ACTION_FINISH_FRAGMENT);\n\n private JRUiFragment mUiFragment;\n private Integer m_Result;\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n LogUtils.logd(TAG, \"[onCreate]: \" + getFragmentId());\n\n JRSession session = JRSession.getInstance();\n\n if (session == null || savedInstanceState != null) {\n /* This flow control path is reached when there's process death and restart */\n Log.e(TAG, \"bailing out after a process kill/restart. mSession: \" + session);\n\n // prevent fragment recreation error -- the system needs the fragment's container to exist\n // even if the Activity is finishing right away\n setContentView(R.layout.jr_fragment_host_activity);\n super.finish();\n return;\n }\n\n switch (getFragmentId()) {\n case JR_PROVIDER_LIST:\n mUiFragment = new JRProviderListFragment();\n break;\n case JR_LANDING:\n mUiFragment = new JRLandingFragment();\n break;\n case JR_WEBVIEW:\n mUiFragment = new JRWebViewFragment();\n break;\n case JR_PUBLISH:\n mUiFragment = new JRPublishFragment();\n break;\n default:\n throw new IllegalFragmentIdException(getFragmentId());\n }\n \n Bundle fragArgs = new Bundle();\n fragArgs.putInt(JRUiFragment.JR_FRAGMENT_FLOW_MODE, getFlowMode());\n fragArgs.putAll(getIntent().getExtras());\n mUiFragment.setArguments(fragArgs);\n\n mUiFragment.onFragmentHostActivityCreate(this, session);\n\n if (shouldBeDialog()) {\n AndroidUtils.activitySetFinishOnTouchOutside(this, true);\n\n if (shouldBePhoneSizedDialog()) {\n getTheme().applyStyle(R.style.jr_dialog_phone_sized, true);\n } else {\n getTheme().applyStyle(R.style.jr_dialog_71_percent, true);\n }\n\n if (!mUiFragment.shouldShowTitleWhenDialog()) {\n getTheme().applyStyle(R.style.jr_disable_title_and_action_bar_style, true);\n }\n } else if (getOperationMode() == JR_FULLSCREEN_NO_TITLE) {\n getWindow().requestFeature(Window.FEATURE_NO_TITLE);\n getTheme().applyStyle(R.style.jr_disable_title_and_action_bar_style, true);\n } else if (getOperationMode() == JR_FULLSCREEN) {\n // noop\n }\n\n setContentView(R.layout.jr_fragment_host_activity);\n\n View fragmentContainer = findViewById(R.id.jr_fragment_container);\n if (fragmentContainer instanceof CustomMeasuringFrameLayout) {\n // CMFL -> dialog mode on a tablet\n if (shouldBePhoneSizedDialog()) {\n // Do the actual setting of the target size to achieve phone sized dialog.\n ((CustomMeasuringFrameLayout) fragmentContainer).setTargetSizeDip(320, 480);\n getWindow().makeActive();\n WindowManager.LayoutParams lp = new WindowManager.LayoutParams();\n lp.copyFrom(getWindow().getAttributes());\n lp.width = AndroidUtils.scaleDipToPixels(320);\n // After discussing it with Lilli we think it makes sense to let the height of the window\n // grow if the title is enabled\n //int targetHeight = mUiFragment.getCustomTitle() == null ? 480 : 560;\n //lp.height = AndroidUtils.scaleDipToPixels(targetHeight);\n getWindow().setAttributes(lp);\n }\n }\n\n getSupportFragmentManager()\n .beginTransaction()\n .add(R.id.jr_fragment_container, mUiFragment)\n .setTransition(FragmentTransaction.TRANSIT_NONE)\n .commit();\n }\n\n private int getOperationMode() {\n return getIntent().getExtras().getInt(JR_OPERATION_MODE);\n }\n\n private boolean shouldBePhoneSizedDialog() {\n return shouldBeDialog() && !(mUiFragment instanceof JRPublishFragment);\n }\n\n private boolean shouldBeDialog() {\n return AndroidUtils.isXlarge();\n }\n\n private int getFragmentId() {\n return getIntent().getExtras().getInt(JR_FRAGMENT_ID);\n }\n\n private int getFlowMode() {\n return getIntent().getExtras().getInt(JRUiFragment.JR_FRAGMENT_FLOW_MODE);\n }\n\n private String getSpecificProvider() {\n return getIntent().getExtras().getString(JR_PROVIDER);\n }\n\n @Override\n protected void onResume() {\n super.onResume();\n }\n\n @Override\n protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n LogUtils.logd(TAG, \"requestCode: \" + requestCode + \" resultCode: \" + resultCode);\n super.onActivityResult(requestCode, resultCode, data);\n /* Sometimes this activity starts an activity by proxy for its fragment, in that case we\n * delegate the result to the fragment here.\n */\n if (requestCode <= 1<<16) mUiFragment.onActivityResult(requestCode, resultCode, data);\n /* However, the Fragment API munges activityForResult invocations from fragments by bitshifting\n * the request code up two bytes. This method doesn't handle such request codes; they dispatch\n * by the Fragment API path.\n */\n }\n\n @Override\n public boolean onKeyDown(int keyCode, KeyEvent event) {\n if (AndroidUtils.isCupcake() && keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {\n // Take care of calling this method on earlier versions of\n // the platform where it doesn't exist.\n onBackPressed();\n }\n\n return super.onKeyDown(keyCode, event);\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n if (item.getItemId() == android.R.id.home) {\n onBackPressed();\n return true;\n } else {\n return super.onOptionsItemSelected(item);\n }\n }\n\n // Unfortunately setResult is final so it can't be overridden to track the result-definedness state of\n // the activity, which is used to track unplanned #finish()es and to fire onBackPressed at that time.\n //@Override\n //public void setResult() { }\n /*package*/ void _setResult(int resultCode) {\n setResult(resultCode);\n m_Result = resultCode;\n }\n\n /**\n * @internal\n * Intercepts finish calls triggered by activitySetFinishOnTouchOutside by detecting whether a result has been\n * specified yet.\n */\n @Override\n public void finish() {\n if (m_Result == null) {\n onBackPressed();\n } else {\n super.finish();\n }\n }\n\n @Override\n public void onBackPressed() {\n LogUtils.logd(TAG, \"onBackPressed\");\n\n mUiFragment.onBackPressed();\n }\n\n public static class IllegalFragmentIdException extends RuntimeException {\n int mFragId;\n\n public IllegalFragmentIdException(int fragId) {\n mFragId = fragId;\n }\n\n public String toString() {\n return \"Bad fragment ID: \" + mFragId;\n }\n }\n\n public static Intent createIntentForCurrentScreen(Activity activity, boolean showTitleBar) {\n Intent intent;\n if (AndroidUtils.isSmallNormalOrLargeScreen()) {\n intent = new Intent(activity, Fullscreen.class);\n if (showTitleBar) {\n intent.putExtra(JR_OPERATION_MODE, JR_FULLSCREEN);\n } else {\n intent.putExtra(JR_OPERATION_MODE, JR_FULLSCREEN_NO_TITLE);\n }\n } else { // Honeycomb (because the screen is large+)\n intent = new Intent(activity, JRFragmentHostActivity.class);\n intent.putExtra(JR_OPERATION_MODE, JR_DIALOG);\n }\n return intent;\n }\n\n public static Intent createProviderListIntent(Activity activity) {\n Intent i = createIntentForCurrentScreen(activity, true);\n i.putExtra(JR_FRAGMENT_ID, JR_PROVIDER_LIST);\n return i;\n }\n\n public static Intent createUserLandingIntent(Activity activity) {\n Intent i = createIntentForCurrentScreen(activity, true);\n i.putExtra(JR_FRAGMENT_ID, JR_LANDING);\n return i;\n }\n\n public static Intent createWebViewIntent(Activity activity) {\n Intent i = createIntentForCurrentScreen(activity, false);\n i.putExtra(JR_FRAGMENT_ID, JR_WEBVIEW);\n return i;\n }\n\n /* ~aliases for alternative activity declarations for this activity */\n public static class Fullscreen extends JRFragmentHostActivity {}\n}", "public abstract class JRUiFragment extends Fragment {\n private static final String KEY_MANAGED_DIALOGS = \"jr_managed_dialogs\";\n private static final String KEY_DIALOG_ID = \"jr_dialog_id\";\n private static final String KEY_MANAGED_DIALOG_OPTIONS = \"jr_dialog_options\";\n private static final String KEY_DIALOG_PROGRESS_TEXT = \"jr_progress_dialog_text\";\n private static final String KEY_DIALOG_PROGRESS_CANCELABLE = \"jr_progress_dialog_cancelable\";\n private static final String PARENT_FRAGMENT_EMBEDDED = \"jr_parent_fragment_embedded\";\n \n public static final String JR_FRAGMENT_FLOW_MODE = \"jr_fragment_flow_mode\";\n public static final int JR_FRAGMENT_FLOW_AUTH = 0;\n public static final int JR_FRAGMENT_FLOW_SHARING = 1;\n /**\n * deprecated\n */\n public static final int JR_FRAGMENT_FLOW_BETA_DIRECT_SHARE = 2;\n\n public static final int REQUEST_LANDING = 1;\n public static final int REQUEST_WEBVIEW = 2;\n public static final int DIALOG_ABOUT = 1000;\n public static final int DIALOG_PROGRESS = 1001;\n public static final String JR_ACTIVITY_JSON = \"JRActivityJson\";\n\n private FinishReceiver mFinishReceiver;\n private HashMap<Integer, ManagedDialog> mManagedDialogs = new HashMap<Integer, ManagedDialog>();\n private JRCustomInterfaceConfiguration mCustomInterfaceConfiguration;\n private Integer mFragmentResult;\n\n /*package*/ JRSession mSession;\n /*package*/ final String TAG = getLogTag();\n /*package*/ String getLogTag() { return getClass().getSimpleName(); }\n\n /**\n * @internal\n *\n * @class FinishReceiver\n * Used to listen to \"Finish\" broadcast messages sent by JREngage.cancel*\n **/\n private class FinishReceiver extends BroadcastReceiver {\n private String TAG = JRUiFragment.this.TAG + \"-\" + FinishReceiver.class.getSimpleName();\n\n @Override\n public void onReceive(Context context, Intent intent) {\n String target = intent.getStringExtra(JRFragmentHostActivity.EXTRA_FINISH_FRAGMENT_TARGET);\n\n if (JRUiFragment.this.getClass().toString().equals(target) ||\n target.equals(JRFragmentHostActivity.FINISH_TARGET_ALL)) {\n if (!isEmbeddedMode()) tryToFinishFragment();\n LogUtils.logd(TAG, \"[onReceive] handled\");\n } else {\n LogUtils.logd(TAG, \"[onReceive] ignored\");\n }\n }\n }\n\n private static class ManagedDialog implements Serializable {\n int mId;\n transient Dialog mDialog;\n transient Bundle mOptions;\n boolean mShowing;\n }\n\n @Override\n public void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState) {\n LogUtils.logd(TAG, \"[\" + new Object() {\n }.getClass().getEnclosingMethod().getName() + \"]\");\n super.onInflate(activity, attrs, savedInstanceState);\n\n if (JRSession.getInstance() == null) {\n throw new IllegalStateException(\"You must call JREngage.initInstance before inflating \" +\n \"JREngage fragments.\");\n }\n }\n\n @Override\n public void onAttach(Activity activity) {\n super.onAttach(activity);\n LogUtils.logd(TAG, \"[\" + new Object() {\n }.getClass().getEnclosingMethod().getName() + \"]\");\n\n if (mFinishReceiver == null) mFinishReceiver = new FinishReceiver();\n getActivity().registerReceiver(mFinishReceiver, JRFragmentHostActivity.FINISH_INTENT_FILTER);\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n LogUtils.logd(TAG, \"[onCreate]\");\n\n mSession = JRSession.getInstance();\n if (mSession != null) mSession.setUiIsShowing(true);\n /* Embedded fragments aren't compatible with setRetainInstance, because the parent Activity may\n * not handle config changes */\n if (!isEmbeddedMode()) setRetainInstance(true);\n setHasOptionsMenu(true);\n\n if (getActivity() instanceof JRFragmentHostActivity) {\n if (getCustomTitle() != null) getActivity().setTitle(getCustomTitle());\n actionBarSetDisplayHomeAsUpEnabled(activityGetActionBar(getActivity()), true);\n }\n }\n\n @Override\n public abstract View onCreateView(LayoutInflater inflater,\n ViewGroup container,\n Bundle savedInstanceState);\n\n @Override\n @SuppressWarnings(\"unchecked\")\n public void onActivityCreated(Bundle savedInstanceState) {\n super.onActivityCreated(savedInstanceState);\n LogUtils.logd(TAG, \"[onActivityCreated]\");\n\n mSession = JRSession.getInstance();\n\n if (savedInstanceState != null) {\n mManagedDialogs = (HashMap) savedInstanceState.get(KEY_MANAGED_DIALOGS);\n Parcelable[] p = savedInstanceState.getParcelableArray(KEY_MANAGED_DIALOG_OPTIONS);\n if (mManagedDialogs != null && p != null) {\n for (Parcelable p_ : p) {\n Bundle b = (Bundle) p_;\n mManagedDialogs.get(b.getInt(KEY_DIALOG_ID)).mOptions = b;\n }\n } else {\n mManagedDialogs = new HashMap<Integer, ManagedDialog>();\n }\n }\n\n for (ManagedDialog d : mManagedDialogs.values()) {\n d.mDialog = onCreateDialog(d.mId, d.mOptions);\n if (d.mShowing) d.mDialog.show();\n }\n }\n\n @Override\n public void onStart() {\n LogUtils.logd(TAG, \"[\" + new Object() {\n }.getClass().getEnclosingMethod().getName() + \"]\");\n super.onStart();\n }\n\n @Override\n public void onResume() {\n super.onResume();\n LogUtils.logd(TAG, \"[onResume]\");\n maybeShowHideTaglines();\n if (mCustomInterfaceConfiguration != null) mCustomInterfaceConfiguration.onResume();\n }\n\n @Override\n public void onPause() {\n if (mCustomInterfaceConfiguration != null) mCustomInterfaceConfiguration.onPause();\n LogUtils.logd(TAG, \"[\" + new Object() {\n }.getClass().getEnclosingMethod().getName() + \"]\");\n super.onPause();\n }\n\n @Override\n public void onStop() {\n LogUtils.logd(TAG, \"[\" + new Object() {\n }.getClass().getEnclosingMethod().getName() + \"]\");\n super.onStop();\n }\n\n @Override\n public void onDestroyView() {\n LogUtils.logd(TAG, \"[onDestroyView]\");\n\n for (ManagedDialog d : mManagedDialogs.values()) d.mDialog.dismiss();\n\n super.onDestroyView();\n }\n\n @Override\n public void onDestroy() {\n LogUtils.logd(TAG, \"[onDestroy]\");\n if (mFragmentResult != null) {\n if (getActivity() instanceof JRFragmentHostActivity) {\n ((JRFragmentHostActivity) getActivity())._setResult(mFragmentResult);\n } else if (getTargetFragment() != null) {\n getTargetFragment().onActivityResult(getTargetRequestCode(), mFragmentResult, null);\n }\n }\n\n if (mSession != null) mSession.setUiIsShowing(false);\n\n if (mCustomInterfaceConfiguration != null) mCustomInterfaceConfiguration.onDestroy();\n\n super.onDestroy();\n }\n\n @Override\n public void onDetach() {\n LogUtils.logd(TAG, \"[\" + new Object() {\n }.getClass().getEnclosingMethod().getName() + \"]\");\n if (mFinishReceiver != null) getActivity().unregisterReceiver(mFinishReceiver);\n\n super.onDetach();\n }\n\n /* May be called at any time before onDestroy() */\n @Override\n public void onSaveInstanceState(Bundle outState) {\n LogUtils.logd(TAG, \"[\" + new Object() {\n }.getClass().getEnclosingMethod().getName() + \"]\");\n\n Bundle[] dialogOptions = new Bundle[mManagedDialogs.size()];\n int x = 0;\n for (ManagedDialog d : mManagedDialogs.values()) {\n d.mShowing = d.mDialog.isShowing();\n dialogOptions[x++] = d.mOptions;\n d.mOptions.putInt(KEY_DIALOG_ID, d.mId);\n }\n outState.putSerializable(KEY_MANAGED_DIALOGS, mManagedDialogs);\n outState.putParcelableArray(KEY_MANAGED_DIALOG_OPTIONS, dialogOptions);\n\n if (mCustomInterfaceConfiguration != null) {\n mCustomInterfaceConfiguration.onSaveInstanceState(outState);\n }\n\n super.onSaveInstanceState(outState);\n }\n\n @Override\n public void onConfigurationChanged(Configuration newConfig) {\n LogUtils.logd(TAG, \"[\" + new Object() {\n }.getClass().getEnclosingMethod().getName() + \"]\");\n super.onConfigurationChanged(newConfig);\n }\n\n @Override\n public void onHiddenChanged(boolean hidden) {\n LogUtils.logd(TAG, \"[\" + new Object() {\n }.getClass().getEnclosingMethod().getName() + \"]\");\n super.onHiddenChanged(hidden);\n }\n //--\n\n @Override\n public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {\n super.onCreateOptionsMenu(menu, inflater);\n\n //menu.add(\"test\");\n\n if (mSession == null || mSession.getHidePoweredBy()) {\n Log.e(TAG, \"Bailing out of onCreateOptionsMenu\");\n return;\n }\n\n inflater.inflate(R.menu.jr_about_menu, menu);\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n if (item.getItemId() == R.id.jr_menu_about) {\n showDialog(DIALOG_ABOUT);\n return true;\n } else {\n return super.onOptionsItemSelected(item);\n }\n }\n\n /*package*/ void onFragmentHostActivityCreate(JRFragmentHostActivity jrfh, JRSession session) {\n String uiCustomizationName =\n getArguments().getString(JRFragmentHostActivity.JR_UI_CUSTOMIZATION_CLASS);\n\n if (uiCustomizationName != null) {\n try {\n Class classRef = Class.forName(uiCustomizationName);\n final JRCustomInterface customInterface = (JRCustomInterface) classRef.newInstance();\n if (customInterface instanceof JRCustomInterfaceConfiguration) {\n mCustomInterfaceConfiguration = (JRCustomInterfaceConfiguration) customInterface;\n if (mCustomInterfaceConfiguration.mColorButtons != null) {\n ColorButton.sEnabled = mCustomInterfaceConfiguration.mColorButtons;\n }\n } else if (customInterface instanceof JRCustomInterfaceView) {\n mCustomInterfaceConfiguration = new JRCustomInterfaceConfiguration() {\n {\n //Type safe because the type of the instantiated instance from the\n //class ref is run time type checked\n mProviderListHeader = (JRCustomInterfaceView) customInterface;\n }\n };\n } else {\n Log.e(TAG, \"Unexpected class from: \" + uiCustomizationName);\n //Not possible at the moment, there are only two subclasses of abstract JRCustomInterface\n }\n } catch (ClassNotFoundException e) {\n customSigninReflectionError(uiCustomizationName, e);\n } catch (ClassCastException e) {\n customSigninReflectionError(uiCustomizationName, e);\n } catch (java.lang.InstantiationException e) {\n customSigninReflectionError(uiCustomizationName, e);\n } catch (IllegalAccessException e) {\n customSigninReflectionError(uiCustomizationName, e);\n }\n }\n }\n\n /*package*/ void maybeShowHideTaglines() {\n if (mSession == null || getView() == null) {\n Log.e(TAG, \"Bailing out of maybeShowHideTaglines: mSession: \" + mSession + \" getView(): \"\n + getView());\n return;\n }\n\n boolean hideTagline = mSession.getHidePoweredBy();\n int visibility = hideTagline ? View.GONE : View.VISIBLE;\n\n View tagline = getView().findViewById(R.id.jr_tagline);\n if (tagline != null) tagline.setVisibility(visibility);\n\n View bonusTagline = getView().findViewById(R.id.jr_email_sms_powered_by_text);\n if (bonusTagline != null) bonusTagline.setVisibility(visibility);\n }\n\n /*package*/ ProgressDialog createProgressDialog(Bundle options) {\n ProgressDialog progressDialog = new ProgressDialog(getActivity());\n progressDialog.setIndeterminate(true);\n progressDialog.setMessage(options.getString(KEY_DIALOG_PROGRESS_TEXT));\n return progressDialog;\n }\n\n /*package*/ void showProgressDialog(String displayText) {\n showProgressDialog(displayText, true);\n }\n\n /*package*/ ManagedDialog showProgressDialog(String displayText, boolean cancelable) {\n Bundle opts = new Bundle();\n opts.putString(KEY_DIALOG_PROGRESS_TEXT, displayText);\n opts.putBoolean(KEY_DIALOG_PROGRESS_CANCELABLE, cancelable);\n return showDialog(DIALOG_PROGRESS, opts);\n }\n\n /*package*/ void showProgressDialog() {\n showProgressDialog(getString(R.string.jr_progress_loading));\n }\n\n /*package*/ void dismissProgressDialog() {\n dismissDialog(DIALOG_PROGRESS);\n }\n\n private AlertDialog createAboutDialog() {\n AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());\n builder.setPositiveButton(jr_dialog_ok, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int id) {\n dialog.dismiss();\n }\n });\n\n AlertDialog retval = builder.create();\n View l = retval.getWindow().getLayoutInflater().inflate(R.layout.jr_about_dialog, null);\n retval.setView(l);\n\n return retval;\n }\n\n /*package*/ final boolean isEmbeddedMode() {\n FragmentActivity a = getActivity();\n return a != null && !(a instanceof JRFragmentHostActivity);\n }\n\n /*package*/ Dialog onCreateDialog(int id, Bundle options) {\n Dialog dialog;\n switch (id) {\n case DIALOG_ABOUT:\n dialog = createAboutDialog();\n break;\n case DIALOG_PROGRESS:\n dialog = createProgressDialog(options);\n break;\n default:\n dialog = null;\n }\n return dialog;\n }\n\n /*package*/ void onPrepareDialog(int id, Dialog d, Bundle options) {\n switch (id) {\n case DIALOG_PROGRESS:\n d.setCancelable(options.getBoolean(KEY_DIALOG_PROGRESS_CANCELABLE, true));\n d.setOnCancelListener(null);\n }\n }\n\n /*package*/ void showDialog(int dialogId) {\n showDialog(dialogId, new Bundle());\n }\n\n /*package*/ ManagedDialog showDialog(int dialogId, Bundle options) {\n ManagedDialog d = mManagedDialogs.get(dialogId);\n if (d == null) {\n d = new ManagedDialog();\n d.mDialog = onCreateDialog(dialogId, options);\n d.mId = dialogId;\n mManagedDialogs.put(dialogId, d);\n }\n\n d.mOptions = options;\n onPrepareDialog(dialogId, d.mDialog, options);\n d.mDialog.show();\n //d.mShowing = true; // See also dismissDialog comment\n\n return d;\n }\n\n /*package*/ void dismissDialog(int dialogId) {\n ManagedDialog d = mManagedDialogs.get(dialogId);\n if (d != null) d.mDialog.dismiss();\n }\n\n private void startActivityForFragId(int fragId, int requestCode) {\n startActivityForFragId(fragId, requestCode, null);\n }\n\n /*package*/ int getColor(int colorId) {\n return getResources().getColor(colorId);\n }\n\n private void startActivityForFragId(int fragId, int requestCode, Bundle opts) {\n boolean showTitle;\n switch (fragId) {\n case JRFragmentHostActivity.JR_LANDING:\n showTitle = true;\n break;\n case JRFragmentHostActivity.JR_WEBVIEW:\n showTitle = false;\n break;\n default: throw new JRFragmentHostActivity.IllegalFragmentIdException(fragId);\n }\n\n Intent i = JRFragmentHostActivity.createIntentForCurrentScreen(getActivity(), showTitle);\n i.putExtra(JRFragmentHostActivity.JR_FRAGMENT_ID, fragId);\n i.putExtra(JRUiFragment.PARENT_FRAGMENT_EMBEDDED, isEmbeddedMode());\n i.putExtra(JR_FRAGMENT_FLOW_MODE, getFragmentFlowMode());\n if (opts != null) i.putExtras(opts);\n startActivityForResult(i, requestCode);\n }\n \n private int getFragmentFlowMode() {\n return getArguments().getInt(JR_FRAGMENT_FLOW_MODE);\n }\n \n private void showFragment(Class<? extends JRUiFragment> fragClass, int requestCode) {\n JRUiFragment f;\n try {\n f = fragClass.newInstance();\n } catch (java.lang.InstantiationException e) {\n throw new RuntimeException(e);\n } catch (IllegalAccessException e) {\n throw new RuntimeException(e);\n }\n Bundle args = new Bundle();\n args.putInt(JR_FRAGMENT_FLOW_MODE, getFragmentFlowMode());\n f.setArguments(args);\n f.setTargetFragment(this, requestCode);\n\n getActivity().getSupportFragmentManager().beginTransaction()\n .replace(((ViewGroup) getView().getParent()).getId(), f)\n .addToBackStack(fragClass.getSimpleName())\n .setTransition(FragmentTransaction.TRANSIT_NONE)\n .commit();\n }\n\n /*package*/ void setFragmentResult(int result) {\n mFragmentResult = result;\n }\n \n /*package*/ Integer getFragmentResult() {\n return mFragmentResult;\n }\n\n /*package*/ void finishFragmentWithResult(int result) {\n setFragmentResult(result);\n finishFragment();\n }\n\n /*package*/ void finishFragment() {\n if (getActivity() instanceof JRFragmentHostActivity) {\n if (mFragmentResult != null) ((JRFragmentHostActivity) getActivity())._setResult(mFragmentResult);\n getActivity().finish();\n } else {\n FragmentManager fm = getActivity().getSupportFragmentManager();\n int bsec = fm.getBackStackEntryCount();\n if (bsec > 0 && fm.getBackStackEntryAt(bsec - 1).getName().equals(getLogTag())) {\n fm.popBackStack();\n } else if (bsec > 0) {\n Log.e(TAG, \"Error trying to finish fragment not on top of back stack\");\n fm.popBackStack(getLogTag(), FragmentManager.POP_BACK_STACK_INCLUSIVE);\n } else { // bsec == 0\n // Root fragment, if it's finishing it's because authentication finished?\n fm.beginTransaction()\n .remove(this)\n .setTransition(FragmentTransaction.TRANSIT_NONE)\n .commit();\n }\n }\n }\n\n /*package*/ void showUserLanding() {\n if (getActivity() instanceof JRFragmentHostActivity || isSharingFlow()) {\n startActivityForFragId(JRFragmentHostActivity.JR_LANDING, REQUEST_LANDING);\n } else {\n showFragment(JRLandingFragment.class, REQUEST_LANDING);\n }\n }\n\n /*package*/ void showWebView(boolean forSharingFlow) {\n if (getActivity() instanceof JRFragmentHostActivity || forSharingFlow) {\n Bundle opts = new Bundle();\n opts.putInt(JR_FRAGMENT_FLOW_MODE,\n forSharingFlow ? JR_FRAGMENT_FLOW_SHARING : JR_FRAGMENT_FLOW_AUTH);\n startActivityForFragId(JRFragmentHostActivity.JR_WEBVIEW, REQUEST_WEBVIEW, opts);\n } else {\n showFragment(JRWebViewFragment.class, REQUEST_WEBVIEW);\n }\n }\n\n /*package*/ void showWebView() {\n showWebView(false);\n }\n\n /*package*/ boolean isSharingFlow() {\n return getArguments().getInt(JR_FRAGMENT_FLOW_MODE) == JR_FRAGMENT_FLOW_SHARING;\n }\n\n /*package*/ void tryToFinishFragment() {\n LogUtils.logd(TAG, \"[tryToFinishFragment]\");\n finishFragment();\n }\n\n /*package*/ boolean hasView() {\n return getView() != null;\n }\n\n /*package*/ boolean isSpecificProviderFlow() {\n return getArguments().getString(JRFragmentHostActivity.JR_PROVIDER) != null;\n }\n\n /*package*/ String getSpecificProvider() {\n return getArguments().getString(JRFragmentHostActivity.JR_PROVIDER);\n }\n\n /**\n * @internal\n * Delegated to from JRFragmentHostActivity\n */\n /*package*/ void onBackPressed() {}\n\n private void customSigninReflectionError(String customName, Exception e) {\n Log.e(TAG, \"Can't load custom signin class: \" + customName + \"\\n\", e);\n }\n\n /*package*/ JRCustomInterfaceConfiguration getCustomUiConfiguration() {\n return mCustomInterfaceConfiguration;\n }\n\n /*package*/ void doCustomViewCreate(JRCustomInterfaceView view,\n LayoutInflater inflater,\n Bundle savedInstanceState,\n ViewGroup container) {\n view.doOnCreateView(this,\n getActivity().getApplicationContext(),\n inflater,\n container,\n savedInstanceState);\n }\n\n public void showProgressDialogForCustomView(boolean cancelable,\n DialogInterface.OnCancelListener cancelListener) {\n ManagedDialog md = showProgressDialog(getString(R.string.jr_progress_loading), cancelable);\n md.mDialog.setOnCancelListener(cancelListener);\n }\n\n public void dismissProgressDialogForCustomView() {\n dismissProgressDialog();\n }\n\n /*package*/ String getCustomTitle() {\n return null;\n }\n\n /*package*/ boolean shouldShowTitleWhenDialog() {\n return false;\n }\n}", "public class AndroidUtils {\n public static final String TAG = AndroidUtils.class.getSimpleName();\n private AndroidUtils() {}\n\n public static boolean isSmallNormalOrLargeScreen() {\n int screenConfig = getScreenSize();\n\n // Galaxy Tab 7\" (the first one) reports SCREENLAYOUT_SIZE_NORMAL\n // Motorola Xoom reports SCREENLAYOUT_SIZE_XLARGE\n // Nexus S reports SCREENLAYOUT_SIZE_NORMAL\n\n return screenConfig == Configuration.SCREENLAYOUT_SIZE_NORMAL ||\n screenConfig == Configuration.SCREENLAYOUT_SIZE_SMALL ||\n screenConfig == Configuration.SCREENLAYOUT_SIZE_LARGE;\n }\n\n public static boolean isCupcake() {\n return Build.VERSION.RELEASE.startsWith(\"1.5\");\n }\n\n private static int getAndroidSdkInt() {\n try {\n return Build.VERSION.class.getField(\"SDK_INT\").getInt(null);\n } catch (NoSuchFieldException e) {\n // Must be Cupcake\n return 3;\n } catch (IllegalAccessException e) {\n // Not expected\n throw new RuntimeException(e);\n }\n }\n\n public static String urlEncode(String s) {\n try {\n return URLEncoder.encode(s, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static String urlDecode(String s) {\n try {\n return URLDecoder.decode(s, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static final int SDK_INT = getAndroidSdkInt();\n\n public static ApplicationInfo getApplicationInfo() {\n String packageName = JREngage.getApplicationContext().getPackageName();\n try {\n return JREngage.getApplicationContext().getPackageManager().getApplicationInfo(packageName, 0);\n } catch (PackageManager.NameNotFoundException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static int scaleDipToPixels(int dip) {\n Context c = JREngage.getApplicationContext();\n final float scale = c.getResources().getDisplayMetrics().density;\n return (int) (((float) dip) * scale);\n }\n\n private static int getScreenSize() {\n int screenConfig = JREngage.getApplicationContext().getResources().getConfiguration().screenLayout;\n screenConfig &= Configuration.SCREENLAYOUT_SIZE_MASK;\n return screenConfig;\n }\n\n public static boolean isXlarge() {\n return (getScreenSize() == Configuration.SCREENLAYOUT_SIZE_XLARGE);\n }\n\n public static boolean isLandscape() {\n return JREngage.getApplicationContext().getResources().getConfiguration().orientation ==\n Configuration.ORIENTATION_LANDSCAPE;\n }\n \n public static void activitySetFinishOnTouchOutside(Activity activity, boolean finish) {\n try {\n Method m = activity.getClass().getMethod(\"activitySetFinishOnTouchOutside\", boolean.class);\n m.invoke(activity, finish);\n } catch (NoSuchMethodException e) {\n Log.e(TAG, \"[activitySetFinishOnTouchOutside]\", e);\n } catch (InvocationTargetException e) {\n Log.e(TAG, \"[activitySetFinishOnTouchOutside]\", e);\n } catch (IllegalAccessException e) {\n Log.e(TAG, \"[activitySetFinishOnTouchOutside]\", e);\n }\n }\n\n public static Object activityGetActionBar(Activity a) {\n try {\n Method getActionBar = a.getClass().getMethod(\"getActionBar\");\n return getActionBar.invoke(a);\n } catch (NoSuchMethodException ignore) {\n } catch (InvocationTargetException ignore) {\n } catch (IllegalAccessException ignore) {\n }\n\n return null;\n }\n\n public static void actionBarSetDisplayHomeAsUpEnabled(Object actionBar, boolean arg) {\n if (actionBar == null) return;\n\n try {\n Method m = actionBar.getClass().getMethod(\"setDisplayHomeAsUpEnabled\", boolean.class);\n m.invoke(actionBar, arg);\n } catch (NoSuchMethodException ignore) {\n } catch (InvocationTargetException ignore) {\n } catch (IllegalAccessException ignore) {\n }\n }\n\n public static Drawable newBitmapDrawable(Context c, Bitmap icon) {\n try {\n Class bitmapDrawableClass = Class.forName(\"android.graphics.drawable.BitmapDrawable\");\n Constructor bitmapDrawableConstructor =\n bitmapDrawableClass.getDeclaredConstructor(Resources.class, Bitmap.class);\n return (BitmapDrawable) bitmapDrawableConstructor.newInstance(c.getResources(), icon);\n } catch (NoSuchMethodException e) {\n throw new RuntimeException(e);\n } catch (ClassNotFoundException e) {\n throw new RuntimeException(e);\n } catch (IllegalAccessException e) {\n throw new RuntimeException(e);\n } catch (InstantiationException e) {\n throw new RuntimeException(e);\n } catch (InvocationTargetException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static void bitmapSetDensity(Bitmap icon, int density) {\n try {\n Method setDensity = icon.getClass().getDeclaredMethod(\"setDensity\", int.class);\n setDensity.invoke(icon, density);\n } catch (NoSuchMethodException e) {\n Log.e(TAG, \"Unexpected: \" + e);\n } catch (IllegalAccessException e) {\n Log.e(TAG, \"Unexpected: \" + e);\n } catch (InvocationTargetException e) {\n Log.e(TAG, \"Unexpected: \" + e);\n }\n }\n\n public static String consoleMessageGetMessage(ConsoleMessage consoleMessage) {\n try {\n Method message = consoleMessage.getClass().getMethod(\"message\");\n return (String) message.invoke(consoleMessage);\n // + consoleMessage.sourceId() + consoleMessage.lineNumber();\n } catch (NoSuchMethodException ignore) {\n } catch (InvocationTargetException ignore) {\n } catch (IllegalAccessException ignore) {\n }\n\n Log.e(TAG, \"[consoleMessageGetMessage] unexpected reflection exception\");\n return null;\n }\n\n public static String readAsset(Context c, String fileName) {\n try {\n InputStream is = c.getAssets().open(fileName);\n byte[] buffer = new byte[is.available()];\n //noinspection ResultOfMethodCallIgnored\n is.read(buffer); // buffer is exactly the right size, a guarantee of asset files\n return new String(buffer);\n } catch (IOException ignore) {\n }\n return null;\n }\n\n //public static int getScreenWidth() {\n // DisplayMetrics metrics = new DisplayMetrics();\n // JREngage.getApplicationContext().getWindowManager().getDefaultDisplay().getMetrics(metrics);\n // metrics.get\n //}\n\n public static int colorDrawableGetColor(ColorDrawable d) {\n try {\n Method getColor = d.getClass().getMethod(\"getColor\");\n return (Integer) getColor.invoke(d);\n } catch (NoSuchMethodException ignore) {\n } catch (InvocationTargetException ignore) {\n } catch (IllegalAccessException ignore) {\n } catch (ClassCastException ignore) {\n }\n\n // For some reason the following doesn't work on Android 15, but the above does, and the below\n // works for Android <= 10, so the function as a whole works but is a dirty hack.\n\n Bitmap b = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);\n d.draw(new Canvas(b));\n return b.getPixel(0, 0);\n }\n\n /**\n * @param context a Context for this application, or null to use a cached context if available\n * @return true if this application was compiled as debuggable, false if not or if a Context was not\n * available to evaluate.\n */\n public static boolean isApplicationDebuggable(Context context) {\n if (context != null) {\n return 0 != (context.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE);\n } else {\n context = JREngage.getApplicationContext();\n return context != null && isApplicationDebuggable(context);\n }\n }\n}", "public class LogUtils {\n private LogUtils() {}\n\n public static void logd(String tag, String msg, Throwable tr) {\n if (JREngage.sLoggingEnabled == null || JREngage.sLoggingEnabled) Log.d(tag, msg, tr);\n }\n\n public static void logd(String tag, String msg) {\n if (JREngage.sLoggingEnabled == null || JREngage.sLoggingEnabled) Log.d(tag, msg);\n }\n\n private static void logd(String msg, Throwable t, int stackDepth) {\n if (!(JREngage.sLoggingEnabled == null || JREngage.sLoggingEnabled)) return;\n if (t != null) {\n Log.d(\"[\" + getLogTag(stackDepth) + \"]\", msg, t);\n } else {\n Log.d(\"[\" + getLogTag(stackDepth) + \"]\", msg);\n }\n }\n\n public static void logd(String msg, Throwable t) {\n logd(msg, t, 2);\n }\n\n public static void logd(String msg) {\n logd(msg, null, 2);\n }\n\n public static void logd() {\n logd(\"\", null, 2);\n }\n\n public static void loge(String msg) {\n loge(msg, null, 2);\n }\n\n public static void loge(String msg, Throwable t) {\n loge(msg, t, 2);\n }\n\n private static void loge(String msg, Throwable t, int stackDepth) {\n if (t != null) {\n Log.e(\"[\" + getLogTag(stackDepth) + \"]\", msg, t);\n } else {\n Log.e(\"[\" + getLogTag(stackDepth) + \"]\", msg);\n }\n }\n\n private static String getLogTag(int stackDepth) {\n String method;\n try {\n throw new Exception();\n } catch (Exception e) {\n e.fillInStackTrace();\n StackTraceElement stackTraceElement = e.getStackTrace()[stackDepth + 1];\n method = stackTraceElement.getClassName() + \".\" + stackTraceElement.getMethodName() + \":\"\n + stackTraceElement.getLineNumber();\n }\n return method;\n }\n\n public static void throwDebugException(RuntimeException debugException) {\n if (AndroidUtils.isApplicationDebuggable(null)) {\n throw debugException;\n } else {\n LogUtils.loge(\"Unexpected exception\", debugException);\n }\n }\n}", "public static void throwDebugException(RuntimeException debugException) {\n if (AndroidUtils.isApplicationDebuggable(null)) {\n throw debugException;\n } else {\n LogUtils.loge(\"Unexpected exception\", debugException);\n }\n}" ]
import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.text.TextUtils; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.widget.FrameLayout; import android.widget.LinearLayout; import com.janrain.android.engage.net.async.HttpResponseHeaders; import com.janrain.android.engage.session.JRProvider; import com.janrain.android.engage.session.JRSession; import com.janrain.android.engage.session.JRSessionDelegate; import com.janrain.android.engage.types.JRActivityObject; import com.janrain.android.engage.types.JRDictionary; import com.janrain.android.engage.ui.JRCustomInterface; import com.janrain.android.engage.ui.JRFragmentHostActivity; import com.janrain.android.engage.ui.JRPublishFragment; import com.janrain.android.engage.ui.JRUiFragment; import com.janrain.android.utils.AndroidUtils; import com.janrain.android.utils.LogUtils; import com.janrain.android.utils.ThreadUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import static com.janrain.android.R.string.jr_git_describe; import static com.janrain.android.utils.LogUtils.throwDebugException;
// * @param hostActivity The android.support.v4.app.FragmentActivity which will host the publishing fragment // * @param containerId The resource ID of a FrameLayout to embed the publishing fragment in // */ //public void showSocialSignInFragment(FragmentActivity hostActivity, // int containerId) { // showSocialSignInFragment(hostActivity, containerId, false, null, null, null, null); //} ///** // * Create a new android.support.v4.Fragment for social sign-in. Use this if you wish to manage the // * FragmentTransaction yourself. // * // * @return The created Fragment, or null upon error (caused by library configuration failure) // */ //public JRProviderListFragment createSocialSignInFragment() { // if (checkSessionDataError()) return null; // // JRProviderListFragment jplf = new JRProviderListFragment(); // // Bundle arguments = new Bundle(); // arguments.putInt(JRUiFragment.JR_FRAGMENT_FLOW_MODE, JRUiFragment.JR_FRAGMENT_FLOW_AUTH); // jplf.setArguments(arguments); // jplf.setArguments(arguments); // return jplf; //} /*@}*/ private void showFragment(Fragment fragment, FragmentActivity hostActivity, int containerId, boolean addToBackStack, Integer transit, Integer transitRes, Integer customEnterAnimation, Integer customExitAnimation) { View fragmentContainer = hostActivity.findViewById(containerId); if (!(fragmentContainer instanceof FrameLayout)) { throw new IllegalStateException("No FrameLayout with ID: " + containerId + ". Found: " + fragmentContainer); } FragmentManager fm = hostActivity.getSupportFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); if (transit != null) ft.setTransition(transit); if (transitRes != null) ft.setTransitionStyle(transitRes); if (customEnterAnimation != null || customExitAnimation != null) { //noinspection ConstantConditions ft.setCustomAnimations(customEnterAnimation, customExitAnimation); } ft.replace(fragmentContainer.getId(), fragment, fragment.getClass().getSimpleName()); if (addToBackStack) ft.addToBackStack(fragment.getClass().getSimpleName()); ft.commit(); } /** @anchor enableProviders **/ /** * @name Enable a Subset of Providers * Methods that configure at runtime a subset of providers to use with the JREngage dialogs. These methods * can only configure a subset of the configured and enabled providers found on your Engage application's * dashboard. **/ /*@{*/ /** * Sets the list of providers that are enabled for authentication. This does not supersede your * RP's deplyoment settings for Android sign-in, as configured on rpxnow.com, it is a supplemental * filter to that configuration. * * @param enabledProviders A list of providers which will be enabled. This set will be intersected with * the set of providers configured on the Engage Dashboard, that intersection * will be the providers that are actually available to the end-user. */ public void setEnabledAuthenticationProviders(final List<String> enabledProviders) { blockOnInitialization(); mSession.setEnabledAuthenticationProviders(enabledProviders); } /** * Convenience variant of setEnabledAuthenticationProviders(List&lt;String>) * * @param enabledProviders An array of providers which will be enabled. This set will be intersected with * the set of providers configured on the Engage Dashboard, that intersection * will be the providers that are actually available to the end-user. */ public void setEnabledAuthenticationProviders(final String[] enabledProviders) { blockOnInitialization(); mSession.setEnabledAuthenticationProviders(Arrays.asList(enabledProviders)); } /** * Sets the list of providers that are enabled for social sharing. This does not supersede your * RP's deplyoment settings for Android social sharing, as configured on rpxnow.com, it is a * supplemental filter to that configuration. * * @param enabledSharingProviders Which providers to enable for authentication, null for all providers. * A list of social sharing providers which will be enabled. This set will * be intersected with the set of providers configured on the Engage * Dashboard, that intersection will be the providers that are actually * available to the end-user. */ public void setEnabledSharingProviders(final List<String> enabledSharingProviders) { blockOnInitialization(); mSession.setEnabledSharingProviders(enabledSharingProviders); } /** * Convenience variant of setEnabledSharingProviders(List&lt;String>) * * @param enabledSharingProviders An array of social sharing providers which will be enabled. This set * will be intersected with the set of providers configured on the Engage * Dashboard, that intersection will be the providers that are actually * available to the end-user. */ public void setEnabledSharingProviders(final String[] enabledSharingProviders) { blockOnInitialization(); mSession.setEnabledSharingProviders(Arrays.asList(enabledSharingProviders)); } /*@}*/
private JRSessionDelegate mJrsd = new JRSessionDelegate.SimpleJRSessionDelegate() {
2
jeffsvajlenko/BigCloneEval
src/tasks/EvaluateRecall.java
[ "public interface CloneMatcher {\n\tpublic boolean isDetected(Clone clone) throws SQLException;\n\tpublic void close() throws SQLException;\n\t\n\tpublic static String getTableName(long toolid) {\n\t\treturn \"tool_\" + toolid + \"_clones\";\n\t}\n\t\n\tpublic static CloneMatcher load(long toolid, String clazz, String params) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {\n\t\t//long time = System.currentTimeMillis();\n\t\tClass<?> mClass = Class.forName(\"cloneMatchingAlgorithms.\" + clazz);\n\t\tConstructor<?> constructor = mClass.getConstructor(long.class, String.class);\n\t\tCloneMatcher matcher = (CloneMatcher) constructor.newInstance(toolid, params);\n\t\t//time = System.currentTimeMillis() - time;\n\t\t//System.out.println(\"TIME: \" + time);\n\t\treturn matcher;\n\t}\n\t\n}", "public class CoverageMatcher implements CloneMatcher {\n\t\n\tprivate Connection conn;\n\tprivate PreparedStatement stmt;\n\t\n\tprivate long toolid;\n\tprivate Integer tolerence;\n\tprivate Double coverage;\n\tprivate Double dtolerence;\n\t\n\tpublic String toString() {\n\t\tString str = \"\";\n\t\tstr += \"Coverage Matcher. Coverage Ratio = \" + coverage + \", minimum raito is of reference clone: \" + dtolerence;\n\t\treturn str;\n\t}\n\t\n\tpublic CoverageMatcher(long toolid, String init) throws IllegalArgumentException, SQLException {\n\t\tthis.toolid = toolid;\n\t\tString [] options = init.split(\"\\\\s+\");\n\t\tif(options.length != 1 && options.length != 3)\n\t\t\tthrow new IllegalArgumentException(\"Should take 1 or 3 parameters.\");\n\t\t\n\t\tthis.coverage = Double.parseDouble(options[0]);\n\t\tthis.tolerence = null;\n\t\tthis.dtolerence = null;\n\t\t\n\t\tif(options.length == 3) {\n\t\t\tif(options[1].equals(\"line\")) {\n\t\t\t\tthis.tolerence = Integer.parseInt(options[2]);\n\t\t\t} else if (options[1].equals(\"ratio\")) {\n\t\t\t\tthis.dtolerence = Double.parseDouble(options[2]);\n\t\t\t} else\n\t\t\t\tthrow new IllegalArgumentException(\"Illegal option: \" + options[1]);\n\t\t}\n\t\tinit();\n\t}\n\t\n\tpublic CoverageMatcher(long toolid, double coverage, Integer tolerence, Double dtolerence) throws SQLException {\n\t\tthis.toolid = toolid;\n\t\tthis.tolerence = tolerence;\n\t\tthis.coverage = coverage;\n\t\tthis.dtolerence = dtolerence;\n\t\tinit();\n\t}\n\t\n\tprivate void init() throws SQLException {\n\t\tString sql = \"SELECT 1 FROM \" + CloneMatcher.getTableName(this.toolid) + \" where type1 = ? and name1 = ? and \"\n\t\t\t\t+ \"(least(?,endline1)-greatest(?,startline1)+1)/? >= \" + coverage + \" \"\n\t\t\t\t+ \"and type2 = ? and name2 = ? and \"\n\t\t\t\t+ \"(least(?,endline2)-greatest(?,startline2)+1)/? >= \" + coverage;\n\t\tif(tolerence != null) {\n\t\t\tsql += \" AND startline1 >= ? AND endline1 <= ? AND startline2 >= ? AND endline2 <= ?\";\n\t\t} else if(dtolerence != null) {\n\t\t\tsql += \" AND (least(?,endline1)-greatest(?,startline1)+1)/(1.0*(endline1-startline1+1)) >= \" + dtolerence;\n\t\t\tsql += \" AND (least(?,endline2)-greatest(?,startline2)+1)/(1.0*(endline2-startline2+1)) >= \" + dtolerence;\n\t\t}\n\t\tthis.conn = ToolsDB.getConnection();\n\t\tthis.stmt = conn.prepareStatement(sql);\n\t}\n\t\n\t@Override\n\tpublic boolean isDetected(Clone clone) throws SQLException {\n\t\tClone alt = new Clone(clone.getFunction_id_two(), clone.getFunction_id_one());\n\t\treturn isDetected_helper(clone) || isDetected_helper(alt);\n\t}\n\t\n\tprivate boolean isDetected_helper(Clone clone) throws SQLException {\n\t\tboolean retval = false;\n\t\tFunction f1 = Functions.get(clone.getFunction_id_one());\n\t\tFunction f2 = Functions.get(clone.getFunction_id_two());\n\t\t\n\t\tstmt.setString(1, f1.getType());\n\t\tstmt.setString(2, f1.getName());\n\t\tstmt.setInt(3, f1.getEndline());\n\t\tstmt.setInt(4, f1.getStartline());\n\t\tstmt.setDouble(5, f1.getEndline() - f1.getStartline() + 1);\n\t\t\n\t\tstmt.setString(6, f2.getType());\n\t\tstmt.setString(7, f2.getName());\n\t\tstmt.setInt(8, f2.getEndline());\n\t\tstmt.setInt(9, f2.getStartline());\n\t\tstmt.setDouble(10, f2.getEndline() - f2.getStartline() + 1);\n\t\t\n\t\tif(tolerence != null) {\n\t\t\tstmt.setInt(12, f1.getStartline() - tolerence);\n\t\t\tstmt.setInt(13, f1.getEndline() + tolerence);\n\t\t\tstmt.setInt(14, f2.getStartline() - tolerence);\n\t\t\tstmt.setInt(15, f2.getEndline() + tolerence);\n\t\t} else if(dtolerence != null) {\n\t\t\tstmt.setInt(12, f1.getEndline());\n\t\t\tstmt.setInt(13, f1.getStartline());\n\t\t\tstmt.setInt(14, f2.getEndline());\n\t\t\tstmt.setInt(15, f2.getStartline());\n\t\t}\n\t\t\n\t\tResultSet rs = stmt.executeQuery();\n\t\tif(rs.next()) {\n\t\t\tretval = true;\n\t\t}\n\t\trs.close();\n\t\t\n\t\treturn retval;\n\t}\n\n\t@Override\n\tpublic void close() throws SQLException {\n\t\tstmt.close();\n\t\tconn.close();\n\t\tstmt = null;\n\t\tconn = null;\n\t}\n\t\n}", "public class Clones {\n\t\n\tpublic static long numClones(long id) throws SQLException {\n\t\tlong retval = 0;\n\t\tString sql = \"SELECT count(1) FROM tool_\" + id + \"_clones\";\n\t\tConnection conn = ToolsDB.getConnection();\n\t\tStatement stmt = conn.createStatement();\n\t\tResultSet rs = stmt.executeQuery(sql);\n\t\tif(rs.next())\n\t\t\tretval = rs.getLong(1);\n\t\tstmt.close();\n\t\tconn.close();\n\t\treturn retval;\n\t}\n\t\n\tpublic static int clearClones(long id) throws SQLException {\n\t\tConnection conn = ToolsDB.getConnection();\n\t\tString sql = \"DELETE FROM tool_\" + id + \"_clones\";\n\t\tStatement stmt = conn.createStatement();\n\t\tint retval = stmt.executeUpdate(sql);\n\t\tstmt.close();\n\t\tconn.close();\n\t\treturn retval;\n\t}\n\t\n\tpublic static long importClones(long id, Path path) throws IOException, SQLException {\n\t\t// Import\n\t\tConnection conn = ToolsDB.getConnection();\n\t\tString sql = \"INSERT INTO tool_\" + id + \"_clones SELECT * FROM csvread('\" + path.toString() + \"','type1,name1,startline1,endline1,type2,name2,startline2,endline2')\";\n\t\tStatement stmt = conn.createStatement();\n\t\tlong retval = stmt.executeUpdate(sql);\n\t\tconn.close();\n\t\treturn retval;\n\t}\n\t\n}", "public class Tool {\n\t\n\tprivate long id;\n\tprivate String name;\n\tprivate String description;\n\t\n\tpublic Tool(long id, String name, String description) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.name = name;\n\t\tthis.description = description;\n\t}\n\n\tpublic long getId() {\n\t\treturn id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\n\tpublic String getDescription() {\n\t\treturn description;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((description == null) ? 0 : description.hashCode());\n\t\tresult = prime * result + (int) (id ^ (id >>> 32));\n\t\tresult = prime * result + ((name == null) ? 0 : name.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tTool other = (Tool) obj;\n\t\tif (description == null) {\n\t\t\tif (other.description != null)\n\t\t\t\treturn false;\n\t\t} else if (!description.equals(other.description))\n\t\t\treturn false;\n\t\tif (id != other.id)\n\t\t\treturn false;\n\t\tif (name == null) {\n\t\t\tif (other.name != null)\n\t\t\t\treturn false;\n\t\t} else if (!name.equals(other.name))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\t\n}", "public class Tools {\n\t\n\tpublic static boolean exists(long id) throws SQLException {\n\t\tTool tool = getTool(id);\n\t\tif(tool == null) {\n\t\t\treturn false;\n\t\t} else {\n\t\t\treturn true;\n\t\t}\n\t}\n\t\n\tpublic static void dropall() throws SQLException {\t\t\n\t\tConnection conn = ToolsDB.getConnection();\n\t\tStatement stmt = conn.createStatement();\n\t\tString sql = \"DROP ALL OBJECTS\";\n\t\tstmt.execute(sql);\n\t\tstmt.close();\n\t\tconn.close();\n\t}\n\t\n\tpublic static void init() throws SQLException {\n\t\tdropall();\n\t\tString sql = \"CREATE TABLE tools ( name character varying NOT NULL, description character varying NOT NULL, id identity NOT NULL);\";\n\t\tConnection conn = ToolsDB.getConnection();\n\t\tStatement stmt = conn.createStatement();\n\t\tstmt.executeUpdate(sql);\n\t\tstmt.close();\n\t\tconn.close();\n\t}\n\t\n\tpublic static boolean deleteToolAndData(long id) throws SQLException {\n\t\t\n\t\t// Remove Tool\n\t\tString sql = \"DELETE FROM tools WHERE id = \" + id;\n\t\tConnection conn = ToolsDB.getConnection();\n\t\tStatement stmt = conn.createStatement();\n\t\tint num = stmt.executeUpdate(sql);\n\t\tconn.close();\n\t\tif(num == 0) {\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\t// Remove Table\n\t\tsql = \"DROP TABLE tool_\" + id + \"_clones\";\n\t\tstmt.execute(sql);\n\t\tconn.close();\n\t\treturn true;\n\t}\n\t\n\tpublic static List<Tool> getTools() throws SQLException {\n\t\tList<Tool> retval = new LinkedList<Tool>();\n\t\tString sql = \"SELECT id, name, description FROM tools ORDER BY id\";\n\t\tConnection conn = ToolsDB.getConnection();\n\t\tStatement stmt = conn.createStatement();\n\t\tResultSet rs = stmt.executeQuery(sql);\n\t\twhile(rs.next()) {\n\t\t\tretval.add(new Tool(rs.getLong(1), rs.getString(2), rs.getString(3)));\n\t\t}\n\t\trs.close();\n\t\tstmt.close();\n\t\tconn.close();\n\t\treturn retval;\n\t}\n\t\n\tpublic static Tool getTool(long id) throws SQLException {\n\t\tTool retval;\n\t\tString sql = \"SELECT id, name, description FROM tools WHERE id = \" + id;\n\t\tConnection conn = ToolsDB.getConnection();\n\t\tStatement stmt = conn.createStatement();\n\t\tResultSet rs = stmt.executeQuery(sql);\n\t\tif(rs.next()) {\n\t\t\tretval = new Tool(rs.getLong(1), rs.getString(2), rs.getString(3));\n\t\t} else {\n\t\t\tretval = null;\n\t\t}\n\t\trs.close();\n\t\tstmt.close();\n\t\tconn.close();\n\t\treturn retval;\n\t}\n\t\n\tpublic static long addTool(String name, String description) throws SQLException {\n\t// Add Tool\n\t\tString sql = \"INSERT INTO tools (name, description) VALUES (?,?)\";\n\t\tConnection conn = ToolsDB.getConnection();\n\t\tPreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);\n\t\tstmt.setString(1, name);\n\t\tstmt.setString(2, description);\n\t\tstmt.executeUpdate();\n\t\tResultSet rs = stmt.getGeneratedKeys();\n\t\trs.next();\n\t\tlong id = rs.getLong(1);\n\t\trs.close();\n\t\tstmt.close();\n\t\t\n\t// Add Clones Table and its index\n\t\tStatement stmt2 = conn.createStatement();\n\t\tsql = \"CREATE TABLE tool_\" + id + \"_clones (type1 character varying NOT NULL, name1 character varying NOT NULL, startline1 integer NOT NULL, endline1 integer NOT NULL, type2 character varying NOT NULL, name2 character varying NOT NULL, startline2 integer NOT NULL, endline2 integer NOT NULL);\";\n\t\tstmt2.execute(sql);\n\t\tsql = \"CREATE INDEX ON tool_\" + id + \"_clones (type1, name1, startline1, endline1, type2, name2, startline2, endline2)\";\n\t\tstmt2.execute(sql);\n\t\tsql = \"CREATE INDEX ON tool_\" + id + \"_clones (type1, name1, type2, name2)\";\n\t\tstmt2.execute(sql);\n\t\tstmt2.close();\n\t\t\n\t\tconn.close();\n\t\treturn id;\n\t}\n\t\n}", "public class ToolEvaluator implements Serializable {\n\n\tpublic void close() throws SQLException {\n\t\tthis.matcher.close();\n\t}\n\t\n\tpublic String toString() {\n\t\tString str;\n\t\tstr = \" Tool ID: \" + tool_id;\n\t\tstr += \"\\n\";\n\t\tstr += \" Matcher: \" + matcher.toString();\n\t\tstr += \"\\n\";\n\t\tstr += \" MinSize: \" + min_size;\n\t\tstr += \"\\n\";\n\t\tstr += \" MaxSize: \" + max_size;\n\t\tstr += \"\\n\";\n\t\tstr += \" MinPrettySize: \" + min_pretty_size;\n\t\tstr += \"\\n\";\n\t\tstr += \" MaxPrettySize: \" + max_pretty_size;\n\t\tstr += \"\\n\";\n\t\tstr += \" MinTokens: \" + min_tokens;\n\t\tstr += \"\\n\";\n\t\tstr += \" MaxTokens: \" + max_tokens;\n\t\tstr += \"\\n\";\n\t\tstr += \" MinJudges: \" + min_judges;\n\t\tstr += \"\\n\";\n\t\tstr += \" MinConfidence: \" + min_confidence;\n\t\tstr += \"\\n\";\n\t\tif(similarity_type == ToolEvaluator.SIMILARITY_TYPE_AVG) {\n\t\tstr += \"SimilarityType: SIMILARITY_TYPE_AVG\";\n\t\t} else if (similarity_type == ToolEvaluator.SIMILARITY_TYPE_BOTH) {\n\t\tstr += \"SimilarityType: SIMILARITY_TYPE_BOTH\";\n\t\t} else if (similarity_type == ToolEvaluator.SIMILARITY_TYPE_LINE) {\n\t\tstr += \"SimilarityType: SIMILARITY_TYPE_LINE\";\n\t\t} else if (similarity_type == ToolEvaluator.SIMILARITY_TYPE_TOKEN) {\n\t\tstr += \"SimilarityType: SIMILARITY_TYPE_TOKEN\";\n\t\t}\n\t\tstr += \"\\n\";\n\t\treturn str;\n\t}\n\t\n\tprivate static final long serialVersionUID = 1L;\n\t\n\tprivate Long tool_id;\n\tprivate CloneMatcher matcher;\n\tprivate Integer min_size;\n\tprivate Integer max_size;\n\tprivate Integer min_pretty_size;\n\tprivate Integer max_pretty_size;\n\tprivate Integer min_tokens;\n\tprivate Integer max_tokens;\n\tprivate Integer min_judges;\n\tprivate Integer min_confidence;\n\tprivate int similarity_type;\n\tprivate boolean include_internal = false;\n\t\n\tprivate Set<Long> functionality_ids;\n\t\n\tHashMap<Long,Integer> numClones_type1_inter;\n\tHashMap<Long,Integer> numDetected_type1_inter;\n\t\n\tHashMap<Long,Integer> numClones_type1_intra;\n\tHashMap<Long,Integer> numDetected_type1_intra;\n\t\n\tHashMap<Long,Integer> numClones_type2c_inter;\n\tHashMap<Long,Integer> numDetected_type2c_inter;\n\t\n\tHashMap<Long,Integer> numClones_type2c_intra;\n\tHashMap<Long,Integer> numDetected_type2c_intra;\n\t\n\tHashMap<Long,Integer> numClones_type2b_inter;\n\tHashMap<Long,Integer> numDetected_type2b_inter;\n\t\n\tHashMap<Long,Integer> numClones_type2b_intra;\n\tHashMap<Long,Integer> numDetected_type2b_intra;\n\t\n\tHashMap<Long,Integer>[] numClones_type3_inter;\n\tHashMap<Long,Integer>[] numDetected_type3_inter; // index, similarity ranges: [0-5), [5,10), [10,15), ..., [95-100]... on indexies 0 through 18\n\t\n\tHashMap<Long,Integer>[] numClones_type3_intra;\n\tHashMap<Long,Integer>[] numDetected_type3_intra;\n\t\n\tHashMap<Long, Integer> numClones_false_inter;\n\tHashMap<Long, Integer> numDetected_false_inter;\n\t\n\tHashMap<Long,Integer> numClones_false_intra;\n\tHashMap<Long,Integer> numDetected_false_intra;\n\t\n\tpublic static final int SIMILARITY_TYPE_TOKEN = 0;\n\tpublic static final int SIMILARITY_TYPE_LINE = 1;\n\tpublic static final int SIMILARITY_TYPE_BOTH = 2;\n\tpublic static final int SIMILARITY_TYPE_AVG = 3;\n\n// All Clones\n\t\n\tpublic int getNumClones_inter(long functionality_id) throws SQLException {\n\t\tint numClones = 0;\n\t\tnumClones += getNumClones_type1_inter(functionality_id);\n\t\tnumClones += getNumClones_type2c_inter(functionality_id);\n\t\tnumClones += getNumClones_type2b_inter(functionality_id);\n\t\tnumClones += getNumClones_type3_inter(functionality_id);\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_intra(long functionality_id) throws SQLException {\n\t\tint numClones = 0;\n\t\tnumClones += getNumClones_type1_intra(functionality_id);\n\t\tnumClones += getNumClones_type2c_intra(functionality_id);\n\t\tnumClones += getNumClones_type2b_intra(functionality_id);\n\t\tnumClones += getNumClones_type3_intra(functionality_id);\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones(long functionality_id) throws SQLException {\n\t\tint numClones = 0;\n\t\tnumClones += getNumClones_type1(functionality_id);\n\t\tnumClones += getNumClones_type2c(functionality_id);\n\t\tnumClones += getNumClones_type2b(functionality_id);\n\t\tnumClones += getNumClones_type3(functionality_id);\n\t\treturn numClones;\n\t}\n\t\t\n\t\n\tpublic int getNumDetected_inter(long functionality_id) throws SQLException {\n\t\tint numDetected = 0;\n\t\tnumDetected += this.getNumDetected_type1_inter(functionality_id);\n\t\tnumDetected += this.getNumDetected_type2_inter(functionality_id);\n\t\tnumDetected += this.getNumDetected_type3_inter(functionality_id);\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_intra(long functionality_id) throws SQLException {\n\t\tint numDetected = 0;\n\t\tnumDetected += this.getNumDetected_type1_intra(functionality_id);\n\t\tnumDetected += this.getNumDetected_type2_intra(functionality_id);\n\t\tnumDetected += this.getNumDetected_type3_intra(functionality_id);\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected(long functionality_id) throws SQLException {\n\t\tint numDetected = 0;\n\t\tnumDetected += this.getNumDetected_type1(functionality_id);\n\t\tnumDetected += this.getNumDetected_type2(functionality_id);\n\t\tnumDetected += this.getNumDetected_type3(functionality_id);\n\t\treturn numDetected;\n\t}\n\t\n\t\n\tpublic double getRecall_inter(long functionality_id) throws SQLException {\n\t\tint numClones = this.getNumClones_inter(functionality_id);\n\t\tint numDetected = this.getNumDetected_inter(functionality_id);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_intra(long functionality_id) throws SQLException {\n\t\tint numClones = this.getNumClones_intra(functionality_id);\n\t\tint numDetected = this.getNumDetected_intra(functionality_id);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall(long functionality_id) throws SQLException {\n\t\tint numClones = this.getNumClones(functionality_id);\n\t\tint numDetected = this.getNumDetected(functionality_id);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic int getNumClones_inter() throws SQLException {\n\t\tint numClones = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tnumClones += this.getNumClones_inter(id);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_intra() throws SQLException {\n\t\tint numClones = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tnumClones += this.getNumClones_intra(id);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones() throws SQLException {\n\t\tint numClones = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tnumClones += this.getNumClones(id);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\t\n\tpublic int getNumDetected_inter() throws SQLException {\n\t\tint numDetected = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tnumDetected += this.getNumDetected_inter(id);\n\t\t}\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_intra() throws SQLException {\n\t\tint numDetected = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tnumDetected += this.getNumDetected_intra(id);\n\t\t}\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected() throws SQLException {\n\t\tint numDetected = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tnumDetected += this.getNumDetected(id);\n\t\t}\n\t\treturn numDetected;\n\t}\n\t\n\t\n\tpublic double getRecall_inter() throws SQLException {\n\t\tint numClones = getNumClones_inter();\n\t\tint numDetected = getNumDetected_inter();\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_intra() throws SQLException {\n\t\tint numClones = getNumClones_intra();\n\t\tint numDetected = getNumDetected_intra();\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall() throws SQLException {\n\t\tint numClones = getNumClones();\n\t\tint numDetected = getNumDetected();\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_avg() throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getRecall(id);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\tpublic double getRecall_avg_inter() throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getRecall_inter(id);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\tpublic double getRecall_avg_intra() throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getRecall_intra(id);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\t\n// False\n\tpublic int getNumClones_false_inter(long functionality_id) throws SQLException {\n\t\tif(!numClones_false_inter.containsKey(functionality_id)) {\n\t\t\tint numClones = EvaluateTools.numFalsePositives(functionality_id, this.min_judges, this.min_confidence, EvaluateTools.INTER_PROJECT_CLONES);\n\t\t\tnumClones_false_inter.put(functionality_id, numClones);\n\t\t}\n\t\treturn numClones_false_inter.get(functionality_id);\n\t}\n\tpublic int getNumClones_false_intra(long functionality_id) throws SQLException {\n\t\tif(!numClones_false_intra.containsKey(functionality_id)) {\n\t\t\tint numClones = EvaluateTools.numFalsePositives(functionality_id, this.min_judges, this.min_confidence, EvaluateTools.INTRA_PROJECT_CLONES);\n\t\t\tnumClones_false_intra.put(functionality_id, numClones);\n\t\t}\n\t\treturn numClones_false_intra.get(functionality_id);\n\t}\n\tpublic int getNumClones_false(long functionality_id) throws SQLException {\n\t\treturn getNumClones_false_inter(functionality_id) + getNumClones_false_intra(functionality_id);\n\t}\n\t\t\n\t\n\tpublic int getNumDetected_false_inter(long functionality_id) throws SQLException {\n\t\tif(!numDetected_false_inter.containsKey(functionality_id)) {\n\t\t\tint numDetected = EvaluateTools.numFalseDetected(tool_id, functionality_id, this.min_judges, this.min_confidence, EvaluateTools.INTER_PROJECT_CLONES, this.matcher);\n\t\t\tnumDetected_false_inter.put(functionality_id, numDetected);\n\t\t}\n\t\treturn numDetected_false_inter.get(functionality_id);\n\t}\n\tpublic int getNumDetected_false_intra(long functionality_id) throws SQLException {\n\t\tif(!numDetected_false_intra.containsKey(functionality_id)) {\n\t\t\tint numDetected = EvaluateTools.numFalseDetected(tool_id, functionality_id, this.min_judges, this.min_confidence, EvaluateTools.INTRA_PROJECT_CLONES, this.matcher);\n\t\t\tnumDetected_false_intra.put(functionality_id, numDetected);\n\t\t}\n\t\treturn numDetected_false_intra.get(functionality_id);\n\t}\n\tpublic int getNumDetected_false(long functionality_id) throws SQLException {\n\t\treturn getNumDetected_false_inter(functionality_id) + getNumDetected_false_intra(functionality_id);\n\t}\n\t\n\t\n\tpublic int getNumClones_false_inter() throws SQLException {\n\t\tint numFalse = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tnumFalse += getNumClones_false_inter(id);\n\t\t}\n\t\treturn numFalse;\n\t}\n\tpublic int getNumClones_false_intra() throws SQLException {\n\t\tint numFalse = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tnumFalse += getNumClones_false_intra(id);\n\t\t}\n\t\treturn numFalse;\n\t}\n\tpublic int getNumClones_false() throws SQLException {\n\t\treturn getNumClones_false_inter() + getNumClones_false_intra();\n\t}\n\t\n\t\n\tpublic int getNumDetected_false_inter() throws SQLException {\n\t\tint numDetected = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tnumDetected += getNumDetected_false_inter(id);\n\t\t}\n\t\treturn numDetected;\n\t}\n\tpublic int getNumDetected_false_intra() throws SQLException {\n\t\tint numDetected = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tnumDetected += getNumDetected_false_intra(id);\n\t\t}\n\t\treturn numDetected;\n\t}\n\tpublic int getNumDetected_false() throws SQLException {\n\t\treturn getNumDetected_false_inter() + getNumDetected_false_intra();\n\t}\n\t\n\t\n\tpublic double getRecall_false_inter(long functionality_id) throws SQLException {\n\t\tint numDetected_false = this.getNumDetected_false_inter(functionality_id);\n\t\tint numClones_false = this.getNumClones_false_inter(functionality_id);\n\t\treturn 1.0*numDetected_false/numClones_false;\n\t}\n\tpublic double getRecall_false_intra(long functionality_id) throws SQLException {\n\t\tint numDetected_false = this.getNumDetected_false_intra(functionality_id);\n\t\tint numClones_false = this.getNumClones_false_intra(functionality_id);\n\t\treturn 1.0*numDetected_false/numClones_false;\n\t}\n\tpublic double getRecall_false(long functionality_id) throws SQLException {\n\t\tint numDetected_false = this.getNumDetected_false(functionality_id);\n\t\tint numClones_false = this.getNumClones_false(functionality_id);\n\t\treturn 1.0*numDetected_false/numClones_false;\n\t}\n\t\n\t\n\tpublic double getRecall_false_inter() throws SQLException {\n\t\tint numDetected_false = this.getNumDetected_false_inter();\n\t\tint numClones_false = this.getNumClones_false_inter();\n\t\treturn 1.0*numDetected_false/numClones_false;\n\t}\n\tpublic double getRecall_false_intra() throws SQLException {\n\t\tint numDetected_false = this.getNumDetected_false_intra();\n\t\tint numClones_false = this.getNumClones_false_intra();\n\t\treturn 1.0*numDetected_false/numClones_false;\n\t}\n\tpublic double getRecall_false() throws SQLException {\n\t\tint numDetected_false = this.getNumDetected_false();\n\t\tint numClones_false = this.getNumClones_false();\n\t\treturn 1.0*numDetected_false/numClones_false;\n\t}\n\t\n\t/**\n\t * Calculated as the ratio of the known clones/false detected that are true not false positives.\n\t * @param functionality_id\n\t * @return\n\t * @throws SQLException\n\t */\n\tpublic double getPrecision_inter(long functionality_id) throws SQLException {\n\t\tint numDetected_true = this.getNumDetected_inter(functionality_id);\n\t\tint numDetected_false = this.getNumDetected_false_inter(functionality_id);\n\t\treturn 1.0*numDetected_true/(numDetected_true+numDetected_false);\n\t}\n\tpublic double getPrecision_intra(long functionality_id) throws SQLException {\n\t\tint numDetected_true = this.getNumDetected_intra(functionality_id);\n\t\tint numDetected_false = this.getNumDetected_false_intra(functionality_id);\n\t\treturn 1.0*numDetected_true/(numDetected_true+numDetected_false);\n\t}\n\tpublic double getPrecision(long functionality_id) throws SQLException {\n\t\tint numDetected_true = this.getNumDetected(functionality_id);\n\t\tint numDetected_false = this.getNumDetected_false(functionality_id);\n\t\treturn 1.0*numDetected_true/(numDetected_true+numDetected_false);\n\t}\n\n\t/**\n\t * Calculated as the ratio of the known clones/false detected that are true not false positives.\n\t * @return\n\t * @throws SQLException\n\t */\n\tpublic double getPrecision_inter() throws SQLException {\n\t\tint numDetected_true = this.getNumDetected_inter();\n\t\tint numDetected_false = this.getNumDetected_false_inter();\n\t\treturn 1.0*numDetected_true/(numDetected_true+numDetected_false);\n\t}\n\tpublic double getPrecision_avg_inter() throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getPrecision_inter(id);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\tpublic double getPrecision_intra() throws SQLException {\n\t\tint numDetected_true = this.getNumDetected_intra();\n\t\tint numDetected_false = this.getNumDetected_false_intra();\n\t\treturn 1.0*numDetected_true/(numDetected_true+numDetected_false);\n\t}\n\tpublic double getPrecision_avg_intra() throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getPrecision_intra(id);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\tpublic double getPrecision() throws SQLException {\n\t\tint numDetected_true = this.getNumDetected();\n\t\tint numDetected_false = this.getNumDetected_false();\n\t\treturn 1.0*numDetected_true/(numDetected_true+numDetected_false);\n\t}\n\t\n\tpublic double getPrecision_avg() throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getPrecision(id);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\t\n// Type-1\n\tpublic int getNumClones_type1_inter(long functionality_id) throws SQLException {\n\t\tif(numClones_type1_inter.get(functionality_id) == null) {\n\t\t\tint numClones = \n\t\t\t\t\tEvaluateTools.numClones(\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t1,\n\t\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTER_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t \t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tmin_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tmax_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tmin_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tmax_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tmin_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tmax_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tmin_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tmin_confidence,\n\t\t\t\t\t\t\t\t\t\t\t\t \t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t);\n\t\t\tnumClones_type1_inter.put(functionality_id, numClones);\n\t\t}\n\t\treturn numClones_type1_inter.get(functionality_id);\n\t}\n\t\n\tpublic int getNumClones_type1_intra(long functionality_id) throws SQLException {\n\t\tif(numClones_type1_intra.get(functionality_id) == null) {\n\t\t\tint numClones = \n\t\t\t\t\tEvaluateTools.numClones(\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t1,\n\t\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTRA_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t \t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tmin_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tmax_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tmin_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tmax_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tmin_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tmax_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tmin_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tmin_confidence,\n\t\t\t\t\t\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t);\n\t\t\tnumClones_type1_intra.put(functionality_id, numClones);\n\t\t}\n\t\treturn numClones_type1_intra.get(functionality_id);\n\t}\n\t\n\tpublic int getNumClones_type1(long functionality_id) throws SQLException {\n\t\treturn getNumClones_type1_inter(functionality_id) + getNumClones_type1_intra(functionality_id);\n\t}\n\t\n\tpublic int getNumClones_type1_inter() throws SQLException {\n\t\t//System.out.println(\"\\tgetNumClones_type1_inter\");\n\t\tint numClones = 0;\n\t\t\n\t\tfor(Long fid : functionality_ids) {\n\t\t\t//System.out.println(\"\\t\\t\"+fid);\n\t\t\tnumClones += getNumClones_type1_inter(fid);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_type1_intra() throws SQLException {\n\t\t//System.out.println(\"\\tgetNumClones_type1_intra\");\n\t\tint numClones = 0;\n\t\tfor(Long fid : functionality_ids) {\n\t\t\t//System.out.println(\"\\t\\t\" + fid);\n\t\t\tnumClones += getNumClones_type1_intra(fid);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_type1() throws SQLException {\n\t\t//System.out.println(\"getNumClones_type1\");\n\t\treturn getNumClones_type1_inter() + getNumClones_type1_intra();\n\t}\n\t\n\tpublic int getNumDetected_type1_inter(long functionality_id) throws SQLException {\n\t\tif(numDetected_type1_inter.get(functionality_id) == null) {\n\t\t\tint numDetected =\n\t\t\t\t\tEvaluateTools.numTrueDetected( \t /*tool_id*/\tthis.tool_id, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*matcher*/\tthis.matcher, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t1,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTER_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tthis.min_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tthis.max_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tthis.min_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tthis.max_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tthis.min_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tthis.max_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tthis.min_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tthis.min_confidence,\n\t\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t);\n\t\t\tnumDetected_type1_inter.put(functionality_id, numDetected);\n\t\t}\n\t\treturn numDetected_type1_inter.get(functionality_id);\n\t}\n\t\n\tpublic int getNumDetected_type1_intra(long functionality_id) throws SQLException {\n\t\tif(numDetected_type1_intra.get(functionality_id) == null) {\n\t\t\tint numDetected =\n\t\t\t\t\tEvaluateTools.numTrueDetected( \t /*tool_id*/\tthis.tool_id, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*matcher*/\tthis.matcher, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t1,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTRA_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tthis.min_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tthis.max_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tthis.min_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tthis.max_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tthis.min_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tthis.max_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tthis.min_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tthis.min_confidence,\n\t\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t);\n\t\t\tnumDetected_type1_intra.put(functionality_id, numDetected);\n\t\t}\n\t\treturn numDetected_type1_intra.get(functionality_id);\n\t}\n\t\n\tpublic int getNumDetected_type1(long functionality_id) throws SQLException {\n\t\treturn getNumDetected_type1_inter(functionality_id) + getNumDetected_type1_intra(functionality_id);\n\t}\n\t\n\tpublic int getNumDetected_type1_inter() throws SQLException {\n\t\t//System.out.println(\"\\tgetNumDetected_type1_inter\");\n\t\tint numDetected = 0;\n\t\tfor(Long fid : functionality_ids) {\n\t\t\t//System.out.println(\"\\t\\t\" + fid);\n\t\t\tnumDetected += getNumDetected_type1_inter(fid);\n\t\t}\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_type1_intra() throws SQLException {\n\t\t//System.out.println(\"\\tgetNumDetected_type1_intra\");\n\t\tint numDetected = 0;\n\t\tfor(Long fid : functionality_ids) {\n\t\t\t//System.out.println(\"\\t\\t\"+fid);\n\t\t\tnumDetected += getNumDetected_type1_intra(fid);\n\t\t}\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_type1() throws SQLException {\n\t\t//System.out.println(\"getNumDetected_type1\");\n\t\treturn getNumDetected_type1_inter() + getNumDetected_type1_intra();\n\t}\n\t\n\tpublic double getRecall_type1_inter(long functionality_id) throws SQLException {\n\t\tint numDetected = getNumDetected_type1_inter(functionality_id);\n\t\tint numClones = getNumClones_type1_inter(functionality_id);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type1_intra(long functionality_id) throws SQLException {\n\t\tint numDetected = getNumDetected_type1_intra(functionality_id);\n\t\tint numClones = getNumClones_type1_intra(functionality_id);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type1(long functionality_id) throws SQLException {\n\t\tint numDetected = getNumDetected_type1(functionality_id);\n\t\tint numClones = getNumClones_type1(functionality_id);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type1_inter() throws SQLException {\n\t\tint numDetected = getNumDetected_type1_inter();\n\t\tint numClones = getNumClones_type1_inter();\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type1_intra() throws SQLException {\n\t\tint numDetected = getNumDetected_type1_intra();\n\t\tint numClones = getNumClones_type1_intra();\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type1() throws SQLException {\n\t\t//System.out.println(\"getRecall_type1\");\n\t\tint numDetected = getNumDetected_type1();\n\t\tint numClones = getNumClones_type1();\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type1_avg() throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getRecall_type1(id);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\tpublic double getRecall_type1_avg_inter() throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getRecall_type1_inter(id);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\t\n\tpublic double getRecall_type1_avg_intra() throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getRecall_type1_intra(id);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\t\n// Type-2\n\t\n\tpublic int getNumClones_type2c_inter(long functionality_id) throws SQLException {\n\t\tif(numClones_type2c_inter.get(functionality_id) == null) {\n\t\t\tint numClones = \n\t\t\t\t\tEvaluateTools.numClones(\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t2,\n\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTER_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tmin_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tmax_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tmin_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tmax_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tmin_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tmax_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tmin_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tmin_confidence,\n\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t\t);\t\t\n\t\t\tnumClones_type2c_inter.put(functionality_id, numClones);\n\t\t}\n\t\treturn numClones_type2c_inter.get(functionality_id);\n\t}\n\t\n\tpublic int getNumClones_type2c_intra(long functionality_id) throws SQLException {\n\t\tif(numClones_type2c_intra.get(functionality_id) == null) {\n\t\t\tint numClones = \n\t\t\t\t\tEvaluateTools.numClones(\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t2,\n\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTRA_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tmin_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tmax_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tmin_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tmax_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tmin_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tmax_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tmin_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tmin_confidence,\n\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t\t);\t\t\n\t\t\tnumClones_type2c_intra.put(functionality_id, numClones);\n\t\t}\n\t\treturn numClones_type2c_intra.get(functionality_id);\n\t}\n\t\n\tpublic int getNumClones_type2c(long functionality_id) throws SQLException {\n\t\treturn getNumClones_type2c_inter(functionality_id) + getNumClones_type2c_intra(functionality_id);\n\t}\n\t\n\tpublic int getNumClones_type2c_inter() throws SQLException {\n\t\tint numClones = 0;\n\t\tfor(Long fid : functionality_ids) {\n\t\t\tnumClones += getNumClones_type2c_inter(fid);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_type2c_intra() throws SQLException {\n\t\tint numClones = 0;\n\t\tfor(Long fid : functionality_ids) {\n\t\t\tnumClones += getNumClones_type2c_intra(fid);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_type2c() throws SQLException {\n\t\treturn getNumClones_type2c_inter() + getNumClones_type2c_intra();\n\t}\n\t\n\tpublic int getNumDetected_type2c_inter(long functionality_id) throws SQLException {\n\t\tif(numDetected_type2c_inter.get(functionality_id) == null) {\n\t\t\tint numDetected =\n\t\t\t\t\tEvaluateTools.numTrueDetected( \t /*tool_id*/\tthis.tool_id, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*matcher*/\tthis.matcher, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t2,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTER_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tthis.min_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tthis.max_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tthis.min_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tthis.max_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tthis.min_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tthis.max_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tthis.min_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tthis.min_confidence,\n\t\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal);\n\t\t\tnumDetected_type2c_inter.put(functionality_id, numDetected);\n\t\t}\n\t\treturn numDetected_type2c_inter.get(functionality_id);\n\t}\n\t\n\tpublic int getNumDetected_type2c_intra(long functionality_id) throws SQLException {\n\t\tif(numDetected_type2c_intra.get(functionality_id) == null) {\n\t\t\tint numDetected =\n\t\t\t\t\tEvaluateTools.numTrueDetected( \t /*tool_id*/\tthis.tool_id, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*matcher*/\tthis.matcher, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t2,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTRA_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tthis.min_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tthis.max_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tthis.min_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tthis.max_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tthis.min_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tthis.max_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tthis.min_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tthis.min_confidence,\n\t\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal);\n\t\t\tnumDetected_type2c_intra.put(functionality_id, numDetected);\n\t\t}\n\t\treturn numDetected_type2c_intra.get(functionality_id);\n\t}\n\t\n\tpublic int getNumDetected_type2c(long functionality_id) throws SQLException {\n\t\treturn getNumDetected_type2c_inter(functionality_id) + getNumDetected_type2c_intra(functionality_id); \n\t}\n\t\n\tpublic int getNumDetected_type2c_inter() throws SQLException {\n\t\tint numDetected = 0;\n\t\tfor(Long fid : functionality_ids)\n\t\t\tnumDetected += getNumDetected_type2c_inter(fid);\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_type2c_intra() throws SQLException {\n\t\tint numDetected = 0;\n\t\tfor(Long fid : functionality_ids)\n\t\t\tnumDetected += getNumDetected_type2c_intra(fid);\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_type2c() throws SQLException {\n\t\treturn getNumDetected_type2c_inter() + getNumDetected_type2c_intra();\n\t}\n\t\n\tpublic double getRecall_type2c_inter(long functionality_id) throws SQLException {\n\t\tint numDetected = getNumDetected_type2c_inter(functionality_id);\n\t\tint numClones = getNumClones_type2c_inter(functionality_id);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type2c_intra(long functionality_id) throws SQLException {\n\t\tint numDetected = getNumDetected_type2c_intra(functionality_id);\n\t\tint numClones = getNumClones_type2c_intra(functionality_id);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type2c(long functionality_id) throws SQLException {\n\t\tint numDetected = getNumDetected_type2c(functionality_id);\n\t\tint numClones = getNumClones_type2c(functionality_id);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type2c_inter() throws SQLException {\n\t\tint numDetected = getNumDetected_type2c_inter();\n\t\tint numClones = getNumClones_type2c_inter();\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type2c_intra() throws SQLException {\n\t\tint numDetected = getNumDetected_type2c_intra();\n\t\tint numClones = getNumClones_type2c_intra();\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type2c() throws SQLException {\n\t\tint numDetected = getNumDetected_type2c();\n\t\tint numClones = getNumClones_type2c();\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type2c_avg() throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getRecall_type2c(id);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\tpublic double getRecall_type2c_avg_inter() throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getRecall_type2c_inter(id);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\tpublic double getRecall_type2c_avg_intra() throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getRecall_type2c_intra(id);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\t\n// Type-2 Blind\n\t\n\tpublic int getNumClones_type2b_inter(long functionality_id) throws SQLException {\n\t\tif(numClones_type2b_inter.get(functionality_id) == null) {\n\t\t\tint numClones = \n\t\t\t\t\tEvaluateTools.numClones(\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTER_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\t1.0,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tmin_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tmax_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tmin_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tmax_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tmin_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tmax_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tmin_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tmin_confidence,\n\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t\t);\t\t\n\t\t\tnumClones_type2b_inter.put(functionality_id, numClones);\n\t\t}\n\t\treturn numClones_type2b_inter.get(functionality_id);\n\t}\n\t\n\tpublic int getNumClones_type2b_intra(long functionality_id) throws SQLException {\n\t\tif(numClones_type2b_intra.get(functionality_id) == null) {\n\t\t\tint numClones = \n\t\t\t\t\tEvaluateTools.numClones(\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTRA_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\t1.0,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tmin_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tmax_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tmin_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tmax_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tmin_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tmax_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tmin_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tmin_confidence,\n\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t\t);\t\t\n\t\t\tnumClones_type2b_intra.put(functionality_id, numClones);\n\t\t}\n\t\treturn numClones_type2b_intra.get(functionality_id);\n\t}\n\t\n\tpublic int getNumClones_type2b(long functionality_id) throws SQLException {\n\t\treturn getNumClones_type2b_inter(functionality_id) + getNumClones_type2b_intra(functionality_id);\n\t}\n\t\n\tpublic int getNumClones_type2b_inter() throws SQLException {\n\t\tint numClones = 0;\n\t\tfor(Long fid : functionality_ids) {\n\t\t\tnumClones += getNumClones_type2b_inter(fid);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_type2b_intra() throws SQLException {\n\t\tint numClones = 0;\n\t\tfor(Long fid : functionality_ids) {\n\t\t\tnumClones += getNumClones_type2b_intra(fid);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_type2b() throws SQLException {\n\t\treturn getNumClones_type2b_inter() + getNumClones_type2b_intra();\n\t}\n\t\n\tpublic int getNumDetected_type2b_inter(long functionality_id) throws SQLException {\n\t\tif(numDetected_type2b_inter.get(functionality_id) == null) {\n\t\t\tint numDetected =\n\t\t\t\t\tEvaluateTools.numTrueDetected( \t /*tool_id*/\tthis.tool_id, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*matcher*/\tthis.matcher, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTER_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\t1.0,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tthis.min_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tthis.max_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tthis.min_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tthis.max_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tthis.min_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tthis.max_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tthis.min_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tthis.min_confidence,\n\t\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal);\n\t\t\tnumDetected_type2b_inter.put(functionality_id, numDetected);\n\t\t}\n\t\treturn numDetected_type2b_inter.get(functionality_id);\n\t}\n\t\n\tpublic int getNumDetected_type2b_intra(long functionality_id) throws SQLException {\n\t\tif(numDetected_type2b_intra.get(functionality_id) == null) {\n\t\t\tint numDetected =\n\t\t\t\t\tEvaluateTools.numTrueDetected( \t /*tool_id*/\tthis.tool_id, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*matcher*/\tthis.matcher, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTRA_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\t1.0,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tthis.min_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tthis.max_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tthis.min_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tthis.max_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tthis.min_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tthis.max_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tthis.min_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tthis.min_confidence,\n\t\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal);\n\t\t\tnumDetected_type2b_intra.put(functionality_id, numDetected);\n\t\t}\n\t\treturn numDetected_type2b_intra.get(functionality_id);\n\t}\n\t\n\tpublic int getNumDetected_type2b(long functionality_id) throws SQLException {\n\t\treturn getNumDetected_type2b_inter(functionality_id) + getNumDetected_type2b_intra(functionality_id);\n\t}\n\t\n\tpublic int getNumDetected_type2b_inter() throws SQLException {\n\t\tint numDetected = 0;\n\t\tfor(Long fid : functionality_ids)\n\t\t\tnumDetected += getNumDetected_type2b_inter(fid);\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_type2b_intra() throws SQLException {\n\t\tint numDetected = 0;\n\t\tfor(Long fid : functionality_ids)\n\t\t\tnumDetected += getNumDetected_type2b_intra(fid);\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_type2b() throws SQLException {\n\t\treturn getNumDetected_type2b_inter() + getNumDetected_type2b_intra();\n\t}\n\t\n\tpublic double getRecall_type2b_inter(long functionality_id) throws SQLException {\n\t\tint numDetected = getNumDetected_type2b_inter(functionality_id);\n\t\tint numClones = getNumClones_type2b_inter(functionality_id);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type2b_intra(long functionality_id) throws SQLException {\n\t\tint numDetected = getNumDetected_type2b_intra(functionality_id);\n\t\tint numClones = getNumClones_type2b_intra(functionality_id);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type2b(long functionality_id) throws SQLException {\n\t\tint numDetected = getNumDetected_type2b(functionality_id);\n\t\tint numClones = getNumClones_type2b(functionality_id);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type2b_inter() throws SQLException {\n\t\tint numDetected = getNumDetected_type2b_inter();\n\t\tint numClones = getNumClones_type2b_inter();\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type2b_intra() throws SQLException {\n\t\tint numDetected = getNumDetected_type2b_intra();\n\t\tint numClones = getNumClones_type2b_intra();\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type2b() throws SQLException {\n\t\tint numDetected = getNumDetected_type2b();\n\t\tint numClones = getNumClones_type2b();\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type2b_avg() throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getRecall_type2b(id);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\tpublic double getRecall_type2b_avg_inter() throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getRecall_type2b_inter(id);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\tpublic double getRecall_type2b_avg_intra() throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getRecall_type2b_intra(id);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\t\n// Type-2\n\t\n\tpublic int getNumClones_type2_inter(long functionality_id) throws SQLException {\n\t\tint numClones = 0;\n\t\tnumClones += getNumClones_type2b_inter(functionality_id);\n\t\tnumClones += getNumClones_type2c_inter(functionality_id);\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_type2_intra(long functionality_id) throws SQLException {\n\t\tint numClones = 0;\n\t\tnumClones += getNumClones_type2b_intra(functionality_id);\n\t\tnumClones += getNumClones_type2c_intra(functionality_id);\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_type2(long functionality_id) throws SQLException {\n\t\treturn getNumClones_type2_inter(functionality_id) + getNumClones_type2_intra(functionality_id);\n\t}\n\t\n\t\n\tpublic int getNumClones_type2_inter() throws SQLException {\n\t\tint numClones = 0;\n\t\tfor(Long fid : functionality_ids) {\n\t\t\tnumClones += getNumClones_type2_inter(fid);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_type2_intra() throws SQLException {\n\t\tint numClones = 0;\n\t\tfor(Long fid : functionality_ids) {\n\t\t\tnumClones += getNumClones_type2_intra(fid);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_type2() throws SQLException {\n\t\treturn getNumClones_type2_inter() + getNumClones_type2_intra();\n\t}\n\t\n\t\n\tpublic int getNumDetected_type2_inter(long functionality_id) throws SQLException {\n\t\tint numDetected = 0;\n\t\tnumDetected += getNumDetected_type2c_inter(functionality_id);\n\t\tnumDetected += getNumDetected_type2b_inter(functionality_id);\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_type2_intra(long functionality_id) throws SQLException {\n\t\tint numDetected = 0;\n\t\tnumDetected += getNumDetected_type2c_intra(functionality_id);\n\t\tnumDetected += getNumDetected_type2b_intra(functionality_id);\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_type2(long functionality_id) throws SQLException {\n\t\treturn getNumDetected_type2_inter(functionality_id) + getNumDetected_type2_intra(functionality_id);\n\t}\n\t\n\t\n\tpublic int getNumDetected_type2_inter() throws SQLException {\n\t\tint numDetected = 0;\n\t\tfor(Long fid : functionality_ids)\n\t\t\tnumDetected += getNumDetected_type2_inter(fid);\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_type2_intra() throws SQLException {\n\t\tint numDetected = 0;\n\t\tfor(Long fid : functionality_ids)\n\t\t\tnumDetected += getNumDetected_type2_intra(fid);\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_type2() throws SQLException {\n\t\treturn getNumDetected_type2_inter() + getNumDetected_type2_intra();\n\t}\n\t\n\t\n\tpublic double getRecall_type2_inter(long functionality_id) throws SQLException {\n\t\tint numDetected = getNumDetected_type2_inter(functionality_id);\n\t\tint numClones = getNumClones_type2_inter(functionality_id);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type2_intra(long functionality_id) throws SQLException {\n\t\tint numDetected = getNumDetected_type2_intra(functionality_id);\n\t\tint numClones = getNumClones_type2_intra(functionality_id);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type2(long functionality_id) throws SQLException {\n\t\tint numDetected = getNumDetected_type2(functionality_id);\n\t\tint numClones = getNumClones_type2(functionality_id);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\t\n\tpublic double getRecall_type2_inter() throws SQLException {\n\t\tint numDetected = getNumDetected_type2_inter();\n\t\tint numClones = getNumClones_type2_inter();\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type2_intra() throws SQLException {\n\t\tint numDetected = getNumDetected_type2_intra();\n\t\tint numClones = getNumClones_type2_intra();\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type2() throws SQLException {\n\t\tint numDetected = getNumDetected_type2();\n\t\tint numClones = getNumClones_type2();\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type2_avg() throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getRecall_type2b(id);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\tpublic double getRecall_type2_avg_inter() throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getRecall_type2b_inter(id);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\tpublic double getRecall_type2_avg_intra() throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getRecall_type2_intra(id);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\t\n// Type-3\n\t\t\n\tpublic int getNumClones_type3_inter(long functionality_id, int similarity) throws SQLException {\n\t\tif(similarity % 5 != 0 || similarity >= 100 || similarity < 0)\n\t\t\tthrow new IllegalArgumentException(\"Similarity must be a multiple of 5 in range [0-100).\");\n\t\tint index = similarity/5;\n\t\tdouble start = similarity/100.0;\n\t\tdouble end = (similarity+5)/100.0;\n\t\tif(numClones_type3_inter[index].get(functionality_id) == null) {\n\t\t\tint numClones;\n\t\t\tif(this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_LINE) {\n\t\t\t\tnumClones = \n\t\t\t\tEvaluateTools.numClones(\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTER_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tstart, \n\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tend, \n\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tmin_size, \n\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tmax_size, \n\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tmin_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tmax_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tmin_tokens, \n\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tmax_tokens, \n\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tmin_judges, \n\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tmin_confidence,\n\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t} else if(this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_TOKEN) {\n\t\t\t\tnumClones = \n\t\t\t\tEvaluateTools.numClones(\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTER_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tstart, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tend, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tmin_size, \n\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tmax_size, \n\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tmin_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tmax_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tmin_tokens, \n\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tmax_tokens, \n\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tmin_judges, \n\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tmin_confidence,\n\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t} else if(this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_BOTH) {\n\t\t\t\tnumClones = \n\t\t\t\tEvaluateTools.numClones(\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTER_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tstart,\n\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tend,\n\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tmin_size, \n\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tmax_size, \n\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tmin_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tmax_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tmin_tokens, \n\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tmax_tokens, \n\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tmin_judges, \n\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tmin_confidence,\n\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t} else {//if(this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_AVG) {\n\t\t\t\tnumClones = \n\t\t\t\tEvaluateTools.numClones(\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTER_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tstart,\n\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tend,\n\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tmin_size, \n\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tmax_size, \n\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tmin_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tmax_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tmin_tokens, \n\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tmax_tokens, \n\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tmin_judges, \n\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tmin_confidence,\n\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t}\n\t\t\tnumClones_type3_inter[index].put(functionality_id, numClones);\n\t\t}\n\t\treturn numClones_type3_inter[index].get(functionality_id);\n\t}\n\t\n\tpublic int getNumClones_type3_intra(long functionality_id, int similarity) throws SQLException {\n\t\tif(similarity % 5 != 0 || similarity >= 100 || similarity < 0)\n\t\t\tthrow new IllegalArgumentException(\"Similarity must be a multiple of 5 in range [0-100).\");\n\t\tint index = similarity/5;\n\t\tdouble start = similarity/100.0;\n\t\tdouble end = (similarity+5)/100.0;\n\t\tif(numClones_type3_intra[index].get(functionality_id) == null) {\n\t\t\tint numClones;\n\t\t\tif(this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_LINE) {\n\t\t\t\tnumClones = \n\t\t\t\tEvaluateTools.numClones(\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTRA_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tstart, \n\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tend, \n\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tmin_size, \n\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tmax_size, \n\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tmin_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tmax_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tmin_tokens, \n\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tmax_tokens, \n\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tmin_judges, \n\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tmin_confidence,\n\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t} else if(this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_TOKEN) {\n\t\t\t\tnumClones = \n\t\t\t\tEvaluateTools.numClones(\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTRA_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tstart, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tend, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tmin_size, \n\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tmax_size, \n\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tmin_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tmax_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tmin_tokens, \n\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tmax_tokens, \n\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tmin_judges, \n\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tmin_confidence,\n\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t} else if(this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_BOTH) {\n\t\t\t\tnumClones = \n\t\t\t\tEvaluateTools.numClones(\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTRA_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tstart,\n\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tend,\n\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tmin_size, \n\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tmax_size, \n\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tmin_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tmax_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tmin_tokens, \n\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tmax_tokens, \n\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tmin_judges, \n\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tmin_confidence,\n\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t} else {//if(this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_AVG) {\n\t\t\t\tnumClones = \n\t\t\t\tEvaluateTools.numClones(\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTRA_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tstart,\n\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tend,\n\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tmin_size, \n\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tmax_size, \n\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tmin_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tmax_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tmin_tokens, \n\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tmax_tokens, \n\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tmin_judges, \n\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tmin_confidence,\n\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t}\n\t\t\tnumClones_type3_intra[index].put(functionality_id, numClones);\n\t\t}\n\t\treturn numClones_type3_intra[index].get(functionality_id);\n\t}\n\t\n\tpublic int getNumClones_type3(long functionality_id, int similarity) throws SQLException {\n\t\treturn getNumClones_type3_inter(functionality_id, similarity) + getNumClones_type3_intra(functionality_id, similarity); \n\t}\n\t\n\t\t\t\n\tpublic int getNumClones_type3_inter(long functionality_id, int similarity_start, int similarity_end) throws SQLException {\n\t\tif(similarity_start < 0) throw new IllegalArgumentException(\"similarity_start must be >= 0.\");\n\t\tif(similarity_end > 100) throw new IllegalArgumentException(\"similarity_end must be <= 100\");\n\t\tif(similarity_start > similarity_end) throw new IllegalArgumentException(\"similarity start must be < similarity_end\");\n\t\tif(similarity_start % 5 != 0) throw new IllegalArgumentException(\"similarity_start must be a multiple of 5\");\n\t\tif(similarity_end % 5 != 0) throw new IllegalArgumentException(\"similarity_end must be a multiple of 5\");\n\t\t\n\t\tint numClones = 0;\n\t\tfor(int i = similarity_start; i < similarity_end; i += 5) {\n\t\t\tnumClones += getNumClones_type3_inter(functionality_id, i);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_type3_intra(long functionality_id, int similarity_start, int similarity_end) throws SQLException {\n\t\tif(similarity_start < 0) throw new IllegalArgumentException(\"similarity_start must be >= 0.\");\n\t\tif(similarity_end > 100) throw new IllegalArgumentException(\"similarity_end must be <= 100\");\n\t\tif(similarity_start > similarity_end) throw new IllegalArgumentException(\"similarity start must be < similarity_end\");\n\t\tif(similarity_start % 5 != 0) throw new IllegalArgumentException(\"similarity_start must be a multiple of 5\");\n\t\tif(similarity_end % 5 != 0) throw new IllegalArgumentException(\"similarity_end must be a multiple of 5\");\n\t\t\n\t\tint numClones = 0;\n\t\tfor(int i = similarity_start; i < similarity_end; i += 5) {\n\t\t\tnumClones += getNumClones_type3_intra(functionality_id, i);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_type3(long functionality_id, int similarity_start, int similarity_end) throws SQLException {\n\t\treturn getNumClones_type3_intra(functionality_id, similarity_start, similarity_end) + getNumClones_type3_inter(functionality_id, similarity_start, similarity_end); \n\t}\n\t\n\t\n\tpublic int getNumClones_type3_inter(int similarity_start, int similarity_end) throws SQLException {\n\t\tif(similarity_start < 0) throw new IllegalArgumentException(\"similarity_start must be >= 0.\");\n\t\tif(similarity_end > 100) throw new IllegalArgumentException(\"similarity_end must be <= 100\");\n\t\tif(similarity_start > similarity_end) throw new IllegalArgumentException(\"similarity start must be < similarity_end\");\n\t\tif(similarity_start % 5 != 0) throw new IllegalArgumentException(\"similarity_start must be a multiple of 5\");\n\t\tif(similarity_end % 5 != 0) throw new IllegalArgumentException(\"similarity_end must be a multiple of 5\");\n\t\t\n\t\tint numClones = 0;\n\t\tfor(long fid : functionality_ids) {\n\t\t\tnumClones += getNumClones_type3_inter(fid, similarity_start, similarity_end);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_type3_intra(int similarity_start, int similarity_end) throws SQLException {\n\t\tif(similarity_start < 0) throw new IllegalArgumentException(\"similarity_start must be >= 0.\");\n\t\tif(similarity_end > 100) throw new IllegalArgumentException(\"similarity_end must be <= 100\");\n\t\tif(similarity_start > similarity_end) throw new IllegalArgumentException(\"similarity start must be < similarity_end\");\n\t\tif(similarity_start % 5 != 0) throw new IllegalArgumentException(\"similarity_start must be a multiple of 5\");\n\t\tif(similarity_end % 5 != 0) throw new IllegalArgumentException(\"similarity_end must be a multiple of 5\");\n\t\t\n\t\tint numClones = 0;\n\t\tfor(long fid : functionality_ids) {\n\t\t\tnumClones += getNumClones_type3_intra(fid, similarity_start, similarity_end);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_type3(int similarity_start, int similarity_end) throws SQLException {\n\t\treturn getNumClones_type3_inter(similarity_start, similarity_end) + getNumClones_type3_intra(similarity_start, similarity_end);\n\t}\n\t\n\t\n\tpublic int getNumClones_type3_inter(long functionality_id) throws SQLException {\n\t\tint numClones = 0;\n\t\tfor(int i = 0; i < 100; i += 5) {\n\t\t\tnumClones += getNumClones_type3_inter(functionality_id, i, i+5);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_type3_intra(long functionality_id) throws SQLException {\n\t\tint numClones = 0;\n\t\tfor(int i = 0; i < 100; i += 5) {\n\t\t\tnumClones += getNumClones_type3_intra(functionality_id, i, i+5);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_type3(long functionality_id) throws SQLException {\n\t\treturn getNumClones_type3_inter(functionality_id) + getNumClones_type3_intra(functionality_id);\n\t}\n\t\n\t\t\n\tpublic int getNumClones_type3_inter() throws SQLException {\n\t\tint numClones = 0;\n\t\tfor(int i = 0; i < 100; i = i + 5) {\n\t\t\tnumClones += getNumClones_type3_inter(i, i+5);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_type3_intra() throws SQLException {\n\t\tint numClones = 0;\n\t\tfor(int i = 0; i < 100; i = i + 5) {\n\t\t\tnumClones += getNumClones_type3_intra(i, i+5);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_type3() throws SQLException {\n\t\treturn getNumClones_type3_intra() + getNumClones_type3_inter();\n\t}\n\t\n\t\n\tpublic int getNumDetected_type3_inter(long functionality_id, int similarity) throws SQLException {\n\t\tif(similarity % 5 != 0 || similarity >= 100 || similarity < 0)\n\t\t\tthrow new IllegalArgumentException(\"Similarity must be a multiple of 5 in range [0-100).\");\n\t\tint index = similarity/5;\n\t\tdouble start = similarity/100.0;\n\t\tdouble end = (similarity+5)/100.0;\n\t\t\n\t\tif(numDetected_type3_inter[index].get(functionality_id) == null) {\n\t\t\tint numDetected;\n\t\t\tif(this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_LINE) {\n\t\t\t\tnumDetected =\n\t\t\t\tEvaluateTools.numTrueDetected( \t /*tool_id*/\tthis.tool_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*matcher*/\tthis.matcher, \n\t\t\t\t\t\t\t\t\t\t\t\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTER_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tstart, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tend, \n\t\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tthis.min_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tthis.max_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tthis.min_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tthis.max_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tthis.min_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tthis.max_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tthis.min_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tthis.min_confidence,\n\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t} else if(this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_TOKEN) {\n\t\t\t\tnumDetected =\n\t\t\t\tEvaluateTools.numTrueDetected( \t /*tool_id*/\tthis.tool_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*matcher*/\tthis.matcher, \n\t\t\t\t\t\t\t\t\t\t\t\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTER_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tstart, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tend, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tthis.min_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tthis.max_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tthis.min_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tthis.max_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tthis.min_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tthis.max_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tthis.min_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tthis.min_confidence,\n\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t} else if(this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_BOTH) {\n\t\t\t\tnumDetected =\n\t\t\t\tEvaluateTools.numTrueDetected( \t /*tool_id*/\tthis.tool_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*matcher*/\tthis.matcher, \n\t\t\t\t\t\t\t\t\t\t\t\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTER_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tstart,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tend,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tthis.min_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tthis.max_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tthis.min_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tthis.max_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tthis.min_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tthis.max_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tthis.min_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tthis.min_confidence,\n\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t} else {//if(this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_AVG) {\n\t\t\t\tnumDetected =\n\t\t\t\tEvaluateTools.numTrueDetected( \t /*tool_id*/\tthis.tool_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*matcher*/\tthis.matcher, \n\t\t\t\t\t\t\t\t\t\t\t\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTER_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tstart,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tend,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tthis.min_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tthis.max_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tthis.min_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tthis.max_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tthis.min_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tthis.max_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tthis.min_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tthis.min_confidence,\n\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t}\n\t\t\tnumDetected_type3_inter[index].put(functionality_id, numDetected);\n\t\t}\n\t\treturn numDetected_type3_inter[index].get(functionality_id);\n\t}\n\t\n\tpublic int getNumDetected_type3_intra(long functionality_id, int similarity) throws SQLException {\n\t\tif(similarity % 5 != 0 || similarity >= 100 || similarity < 0)\n\t\t\tthrow new IllegalArgumentException(\"Similarity must be a multiple of 5 in range [0-100).\");\n\t\tint index = similarity/5;\n\t\tdouble start = similarity/100.0;\n\t\tdouble end = (similarity+5)/100.0;\n\t\t\n\t\tif(numDetected_type3_intra[index].get(functionality_id) == null) {\n\t\t\tint numDetected;\n\t\t\tif(this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_LINE) {\n\t\t\t\tnumDetected =\n\t\t\t\tEvaluateTools.numTrueDetected( \t /*tool_id*/\tthis.tool_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*matcher*/\tthis.matcher, \n\t\t\t\t\t\t\t\t\t\t\t\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTRA_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tstart, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tend, \n\t\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tthis.min_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tthis.max_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tthis.min_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tthis.max_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tthis.min_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tthis.max_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tthis.min_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tthis.min_confidence,\n\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t} else if(this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_TOKEN) {\n\t\t\t\tnumDetected =\n\t\t\t\tEvaluateTools.numTrueDetected( \t /*tool_id*/\tthis.tool_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*matcher*/\tthis.matcher, \n\t\t\t\t\t\t\t\t\t\t\t\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTRA_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tstart, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tend, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tthis.min_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tthis.max_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tthis.min_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tthis.max_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tthis.min_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tthis.max_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tthis.min_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tthis.min_confidence,\n\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t} else if(this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_BOTH) {\n\t\t\t\tnumDetected =\n\t\t\t\tEvaluateTools.numTrueDetected( \t /*tool_id*/\tthis.tool_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*matcher*/\tthis.matcher, \n\t\t\t\t\t\t\t\t\t\t\t\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTRA_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tstart,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tend,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tthis.min_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tthis.max_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tthis.min_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tthis.max_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tthis.min_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tthis.max_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tthis.min_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tthis.min_confidence,\n\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t} else {//if(this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_AVG) {\n\t\t\t\tnumDetected =\n\t\t\t\tEvaluateTools.numTrueDetected( \t /*tool_id*/\tthis.tool_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*matcher*/\tthis.matcher, \n\t\t\t\t\t\t\t\t\t\t\t\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTRA_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tstart,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tend,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tthis.min_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tthis.max_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tthis.min_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tthis.max_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tthis.min_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tthis.max_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tthis.min_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tthis.min_confidence,\n\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t}\n\t\t\tnumDetected_type3_intra[index].put(functionality_id, numDetected);\n\t\t}\n\t\treturn numDetected_type3_intra[index].get(functionality_id);\n\t}\n\t\n\tpublic int getNumDetected_type3(long functionality_id, int similarity) throws SQLException {\n\t\treturn getNumDetected_type3_intra(functionality_id, similarity) + getNumDetected_type3_inter(functionality_id, similarity);\n\t}\n\t\n\t\n\tpublic int getNumDetected_type3_inter(long functionality_id, int similarity_start, int similarity_end) throws SQLException {\n\t\tif(similarity_start < 0) throw new IllegalArgumentException(\"similarity_start must be >= 0.\");\n\t\tif(similarity_end > 100) throw new IllegalArgumentException(\"similarity_end must be <= 100\");\n\t\tif(similarity_start > similarity_end) throw new IllegalArgumentException(\"similarity start must be < similarity_end\");\n\t\tif(similarity_start % 5 != 0) throw new IllegalArgumentException(\"similarity_start must be a multiple of 5\");\n\t\tif(similarity_end % 5 != 0) throw new IllegalArgumentException(\"similarity_end must be a multiple of 5\");\n\t\t\n\t\tint numDetected = 0;\n\t\tfor(int i = similarity_start; i < similarity_end; i += 5) {\n\t\t\tnumDetected += getNumDetected_type3_inter(functionality_id, i);\n\t\t}\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_type3_intra(long functionality_id, int similarity_start, int similarity_end) throws SQLException {\n\t\tif(similarity_start < 0) throw new IllegalArgumentException(\"similarity_start must be >= 0.\");\n\t\tif(similarity_end > 100) throw new IllegalArgumentException(\"similarity_end must be <= 100\");\n\t\tif(similarity_start > similarity_end) throw new IllegalArgumentException(\"similarity start must be < similarity_end\");\n\t\tif(similarity_start % 5 != 0) throw new IllegalArgumentException(\"similarity_start must be a multiple of 5\");\n\t\tif(similarity_end % 5 != 0) throw new IllegalArgumentException(\"similarity_end must be a multiple of 5\");\n\t\t\n\t\tint numDetected = 0;\n\t\tfor(int i = similarity_start; i < similarity_end; i += 5) {\n\t\t\tnumDetected += getNumDetected_type3_intra(functionality_id, i);\n\t\t}\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_type3(long functionality_id, int similarity_start, int similarity_end) throws SQLException {\n\t\treturn getNumDetected_type3_intra(functionality_id, similarity_start, similarity_end) +\n\t\t\t getNumDetected_type3_inter(functionality_id, similarity_start, similarity_end);\n\t}\n\t\n\t\n\tpublic int getNumDetected_type3_inter(int similarity_start, int similarity_end) throws SQLException {\n\t\tif(similarity_start < 0) throw new IllegalArgumentException(\"similarity_start must be >= 0.\");\n\t\tif(similarity_end > 100) throw new IllegalArgumentException(\"similarity_end must be <= 100\");\n\t\tif(similarity_start > similarity_end) throw new IllegalArgumentException(\"similarity start must be < similarity_end\");\n\t\tif(similarity_start % 5 != 0) throw new IllegalArgumentException(\"similarity_start must be a multiple of 5\");\n\t\tif(similarity_end % 5 != 0) throw new IllegalArgumentException(\"similarity_end must be a multiple of 5\");\n\t\t\n\t\tint numDetected = 0;\n\t\tfor(long fid : functionality_ids) {\n\t\t\tnumDetected += getNumDetected_type3_inter(fid, similarity_start, similarity_end);\n\t\t}\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_type3_intra(int similarity_start, int similarity_end) throws SQLException {\n\t\tif(similarity_start < 0) throw new IllegalArgumentException(\"similarity_start must be >= 0.\");\n\t\tif(similarity_end > 100) throw new IllegalArgumentException(\"similarity_end must be <= 100\");\n\t\tif(similarity_start > similarity_end) throw new IllegalArgumentException(\"similarity start must be < similarity_end\");\n\t\tif(similarity_start % 5 != 0) throw new IllegalArgumentException(\"similarity_start must be a multiple of 5\");\n\t\tif(similarity_end % 5 != 0) throw new IllegalArgumentException(\"similarity_end must be a multiple of 5\");\n\t\t\n\t\tint numDetected = 0;\n\t\tfor(long fid : functionality_ids) {\n\t\t\tnumDetected += getNumDetected_type3_intra(fid, similarity_start, similarity_end);\n\t\t}\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_type3(int similarity_start, int similarity_end) throws SQLException {\n\t\treturn getNumDetected_type3_intra(similarity_start, similarity_end) +\n\t\t\t getNumDetected_type3_inter(similarity_start, similarity_end);\n\t}\n\t\n\t\n\tpublic int getNumDetected_type3_inter(long functionality_id) throws SQLException {\n\t\tint numDetected = 0;\n\t\tfor(int i = 0; i < 100; i += 5) {\n\t\t\tnumDetected += getNumDetected_type3_inter(functionality_id, i, i+5);\n\t\t}\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_type3_intra(long functionality_id) throws SQLException {\n\t\tint numDetected = 0;\n\t\tfor(int i = 0; i < 100; i += 5) {\n\t\t\tnumDetected += getNumDetected_type3_intra(functionality_id, i, i+5);\n\t\t}\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_type3(long functionality_id) throws SQLException {\n\t\treturn getNumDetected_type3_intra(functionality_id) + \n\t\t\t getNumDetected_type3_inter(functionality_id);\n\t}\n\t\n\t\n\tpublic int getNumDetected_type3_inter() throws SQLException {\n\t\tint numDetected = 0;\n\t\tfor(int i = 0; i < 100; i = i + 5) {\n\t\t\tnumDetected += getNumDetected_type3_inter(i, i+5);\n\t\t}\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_type3_intra() throws SQLException {\n\t\tint numDetected = 0;\n\t\tfor(int i = 0; i < 100; i = i + 5) {\n\t\t\tnumDetected += getNumDetected_type3_intra(i, i+5);\n\t\t}\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_type3() throws SQLException {\n\t\treturn getNumDetected_type3_intra() + getNumDetected_type3_inter();\n\t}\n\t\n\t\n\tpublic double getRecall_type3_inter(long functionality_id, int similarity_start, int similarity_end) throws SQLException {\n\t\tif(similarity_start < 0) throw new IllegalArgumentException(\"similarity_start must be >= 0.\");\n\t\tif(similarity_end > 100) throw new IllegalArgumentException(\"similarity_end must be <= 100\");\n\t\tif(similarity_start > similarity_end) throw new IllegalArgumentException(\"similarity start must be < similarity_end\");\n\t\tif(similarity_start % 5 != 0) throw new IllegalArgumentException(\"similarity_start must be a multiple of 5\");\n\t\tif(similarity_end % 5 != 0) throw new IllegalArgumentException(\"similarity_end must be a multiple of 5\");\n\t\t\n\t\tint numDetected = getNumDetected_type3_inter(functionality_id, similarity_start, similarity_end);\n\t\tint numClones = getNumClones_type3_inter(functionality_id, similarity_start, similarity_end);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type3_intra(long functionality_id, int similarity_start, int similarity_end) throws SQLException {\n\t\tif(similarity_start < 0) throw new IllegalArgumentException(\"similarity_start must be >= 0.\");\n\t\tif(similarity_end > 100) throw new IllegalArgumentException(\"similarity_end must be <= 100\");\n\t\tif(similarity_start > similarity_end) throw new IllegalArgumentException(\"similarity start must be < similarity_end\");\n\t\tif(similarity_start % 5 != 0) throw new IllegalArgumentException(\"similarity_start must be a multiple of 5\");\n\t\tif(similarity_end % 5 != 0) throw new IllegalArgumentException(\"similarity_end must be a multiple of 5\");\n\t\t\n\t\tint numDetected = getNumDetected_type3_intra(functionality_id, similarity_start, similarity_end);\n\t\tint numClones = getNumClones_type3_intra(functionality_id, similarity_start, similarity_end);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type3(long functionality_id, int similarity_start, int similarity_end) throws SQLException {\n\t\tif(similarity_start < 0) throw new IllegalArgumentException(\"similarity_start must be >= 0.\");\n\t\tif(similarity_end > 100) throw new IllegalArgumentException(\"similarity_end must be <= 100\");\n\t\tif(similarity_start > similarity_end) throw new IllegalArgumentException(\"similarity start must be < similarity_end\");\n\t\tif(similarity_start % 5 != 0) throw new IllegalArgumentException(\"similarity_start must be a multiple of 5\");\n\t\tif(similarity_end % 5 != 0) throw new IllegalArgumentException(\"similarity_end must be a multiple of 5\");\n\t\t\n\t\tint numDetected = getNumDetected_type3(functionality_id, similarity_start, similarity_end);\n\t\tint numClones = getNumClones_type3 (functionality_id, similarity_start, similarity_end);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\t\n\tpublic double getRecall_type3_inter(int similarity_start, int similarity_end) throws SQLException {\n\t\tif(similarity_start < 0) throw new IllegalArgumentException(\"similarity_start must be >= 0.\");\n\t\tif(similarity_end > 100) throw new IllegalArgumentException(\"similarity_end must be <= 100\");\n\t\tif(similarity_start > similarity_end) throw new IllegalArgumentException(\"similarity start must be < similarity_end\");\n\t\tif(similarity_start % 5 != 0) throw new IllegalArgumentException(\"similarity_start must be a multiple of 5\");\n\t\tif(similarity_end % 5 != 0) throw new IllegalArgumentException(\"similarity_end must be a multiple of 5\");\n\t\t\n\t\tint numDetected = getNumDetected_type3_inter(similarity_start, similarity_end);\n\t\tint numClones = getNumClones_type3_inter(similarity_start, similarity_end);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type3_avg_inter(int similarity_start, int similarity_end) throws SQLException {\n\t\tif(similarity_start < 0) throw new IllegalArgumentException(\"similarity_start must be >= 0.\");\n\t\tif(similarity_end > 100) throw new IllegalArgumentException(\"similarity_end must be <= 100\");\n\t\tif(similarity_start > similarity_end) throw new IllegalArgumentException(\"similarity start must be < similarity_end\");\n\t\tif(similarity_start % 5 != 0) throw new IllegalArgumentException(\"similarity_start must be a multiple of 5\");\n\t\tif(similarity_end % 5 != 0) throw new IllegalArgumentException(\"similarity_end must be a multiple of 5\");\n\t\t\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = this.getRecall_type3_inter(id, similarity_start, similarity_end);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\t\n\tpublic double getRecall_type3_intra(int similarity_start, int similarity_end) throws SQLException {\n\t\tif(similarity_start < 0) throw new IllegalArgumentException(\"similarity_start must be >= 0.\");\n\t\tif(similarity_end > 100) throw new IllegalArgumentException(\"similarity_end must be <= 100\");\n\t\tif(similarity_start > similarity_end) throw new IllegalArgumentException(\"similarity start must be < similarity_end\");\n\t\tif(similarity_start % 5 != 0) throw new IllegalArgumentException(\"similarity_start must be a multiple of 5\");\n\t\tif(similarity_end % 5 != 0) throw new IllegalArgumentException(\"similarity_end must be a multiple of 5\");\n\t\t\n\t\tint numDetected = getNumDetected_type3_intra(similarity_start, similarity_end);\n\t\tint numClones = getNumClones_type3_intra(similarity_start, similarity_end);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type3_avg_intra(int similarity_start, int similarity_end) throws SQLException {\n\t\tif(similarity_start < 0) throw new IllegalArgumentException(\"similarity_start must be >= 0.\");\n\t\tif(similarity_end > 100) throw new IllegalArgumentException(\"similarity_end must be <= 100\");\n\t\tif(similarity_start > similarity_end) throw new IllegalArgumentException(\"similarity start must be < similarity_end\");\n\t\tif(similarity_start % 5 != 0) throw new IllegalArgumentException(\"similarity_start must be a multiple of 5\");\n\t\tif(similarity_end % 5 != 0) throw new IllegalArgumentException(\"similarity_end must be a multiple of 5\");\n\t\t\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = this.getRecall_type3_intra(id, similarity_start, similarity_end);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\t\n\tpublic double getRecall_type3(int similarity_start, int similarity_end) throws SQLException {\n\t\tif(similarity_start < 0) throw new IllegalArgumentException(\"similarity_start must be >= 0.\");\n\t\tif(similarity_end > 100) throw new IllegalArgumentException(\"similarity_end must be <= 100\");\n\t\tif(similarity_start > similarity_end) throw new IllegalArgumentException(\"similarity start must be < similarity_end\");\n\t\tif(similarity_start % 5 != 0) throw new IllegalArgumentException(\"similarity_start must be a multiple of 5\");\n\t\tif(similarity_end % 5 != 0) throw new IllegalArgumentException(\"similarity_end must be a multiple of 5\");\n\t\t\n\t\tint numDetected = getNumDetected_type3(similarity_start, similarity_end);\n\t\tint numClones = getNumClones_type3(similarity_start, similarity_end);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type3_avg(int similarity_start, int similarity_end) throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getRecall_type3(id, similarity_start, similarity_end);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\t\n\t\t\n\tpublic double getRecall_type3_inter(long functionality_id) throws SQLException {\n\t\tint numDetected = getNumDetected_type3_inter(functionality_id);\n\t\tint numClones = getNumClones_type3_inter(functionality_id);\n\t\t//System.out.println(numDetected + \" \" + numClones);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type3_intra(long functionality_id) throws SQLException {\n\t\tint numDetected = getNumDetected_type3_intra(functionality_id);\n\t\tint numClones = getNumClones_type3_intra(functionality_id);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type3(long functionality_id) throws SQLException {\n\t\tint numDetected = getNumDetected_type3(functionality_id);\n\t\tint numClones = getNumClones_type3(functionality_id);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\t\n\tpublic double getRecall_type3_inter() throws SQLException {\n\t\tint numDetected = getNumDetected_type3_inter();\n\t\tint numClones = getNumClones_type3_inter();\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type3_intra() throws SQLException {\n\t\tint numDetected = getNumDetected_type3_intra();\n\t\tint numClones = getNumClones_type3_intra();\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type3() throws SQLException {\n\t\tint numDetected = getNumDetected_type3();\n\t\tint numClones = getNumClones_type3();\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\t\n\tpublic CloneMatcher getMatcher() {\n\t\treturn this.matcher;\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\tpublic ToolEvaluator(Long tool_id, CloneMatcher matcher, int similarity_type,\n\t\t\t \t\t\t Integer min_size, Integer max_size, Integer min_pretty_size, Integer max_pretty_size, Integer min_tokens, Integer max_tokens,\n\t\t\t \t\t\t Integer min_judges, Integer min_confidence, boolean includeInternal) throws SQLException {\n\t\t\n\t\tthis.similarity_type = similarity_type;\n\t\tthis.tool_id = tool_id;\n\t\tthis.matcher = matcher;\n\t\tthis.min_size = min_size;\n\t\tthis.max_size = max_size;\n\t\tthis.min_pretty_size = min_pretty_size;\n\t\tthis.max_pretty_size = max_pretty_size;\n\t\tthis.min_tokens = min_tokens;\n\t\tthis.max_tokens = max_tokens;\n\t\tthis.min_judges = min_judges;\n\t\tthis.min_confidence = min_confidence;\n\t\tthis.include_internal = includeInternal;\n\t\t\n\t\tnumClones_type1_inter = new HashMap<Long,Integer>();\n\t\tnumClones_type1_intra = new HashMap<Long,Integer>();\n\t\t\n\t\tnumDetected_type1_inter = new HashMap<Long,Integer>();\n\t\tnumDetected_type1_intra = new HashMap<Long,Integer>();\n\t\t\n\t\tnumClones_type2c_inter = new HashMap<Long,Integer>();\n\t\tnumClones_type2c_intra = new HashMap<Long,Integer>();\n\t\t\n\t\tnumDetected_type2c_inter = new HashMap<Long,Integer>();\n\t\tnumDetected_type2c_intra = new HashMap<Long,Integer>();\n\t\t\n\t\tnumClones_type2b_inter = new HashMap<Long,Integer>();\n\t\tnumClones_type2b_intra = new HashMap<Long,Integer>();\n\t\t\n\t\tnumDetected_type2b_inter = new HashMap<Long,Integer>();\n\t\tnumDetected_type2b_intra = new HashMap<Long,Integer>();\n\t\t\n\t\tnumClones_type3_inter = (HashMap<Long,Integer>[]) new HashMap[20];\n\t\tnumClones_type3_intra = (HashMap<Long,Integer>[]) new HashMap[20];\n\t\t\n\t\tnumDetected_type3_inter = (HashMap<Long,Integer>[]) new HashMap[20];\n\t\tnumDetected_type3_intra = (HashMap<Long,Integer>[]) new HashMap[20];\n\t\t\n\t\tnumClones_false_inter = new HashMap<Long,Integer>();\n\t\tnumClones_false_intra = new HashMap<Long,Integer>();\n\t\t\n\t\tnumDetected_false_inter = new HashMap<Long,Integer>();\n\t\tnumDetected_false_intra = new HashMap<Long,Integer>();\n\t\t\n\t\tfor(int i = 0; i < 20; i++) {\n\t\t\tnumClones_type3_inter[i] = new HashMap<Long,Integer>();\n\t\t\tnumClones_type3_intra[i] = new HashMap<Long,Integer>();\n\t\t\tnumDetected_type3_inter[i] = new HashMap<Long,Integer>();\n\t\t\tnumDetected_type3_intra[i] = new HashMap<Long,Integer>();\n\t\t}\n\t\t\n\t\tfunctionality_ids = Functionalities.getFunctionalityIds();\n\t\tfor(long id : functionality_ids) {\n\t\t\tnumClones_type1_inter.put(id, null);\n\t\t\tnumDetected_type1_inter.put(id, null);\n\t\t\tnumClones_type2c_inter.put(id, null);\n\t\t\tnumDetected_type2c_inter.put(id, null);\n\t\t\tnumClones_type1_intra.put(id, null);\n\t\t\tnumDetected_type1_intra.put(id, null);\n\t\t\tnumClones_type2c_intra.put(id, null);\n\t\t\tnumDetected_type2c_intra.put(id, null);\n\t\t\tfor(int i = 0; i < 19; i++) {\n\t\t\t\tnumClones_type3_inter[i].put(id, null);\n\t\t\t\tnumDetected_type3_inter[i].put(id, null);\n\t\t\t\tnumClones_type3_intra[i].put(id, null);\n\t\t\t\tnumDetected_type3_intra[i].put(id, null);\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime\n\t\t\t\t* result\n\t\t\t\t+ ((functionality_ids == null) ? 0 : functionality_ids\n\t\t\t\t\t\t.hashCode());\n\t\tresult = prime * result + ((matcher == null) ? 0 : matcher.hashCode());\n\t\tresult = prime * result\n\t\t\t\t+ ((max_pretty_size == null) ? 0 : max_pretty_size.hashCode());\n\t\tresult = prime * result\n\t\t\t\t+ ((max_size == null) ? 0 : max_size.hashCode());\n\t\tresult = prime * result\n\t\t\t\t+ ((max_tokens == null) ? 0 : max_tokens.hashCode());\n\t\tresult = prime * result\n\t\t\t\t+ ((min_confidence == null) ? 0 : min_confidence.hashCode());\n\t\tresult = prime * result\n\t\t\t\t+ ((min_judges == null) ? 0 : min_judges.hashCode());\n\t\tresult = prime * result\n\t\t\t\t+ ((min_pretty_size == null) ? 0 : min_pretty_size.hashCode());\n\t\tresult = prime * result\n\t\t\t\t+ ((min_size == null) ? 0 : min_size.hashCode());\n\t\tresult = prime * result\n\t\t\t\t+ ((min_tokens == null) ? 0 : min_tokens.hashCode());\n\t\tresult = prime\n\t\t\t\t* result\n\t\t\t\t+ ((numClones_false_inter == null) ? 0 : numClones_false_inter\n\t\t\t\t\t\t.hashCode());\n\t\tresult = prime\n\t\t\t\t* result\n\t\t\t\t+ ((numClones_false_intra == null) ? 0 : numClones_false_intra\n\t\t\t\t\t\t.hashCode());\n\t\tresult = prime\n\t\t\t\t* result\n\t\t\t\t+ ((numClones_type1_inter == null) ? 0 : numClones_type1_inter\n\t\t\t\t\t\t.hashCode());\n\t\tresult = prime\n\t\t\t\t* result\n\t\t\t\t+ ((numClones_type1_intra == null) ? 0 : numClones_type1_intra\n\t\t\t\t\t\t.hashCode());\n\t\tresult = prime\n\t\t\t\t* result\n\t\t\t\t+ ((numClones_type2b_inter == null) ? 0\n\t\t\t\t\t\t: numClones_type2b_inter.hashCode());\n\t\tresult = prime\n\t\t\t\t* result\n\t\t\t\t+ ((numClones_type2b_intra == null) ? 0\n\t\t\t\t\t\t: numClones_type2b_intra.hashCode());\n\t\tresult = prime\n\t\t\t\t* result\n\t\t\t\t+ ((numClones_type2c_inter == null) ? 0\n\t\t\t\t\t\t: numClones_type2c_inter.hashCode());\n\t\tresult = prime\n\t\t\t\t* result\n\t\t\t\t+ ((numClones_type2c_intra == null) ? 0\n\t\t\t\t\t\t: numClones_type2c_intra.hashCode());\n\t\tresult = prime * result + Arrays.hashCode(numClones_type3_inter);\n\t\tresult = prime * result + Arrays.hashCode(numClones_type3_intra);\n\t\tresult = prime\n\t\t\t\t* result\n\t\t\t\t+ ((numDetected_false_inter == null) ? 0\n\t\t\t\t\t\t: numDetected_false_inter.hashCode());\n\t\tresult = prime\n\t\t\t\t* result\n\t\t\t\t+ ((numDetected_false_intra == null) ? 0\n\t\t\t\t\t\t: numDetected_false_intra.hashCode());\n\t\tresult = prime\n\t\t\t\t* result\n\t\t\t\t+ ((numDetected_type1_inter == null) ? 0\n\t\t\t\t\t\t: numDetected_type1_inter.hashCode());\n\t\tresult = prime\n\t\t\t\t* result\n\t\t\t\t+ ((numDetected_type1_intra == null) ? 0\n\t\t\t\t\t\t: numDetected_type1_intra.hashCode());\n\t\tresult = prime\n\t\t\t\t* result\n\t\t\t\t+ ((numDetected_type2b_inter == null) ? 0\n\t\t\t\t\t\t: numDetected_type2b_inter.hashCode());\n\t\tresult = prime\n\t\t\t\t* result\n\t\t\t\t+ ((numDetected_type2b_intra == null) ? 0\n\t\t\t\t\t\t: numDetected_type2b_intra.hashCode());\n\t\tresult = prime\n\t\t\t\t* result\n\t\t\t\t+ ((numDetected_type2c_inter == null) ? 0\n\t\t\t\t\t\t: numDetected_type2c_inter.hashCode());\n\t\tresult = prime\n\t\t\t\t* result\n\t\t\t\t+ ((numDetected_type2c_intra == null) ? 0\n\t\t\t\t\t\t: numDetected_type2c_intra.hashCode());\n\t\tresult = prime * result + Arrays.hashCode(numDetected_type3_inter);\n\t\tresult = prime * result + Arrays.hashCode(numDetected_type3_intra);\n\t\tresult = prime * result + similarity_type;\n\t\tresult = prime * result + ((tool_id == null) ? 0 : tool_id.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tToolEvaluator other = (ToolEvaluator) obj;\n\t\tif (functionality_ids == null) {\n\t\t\tif (other.functionality_ids != null)\n\t\t\t\treturn false;\n\t\t} else if (!functionality_ids.equals(other.functionality_ids))\n\t\t\treturn false;\n\t\tif (matcher == null) {\n\t\t\tif (other.matcher != null)\n\t\t\t\treturn false;\n\t\t} else if (!matcher.equals(other.matcher))\n\t\t\treturn false;\n\t\tif (max_pretty_size == null) {\n\t\t\tif (other.max_pretty_size != null)\n\t\t\t\treturn false;\n\t\t} else if (!max_pretty_size.equals(other.max_pretty_size))\n\t\t\treturn false;\n\t\tif (max_size == null) {\n\t\t\tif (other.max_size != null)\n\t\t\t\treturn false;\n\t\t} else if (!max_size.equals(other.max_size))\n\t\t\treturn false;\n\t\tif (max_tokens == null) {\n\t\t\tif (other.max_tokens != null)\n\t\t\t\treturn false;\n\t\t} else if (!max_tokens.equals(other.max_tokens))\n\t\t\treturn false;\n\t\tif (min_confidence == null) {\n\t\t\tif (other.min_confidence != null)\n\t\t\t\treturn false;\n\t\t} else if (!min_confidence.equals(other.min_confidence))\n\t\t\treturn false;\n\t\tif (min_judges == null) {\n\t\t\tif (other.min_judges != null)\n\t\t\t\treturn false;\n\t\t} else if (!min_judges.equals(other.min_judges))\n\t\t\treturn false;\n\t\tif (min_pretty_size == null) {\n\t\t\tif (other.min_pretty_size != null)\n\t\t\t\treturn false;\n\t\t} else if (!min_pretty_size.equals(other.min_pretty_size))\n\t\t\treturn false;\n\t\tif (min_size == null) {\n\t\t\tif (other.min_size != null)\n\t\t\t\treturn false;\n\t\t} else if (!min_size.equals(other.min_size))\n\t\t\treturn false;\n\t\tif (min_tokens == null) {\n\t\t\tif (other.min_tokens != null)\n\t\t\t\treturn false;\n\t\t} else if (!min_tokens.equals(other.min_tokens))\n\t\t\treturn false;\n\t\tif (numClones_false_inter == null) {\n\t\t\tif (other.numClones_false_inter != null)\n\t\t\t\treturn false;\n\t\t} else if (!numClones_false_inter.equals(other.numClones_false_inter))\n\t\t\treturn false;\n\t\tif (numClones_false_intra == null) {\n\t\t\tif (other.numClones_false_intra != null)\n\t\t\t\treturn false;\n\t\t} else if (!numClones_false_intra.equals(other.numClones_false_intra))\n\t\t\treturn false;\n\t\tif (numClones_type1_inter == null) {\n\t\t\tif (other.numClones_type1_inter != null)\n\t\t\t\treturn false;\n\t\t} else if (!numClones_type1_inter.equals(other.numClones_type1_inter))\n\t\t\treturn false;\n\t\tif (numClones_type1_intra == null) {\n\t\t\tif (other.numClones_type1_intra != null)\n\t\t\t\treturn false;\n\t\t} else if (!numClones_type1_intra.equals(other.numClones_type1_intra))\n\t\t\treturn false;\n\t\tif (numClones_type2b_inter == null) {\n\t\t\tif (other.numClones_type2b_inter != null)\n\t\t\t\treturn false;\n\t\t} else if (!numClones_type2b_inter.equals(other.numClones_type2b_inter))\n\t\t\treturn false;\n\t\tif (numClones_type2b_intra == null) {\n\t\t\tif (other.numClones_type2b_intra != null)\n\t\t\t\treturn false;\n\t\t} else if (!numClones_type2b_intra.equals(other.numClones_type2b_intra))\n\t\t\treturn false;\n\t\tif (numClones_type2c_inter == null) {\n\t\t\tif (other.numClones_type2c_inter != null)\n\t\t\t\treturn false;\n\t\t} else if (!numClones_type2c_inter.equals(other.numClones_type2c_inter))\n\t\t\treturn false;\n\t\tif (numClones_type2c_intra == null) {\n\t\t\tif (other.numClones_type2c_intra != null)\n\t\t\t\treturn false;\n\t\t} else if (!numClones_type2c_intra.equals(other.numClones_type2c_intra))\n\t\t\treturn false;\n\t\tif (!Arrays.equals(numClones_type3_inter, other.numClones_type3_inter))\n\t\t\treturn false;\n\t\tif (!Arrays.equals(numClones_type3_intra, other.numClones_type3_intra))\n\t\t\treturn false;\n\t\tif (numDetected_false_inter == null) {\n\t\t\tif (other.numDetected_false_inter != null)\n\t\t\t\treturn false;\n\t\t} else if (!numDetected_false_inter\n\t\t\t\t.equals(other.numDetected_false_inter))\n\t\t\treturn false;\n\t\tif (numDetected_false_intra == null) {\n\t\t\tif (other.numDetected_false_intra != null)\n\t\t\t\treturn false;\n\t\t} else if (!numDetected_false_intra\n\t\t\t\t.equals(other.numDetected_false_intra))\n\t\t\treturn false;\n\t\tif (numDetected_type1_inter == null) {\n\t\t\tif (other.numDetected_type1_inter != null)\n\t\t\t\treturn false;\n\t\t} else if (!numDetected_type1_inter\n\t\t\t\t.equals(other.numDetected_type1_inter))\n\t\t\treturn false;\n\t\tif (numDetected_type1_intra == null) {\n\t\t\tif (other.numDetected_type1_intra != null)\n\t\t\t\treturn false;\n\t\t} else if (!numDetected_type1_intra\n\t\t\t\t.equals(other.numDetected_type1_intra))\n\t\t\treturn false;\n\t\tif (numDetected_type2b_inter == null) {\n\t\t\tif (other.numDetected_type2b_inter != null)\n\t\t\t\treturn false;\n\t\t} else if (!numDetected_type2b_inter\n\t\t\t\t.equals(other.numDetected_type2b_inter))\n\t\t\treturn false;\n\t\tif (numDetected_type2b_intra == null) {\n\t\t\tif (other.numDetected_type2b_intra != null)\n\t\t\t\treturn false;\n\t\t} else if (!numDetected_type2b_intra\n\t\t\t\t.equals(other.numDetected_type2b_intra))\n\t\t\treturn false;\n\t\tif (numDetected_type2c_inter == null) {\n\t\t\tif (other.numDetected_type2c_inter != null)\n\t\t\t\treturn false;\n\t\t} else if (!numDetected_type2c_inter\n\t\t\t\t.equals(other.numDetected_type2c_inter))\n\t\t\treturn false;\n\t\tif (numDetected_type2c_intra == null) {\n\t\t\tif (other.numDetected_type2c_intra != null)\n\t\t\t\treturn false;\n\t\t} else if (!numDetected_type2c_intra\n\t\t\t\t.equals(other.numDetected_type2c_intra))\n\t\t\treturn false;\n\t\tif (!Arrays.equals(numDetected_type3_inter,\n\t\t\t\tother.numDetected_type3_inter))\n\t\t\treturn false;\n\t\tif (!Arrays.equals(numDetected_type3_intra,\n\t\t\t\tother.numDetected_type3_intra))\n\t\t\treturn false;\n\t\tif (similarity_type != other.similarity_type)\n\t\t\treturn false;\n\t\tif (tool_id == null) {\n\t\t\tif (other.tool_id != null)\n\t\t\t\treturn false;\n\t\t} else if (!tool_id.equals(other.tool_id))\n\t\t\treturn false;\n\t\treturn true;\n\t}\t\n\t\n//\tpublic static boolean exists(ToolEvaluator te, Path dir) throws SQLException {\n//\t\tPath pserialized = dir.resolve(te.getSerializedFileName());\n//\t\treturn Files.exists(pserialized);\n//\t}\n//\t\n//\tpublic static ToolEvaluator load(ToolEvaluator te, Path dir) throws FileNotFoundException, IOException, ClassNotFoundException, SQLException {\n//\t\tPath pserialized = dir.resolve(te.getSerializedFileName());\n//\t\tObjectInputStream ois = new ObjectInputStream(new FileInputStream(pserialized.toFile()));\n//\t\tToolEvaluator check = (ToolEvaluator) ois.readObject();\n//\t\tois.close();\n//\t\treturn check;\n//\t}\n//\t\n//\tpublic static void save(ToolEvaluator te, Path dir) throws FileNotFoundException, IOException, SQLException {\n//\t\tFiles.createDirectories(dir);\n//\t\tPath pserialized = dir.resolve(te.getSerializedFileName());\n//\t\tif(Files.exists(pserialized))\n//\t\t\tFiles.delete(pserialized);\n//\t\tFiles.createFile(pserialized);\n//\t\tObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(pserialized.toFile()));\n//\t\toos.writeObject(te);\n//\t\toos.close();\n//\t}\n\n\tpublic Long getTool_id() {\n\t\treturn tool_id;\n\t}\n\n\tpublic Integer getMin_size() {\n\t\treturn min_size;\n\t}\n\n\tpublic Integer getMax_size() {\n\t\treturn max_size;\n\t}\n\n\tpublic Integer getMin_pretty_size() {\n\t\treturn min_pretty_size;\n\t}\n\n\tpublic Integer getMax_pretty_size() {\n\t\treturn max_pretty_size;\n\t}\n\n\tpublic Integer getMin_tokens() {\n\t\treturn min_tokens;\n\t}\n\n\tpublic Integer getMax_tokens() {\n\t\treturn max_tokens;\n\t}\n\n\tpublic Integer getMin_judges() {\n\t\treturn min_judges;\n\t}\n\n\tpublic Integer getMin_confidence() {\n\t\treturn min_confidence;\n\t}\n\n\tpublic int getSimilarity_type() {\n\t\treturn similarity_type;\n\t}\n\n\tpublic String getSimilarity_type_string() {\n\t\tif(this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_AVG) {\n\t\t\treturn \"AVG\";\n\t\t} else if (this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_BOTH) {\n\t\t\treturn \"BOTH\";\n\t\t} else if (this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_LINE) {\n\t\t\treturn \"LINE\";\n\t\t} else if (this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_TOKEN) {\n\t\t\treturn \"TOKEN\";\n\t\t} else {\n\t\t\treturn \"UNKNOWN\";\n\t\t}\n\t}\n\t\n\tpublic boolean isInclude_internal() {\n\t\treturn include_internal;\n\t}\n\n\tpublic Set<Long> getFunctionality_ids() {\n\t\treturn functionality_ids;\n\t}\n\t\n}", "public class FixPath {\n\n\tpublic static Path getAbsolutePath(Path path) {\n\t\t// User executed form commands/ directory, but working directory is ../ from there.\n\t\t// If specified a relative directory, need to base it correctly from user perspective.\n\t\tif(!path.isAbsolute()) {\n\t\t\tpath = Paths.get(\"commands/\").toAbsolutePath().resolve(path);\n\t\t}\n\t\treturn path;\n\t}\n\t\n}", "public class ToolEvaluator implements Serializable {\n\n\tpublic void close() throws SQLException {\n\t\tthis.matcher.close();\n\t}\n\t\n\tpublic String toString() {\n\t\tString str;\n\t\tstr = \" Tool ID: \" + tool_id;\n\t\tstr += \"\\n\";\n\t\tstr += \" Matcher: \" + matcher.toString();\n\t\tstr += \"\\n\";\n\t\tstr += \" MinSize: \" + min_size;\n\t\tstr += \"\\n\";\n\t\tstr += \" MaxSize: \" + max_size;\n\t\tstr += \"\\n\";\n\t\tstr += \" MinPrettySize: \" + min_pretty_size;\n\t\tstr += \"\\n\";\n\t\tstr += \" MaxPrettySize: \" + max_pretty_size;\n\t\tstr += \"\\n\";\n\t\tstr += \" MinTokens: \" + min_tokens;\n\t\tstr += \"\\n\";\n\t\tstr += \" MaxTokens: \" + max_tokens;\n\t\tstr += \"\\n\";\n\t\tstr += \" MinJudges: \" + min_judges;\n\t\tstr += \"\\n\";\n\t\tstr += \" MinConfidence: \" + min_confidence;\n\t\tstr += \"\\n\";\n\t\tif(similarity_type == ToolEvaluator.SIMILARITY_TYPE_AVG) {\n\t\tstr += \"SimilarityType: SIMILARITY_TYPE_AVG\";\n\t\t} else if (similarity_type == ToolEvaluator.SIMILARITY_TYPE_BOTH) {\n\t\tstr += \"SimilarityType: SIMILARITY_TYPE_BOTH\";\n\t\t} else if (similarity_type == ToolEvaluator.SIMILARITY_TYPE_LINE) {\n\t\tstr += \"SimilarityType: SIMILARITY_TYPE_LINE\";\n\t\t} else if (similarity_type == ToolEvaluator.SIMILARITY_TYPE_TOKEN) {\n\t\tstr += \"SimilarityType: SIMILARITY_TYPE_TOKEN\";\n\t\t}\n\t\tstr += \"\\n\";\n\t\treturn str;\n\t}\n\t\n\tprivate static final long serialVersionUID = 1L;\n\t\n\tprivate Long tool_id;\n\tprivate CloneMatcher matcher;\n\tprivate Integer min_size;\n\tprivate Integer max_size;\n\tprivate Integer min_pretty_size;\n\tprivate Integer max_pretty_size;\n\tprivate Integer min_tokens;\n\tprivate Integer max_tokens;\n\tprivate Integer min_judges;\n\tprivate Integer min_confidence;\n\tprivate int similarity_type;\n\tprivate boolean include_internal = false;\n\t\n\tprivate Set<Long> functionality_ids;\n\t\n\tHashMap<Long,Integer> numClones_type1_inter;\n\tHashMap<Long,Integer> numDetected_type1_inter;\n\t\n\tHashMap<Long,Integer> numClones_type1_intra;\n\tHashMap<Long,Integer> numDetected_type1_intra;\n\t\n\tHashMap<Long,Integer> numClones_type2c_inter;\n\tHashMap<Long,Integer> numDetected_type2c_inter;\n\t\n\tHashMap<Long,Integer> numClones_type2c_intra;\n\tHashMap<Long,Integer> numDetected_type2c_intra;\n\t\n\tHashMap<Long,Integer> numClones_type2b_inter;\n\tHashMap<Long,Integer> numDetected_type2b_inter;\n\t\n\tHashMap<Long,Integer> numClones_type2b_intra;\n\tHashMap<Long,Integer> numDetected_type2b_intra;\n\t\n\tHashMap<Long,Integer>[] numClones_type3_inter;\n\tHashMap<Long,Integer>[] numDetected_type3_inter; // index, similarity ranges: [0-5), [5,10), [10,15), ..., [95-100]... on indexies 0 through 18\n\t\n\tHashMap<Long,Integer>[] numClones_type3_intra;\n\tHashMap<Long,Integer>[] numDetected_type3_intra;\n\t\n\tHashMap<Long, Integer> numClones_false_inter;\n\tHashMap<Long, Integer> numDetected_false_inter;\n\t\n\tHashMap<Long,Integer> numClones_false_intra;\n\tHashMap<Long,Integer> numDetected_false_intra;\n\t\n\tpublic static final int SIMILARITY_TYPE_TOKEN = 0;\n\tpublic static final int SIMILARITY_TYPE_LINE = 1;\n\tpublic static final int SIMILARITY_TYPE_BOTH = 2;\n\tpublic static final int SIMILARITY_TYPE_AVG = 3;\n\n// All Clones\n\t\n\tpublic int getNumClones_inter(long functionality_id) throws SQLException {\n\t\tint numClones = 0;\n\t\tnumClones += getNumClones_type1_inter(functionality_id);\n\t\tnumClones += getNumClones_type2c_inter(functionality_id);\n\t\tnumClones += getNumClones_type2b_inter(functionality_id);\n\t\tnumClones += getNumClones_type3_inter(functionality_id);\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_intra(long functionality_id) throws SQLException {\n\t\tint numClones = 0;\n\t\tnumClones += getNumClones_type1_intra(functionality_id);\n\t\tnumClones += getNumClones_type2c_intra(functionality_id);\n\t\tnumClones += getNumClones_type2b_intra(functionality_id);\n\t\tnumClones += getNumClones_type3_intra(functionality_id);\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones(long functionality_id) throws SQLException {\n\t\tint numClones = 0;\n\t\tnumClones += getNumClones_type1(functionality_id);\n\t\tnumClones += getNumClones_type2c(functionality_id);\n\t\tnumClones += getNumClones_type2b(functionality_id);\n\t\tnumClones += getNumClones_type3(functionality_id);\n\t\treturn numClones;\n\t}\n\t\t\n\t\n\tpublic int getNumDetected_inter(long functionality_id) throws SQLException {\n\t\tint numDetected = 0;\n\t\tnumDetected += this.getNumDetected_type1_inter(functionality_id);\n\t\tnumDetected += this.getNumDetected_type2_inter(functionality_id);\n\t\tnumDetected += this.getNumDetected_type3_inter(functionality_id);\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_intra(long functionality_id) throws SQLException {\n\t\tint numDetected = 0;\n\t\tnumDetected += this.getNumDetected_type1_intra(functionality_id);\n\t\tnumDetected += this.getNumDetected_type2_intra(functionality_id);\n\t\tnumDetected += this.getNumDetected_type3_intra(functionality_id);\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected(long functionality_id) throws SQLException {\n\t\tint numDetected = 0;\n\t\tnumDetected += this.getNumDetected_type1(functionality_id);\n\t\tnumDetected += this.getNumDetected_type2(functionality_id);\n\t\tnumDetected += this.getNumDetected_type3(functionality_id);\n\t\treturn numDetected;\n\t}\n\t\n\t\n\tpublic double getRecall_inter(long functionality_id) throws SQLException {\n\t\tint numClones = this.getNumClones_inter(functionality_id);\n\t\tint numDetected = this.getNumDetected_inter(functionality_id);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_intra(long functionality_id) throws SQLException {\n\t\tint numClones = this.getNumClones_intra(functionality_id);\n\t\tint numDetected = this.getNumDetected_intra(functionality_id);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall(long functionality_id) throws SQLException {\n\t\tint numClones = this.getNumClones(functionality_id);\n\t\tint numDetected = this.getNumDetected(functionality_id);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic int getNumClones_inter() throws SQLException {\n\t\tint numClones = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tnumClones += this.getNumClones_inter(id);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_intra() throws SQLException {\n\t\tint numClones = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tnumClones += this.getNumClones_intra(id);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones() throws SQLException {\n\t\tint numClones = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tnumClones += this.getNumClones(id);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\t\n\tpublic int getNumDetected_inter() throws SQLException {\n\t\tint numDetected = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tnumDetected += this.getNumDetected_inter(id);\n\t\t}\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_intra() throws SQLException {\n\t\tint numDetected = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tnumDetected += this.getNumDetected_intra(id);\n\t\t}\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected() throws SQLException {\n\t\tint numDetected = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tnumDetected += this.getNumDetected(id);\n\t\t}\n\t\treturn numDetected;\n\t}\n\t\n\t\n\tpublic double getRecall_inter() throws SQLException {\n\t\tint numClones = getNumClones_inter();\n\t\tint numDetected = getNumDetected_inter();\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_intra() throws SQLException {\n\t\tint numClones = getNumClones_intra();\n\t\tint numDetected = getNumDetected_intra();\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall() throws SQLException {\n\t\tint numClones = getNumClones();\n\t\tint numDetected = getNumDetected();\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_avg() throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getRecall(id);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\tpublic double getRecall_avg_inter() throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getRecall_inter(id);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\tpublic double getRecall_avg_intra() throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getRecall_intra(id);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\t\n// False\n\tpublic int getNumClones_false_inter(long functionality_id) throws SQLException {\n\t\tif(!numClones_false_inter.containsKey(functionality_id)) {\n\t\t\tint numClones = EvaluateTools.numFalsePositives(functionality_id, this.min_judges, this.min_confidence, EvaluateTools.INTER_PROJECT_CLONES);\n\t\t\tnumClones_false_inter.put(functionality_id, numClones);\n\t\t}\n\t\treturn numClones_false_inter.get(functionality_id);\n\t}\n\tpublic int getNumClones_false_intra(long functionality_id) throws SQLException {\n\t\tif(!numClones_false_intra.containsKey(functionality_id)) {\n\t\t\tint numClones = EvaluateTools.numFalsePositives(functionality_id, this.min_judges, this.min_confidence, EvaluateTools.INTRA_PROJECT_CLONES);\n\t\t\tnumClones_false_intra.put(functionality_id, numClones);\n\t\t}\n\t\treturn numClones_false_intra.get(functionality_id);\n\t}\n\tpublic int getNumClones_false(long functionality_id) throws SQLException {\n\t\treturn getNumClones_false_inter(functionality_id) + getNumClones_false_intra(functionality_id);\n\t}\n\t\t\n\t\n\tpublic int getNumDetected_false_inter(long functionality_id) throws SQLException {\n\t\tif(!numDetected_false_inter.containsKey(functionality_id)) {\n\t\t\tint numDetected = EvaluateTools.numFalseDetected(tool_id, functionality_id, this.min_judges, this.min_confidence, EvaluateTools.INTER_PROJECT_CLONES, this.matcher);\n\t\t\tnumDetected_false_inter.put(functionality_id, numDetected);\n\t\t}\n\t\treturn numDetected_false_inter.get(functionality_id);\n\t}\n\tpublic int getNumDetected_false_intra(long functionality_id) throws SQLException {\n\t\tif(!numDetected_false_intra.containsKey(functionality_id)) {\n\t\t\tint numDetected = EvaluateTools.numFalseDetected(tool_id, functionality_id, this.min_judges, this.min_confidence, EvaluateTools.INTRA_PROJECT_CLONES, this.matcher);\n\t\t\tnumDetected_false_intra.put(functionality_id, numDetected);\n\t\t}\n\t\treturn numDetected_false_intra.get(functionality_id);\n\t}\n\tpublic int getNumDetected_false(long functionality_id) throws SQLException {\n\t\treturn getNumDetected_false_inter(functionality_id) + getNumDetected_false_intra(functionality_id);\n\t}\n\t\n\t\n\tpublic int getNumClones_false_inter() throws SQLException {\n\t\tint numFalse = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tnumFalse += getNumClones_false_inter(id);\n\t\t}\n\t\treturn numFalse;\n\t}\n\tpublic int getNumClones_false_intra() throws SQLException {\n\t\tint numFalse = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tnumFalse += getNumClones_false_intra(id);\n\t\t}\n\t\treturn numFalse;\n\t}\n\tpublic int getNumClones_false() throws SQLException {\n\t\treturn getNumClones_false_inter() + getNumClones_false_intra();\n\t}\n\t\n\t\n\tpublic int getNumDetected_false_inter() throws SQLException {\n\t\tint numDetected = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tnumDetected += getNumDetected_false_inter(id);\n\t\t}\n\t\treturn numDetected;\n\t}\n\tpublic int getNumDetected_false_intra() throws SQLException {\n\t\tint numDetected = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tnumDetected += getNumDetected_false_intra(id);\n\t\t}\n\t\treturn numDetected;\n\t}\n\tpublic int getNumDetected_false() throws SQLException {\n\t\treturn getNumDetected_false_inter() + getNumDetected_false_intra();\n\t}\n\t\n\t\n\tpublic double getRecall_false_inter(long functionality_id) throws SQLException {\n\t\tint numDetected_false = this.getNumDetected_false_inter(functionality_id);\n\t\tint numClones_false = this.getNumClones_false_inter(functionality_id);\n\t\treturn 1.0*numDetected_false/numClones_false;\n\t}\n\tpublic double getRecall_false_intra(long functionality_id) throws SQLException {\n\t\tint numDetected_false = this.getNumDetected_false_intra(functionality_id);\n\t\tint numClones_false = this.getNumClones_false_intra(functionality_id);\n\t\treturn 1.0*numDetected_false/numClones_false;\n\t}\n\tpublic double getRecall_false(long functionality_id) throws SQLException {\n\t\tint numDetected_false = this.getNumDetected_false(functionality_id);\n\t\tint numClones_false = this.getNumClones_false(functionality_id);\n\t\treturn 1.0*numDetected_false/numClones_false;\n\t}\n\t\n\t\n\tpublic double getRecall_false_inter() throws SQLException {\n\t\tint numDetected_false = this.getNumDetected_false_inter();\n\t\tint numClones_false = this.getNumClones_false_inter();\n\t\treturn 1.0*numDetected_false/numClones_false;\n\t}\n\tpublic double getRecall_false_intra() throws SQLException {\n\t\tint numDetected_false = this.getNumDetected_false_intra();\n\t\tint numClones_false = this.getNumClones_false_intra();\n\t\treturn 1.0*numDetected_false/numClones_false;\n\t}\n\tpublic double getRecall_false() throws SQLException {\n\t\tint numDetected_false = this.getNumDetected_false();\n\t\tint numClones_false = this.getNumClones_false();\n\t\treturn 1.0*numDetected_false/numClones_false;\n\t}\n\t\n\t/**\n\t * Calculated as the ratio of the known clones/false detected that are true not false positives.\n\t * @param functionality_id\n\t * @return\n\t * @throws SQLException\n\t */\n\tpublic double getPrecision_inter(long functionality_id) throws SQLException {\n\t\tint numDetected_true = this.getNumDetected_inter(functionality_id);\n\t\tint numDetected_false = this.getNumDetected_false_inter(functionality_id);\n\t\treturn 1.0*numDetected_true/(numDetected_true+numDetected_false);\n\t}\n\tpublic double getPrecision_intra(long functionality_id) throws SQLException {\n\t\tint numDetected_true = this.getNumDetected_intra(functionality_id);\n\t\tint numDetected_false = this.getNumDetected_false_intra(functionality_id);\n\t\treturn 1.0*numDetected_true/(numDetected_true+numDetected_false);\n\t}\n\tpublic double getPrecision(long functionality_id) throws SQLException {\n\t\tint numDetected_true = this.getNumDetected(functionality_id);\n\t\tint numDetected_false = this.getNumDetected_false(functionality_id);\n\t\treturn 1.0*numDetected_true/(numDetected_true+numDetected_false);\n\t}\n\n\t/**\n\t * Calculated as the ratio of the known clones/false detected that are true not false positives.\n\t * @return\n\t * @throws SQLException\n\t */\n\tpublic double getPrecision_inter() throws SQLException {\n\t\tint numDetected_true = this.getNumDetected_inter();\n\t\tint numDetected_false = this.getNumDetected_false_inter();\n\t\treturn 1.0*numDetected_true/(numDetected_true+numDetected_false);\n\t}\n\tpublic double getPrecision_avg_inter() throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getPrecision_inter(id);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\tpublic double getPrecision_intra() throws SQLException {\n\t\tint numDetected_true = this.getNumDetected_intra();\n\t\tint numDetected_false = this.getNumDetected_false_intra();\n\t\treturn 1.0*numDetected_true/(numDetected_true+numDetected_false);\n\t}\n\tpublic double getPrecision_avg_intra() throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getPrecision_intra(id);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\tpublic double getPrecision() throws SQLException {\n\t\tint numDetected_true = this.getNumDetected();\n\t\tint numDetected_false = this.getNumDetected_false();\n\t\treturn 1.0*numDetected_true/(numDetected_true+numDetected_false);\n\t}\n\t\n\tpublic double getPrecision_avg() throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getPrecision(id);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\t\n// Type-1\n\tpublic int getNumClones_type1_inter(long functionality_id) throws SQLException {\n\t\tif(numClones_type1_inter.get(functionality_id) == null) {\n\t\t\tint numClones = \n\t\t\t\t\tEvaluateTools.numClones(\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t1,\n\t\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTER_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t \t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tmin_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tmax_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tmin_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tmax_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tmin_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tmax_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tmin_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tmin_confidence,\n\t\t\t\t\t\t\t\t\t\t\t\t \t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t);\n\t\t\tnumClones_type1_inter.put(functionality_id, numClones);\n\t\t}\n\t\treturn numClones_type1_inter.get(functionality_id);\n\t}\n\t\n\tpublic int getNumClones_type1_intra(long functionality_id) throws SQLException {\n\t\tif(numClones_type1_intra.get(functionality_id) == null) {\n\t\t\tint numClones = \n\t\t\t\t\tEvaluateTools.numClones(\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t1,\n\t\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTRA_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t \t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tmin_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tmax_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tmin_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tmax_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tmin_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tmax_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tmin_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tmin_confidence,\n\t\t\t\t\t\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t);\n\t\t\tnumClones_type1_intra.put(functionality_id, numClones);\n\t\t}\n\t\treturn numClones_type1_intra.get(functionality_id);\n\t}\n\t\n\tpublic int getNumClones_type1(long functionality_id) throws SQLException {\n\t\treturn getNumClones_type1_inter(functionality_id) + getNumClones_type1_intra(functionality_id);\n\t}\n\t\n\tpublic int getNumClones_type1_inter() throws SQLException {\n\t\t//System.out.println(\"\\tgetNumClones_type1_inter\");\n\t\tint numClones = 0;\n\t\t\n\t\tfor(Long fid : functionality_ids) {\n\t\t\t//System.out.println(\"\\t\\t\"+fid);\n\t\t\tnumClones += getNumClones_type1_inter(fid);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_type1_intra() throws SQLException {\n\t\t//System.out.println(\"\\tgetNumClones_type1_intra\");\n\t\tint numClones = 0;\n\t\tfor(Long fid : functionality_ids) {\n\t\t\t//System.out.println(\"\\t\\t\" + fid);\n\t\t\tnumClones += getNumClones_type1_intra(fid);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_type1() throws SQLException {\n\t\t//System.out.println(\"getNumClones_type1\");\n\t\treturn getNumClones_type1_inter() + getNumClones_type1_intra();\n\t}\n\t\n\tpublic int getNumDetected_type1_inter(long functionality_id) throws SQLException {\n\t\tif(numDetected_type1_inter.get(functionality_id) == null) {\n\t\t\tint numDetected =\n\t\t\t\t\tEvaluateTools.numTrueDetected( \t /*tool_id*/\tthis.tool_id, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*matcher*/\tthis.matcher, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t1,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTER_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tthis.min_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tthis.max_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tthis.min_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tthis.max_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tthis.min_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tthis.max_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tthis.min_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tthis.min_confidence,\n\t\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t);\n\t\t\tnumDetected_type1_inter.put(functionality_id, numDetected);\n\t\t}\n\t\treturn numDetected_type1_inter.get(functionality_id);\n\t}\n\t\n\tpublic int getNumDetected_type1_intra(long functionality_id) throws SQLException {\n\t\tif(numDetected_type1_intra.get(functionality_id) == null) {\n\t\t\tint numDetected =\n\t\t\t\t\tEvaluateTools.numTrueDetected( \t /*tool_id*/\tthis.tool_id, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*matcher*/\tthis.matcher, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t1,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTRA_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tthis.min_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tthis.max_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tthis.min_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tthis.max_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tthis.min_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tthis.max_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tthis.min_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tthis.min_confidence,\n\t\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t);\n\t\t\tnumDetected_type1_intra.put(functionality_id, numDetected);\n\t\t}\n\t\treturn numDetected_type1_intra.get(functionality_id);\n\t}\n\t\n\tpublic int getNumDetected_type1(long functionality_id) throws SQLException {\n\t\treturn getNumDetected_type1_inter(functionality_id) + getNumDetected_type1_intra(functionality_id);\n\t}\n\t\n\tpublic int getNumDetected_type1_inter() throws SQLException {\n\t\t//System.out.println(\"\\tgetNumDetected_type1_inter\");\n\t\tint numDetected = 0;\n\t\tfor(Long fid : functionality_ids) {\n\t\t\t//System.out.println(\"\\t\\t\" + fid);\n\t\t\tnumDetected += getNumDetected_type1_inter(fid);\n\t\t}\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_type1_intra() throws SQLException {\n\t\t//System.out.println(\"\\tgetNumDetected_type1_intra\");\n\t\tint numDetected = 0;\n\t\tfor(Long fid : functionality_ids) {\n\t\t\t//System.out.println(\"\\t\\t\"+fid);\n\t\t\tnumDetected += getNumDetected_type1_intra(fid);\n\t\t}\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_type1() throws SQLException {\n\t\t//System.out.println(\"getNumDetected_type1\");\n\t\treturn getNumDetected_type1_inter() + getNumDetected_type1_intra();\n\t}\n\t\n\tpublic double getRecall_type1_inter(long functionality_id) throws SQLException {\n\t\tint numDetected = getNumDetected_type1_inter(functionality_id);\n\t\tint numClones = getNumClones_type1_inter(functionality_id);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type1_intra(long functionality_id) throws SQLException {\n\t\tint numDetected = getNumDetected_type1_intra(functionality_id);\n\t\tint numClones = getNumClones_type1_intra(functionality_id);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type1(long functionality_id) throws SQLException {\n\t\tint numDetected = getNumDetected_type1(functionality_id);\n\t\tint numClones = getNumClones_type1(functionality_id);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type1_inter() throws SQLException {\n\t\tint numDetected = getNumDetected_type1_inter();\n\t\tint numClones = getNumClones_type1_inter();\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type1_intra() throws SQLException {\n\t\tint numDetected = getNumDetected_type1_intra();\n\t\tint numClones = getNumClones_type1_intra();\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type1() throws SQLException {\n\t\t//System.out.println(\"getRecall_type1\");\n\t\tint numDetected = getNumDetected_type1();\n\t\tint numClones = getNumClones_type1();\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type1_avg() throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getRecall_type1(id);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\tpublic double getRecall_type1_avg_inter() throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getRecall_type1_inter(id);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\t\n\tpublic double getRecall_type1_avg_intra() throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getRecall_type1_intra(id);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\t\n// Type-2\n\t\n\tpublic int getNumClones_type2c_inter(long functionality_id) throws SQLException {\n\t\tif(numClones_type2c_inter.get(functionality_id) == null) {\n\t\t\tint numClones = \n\t\t\t\t\tEvaluateTools.numClones(\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t2,\n\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTER_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tmin_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tmax_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tmin_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tmax_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tmin_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tmax_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tmin_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tmin_confidence,\n\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t\t);\t\t\n\t\t\tnumClones_type2c_inter.put(functionality_id, numClones);\n\t\t}\n\t\treturn numClones_type2c_inter.get(functionality_id);\n\t}\n\t\n\tpublic int getNumClones_type2c_intra(long functionality_id) throws SQLException {\n\t\tif(numClones_type2c_intra.get(functionality_id) == null) {\n\t\t\tint numClones = \n\t\t\t\t\tEvaluateTools.numClones(\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t2,\n\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTRA_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tmin_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tmax_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tmin_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tmax_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tmin_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tmax_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tmin_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tmin_confidence,\n\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t\t);\t\t\n\t\t\tnumClones_type2c_intra.put(functionality_id, numClones);\n\t\t}\n\t\treturn numClones_type2c_intra.get(functionality_id);\n\t}\n\t\n\tpublic int getNumClones_type2c(long functionality_id) throws SQLException {\n\t\treturn getNumClones_type2c_inter(functionality_id) + getNumClones_type2c_intra(functionality_id);\n\t}\n\t\n\tpublic int getNumClones_type2c_inter() throws SQLException {\n\t\tint numClones = 0;\n\t\tfor(Long fid : functionality_ids) {\n\t\t\tnumClones += getNumClones_type2c_inter(fid);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_type2c_intra() throws SQLException {\n\t\tint numClones = 0;\n\t\tfor(Long fid : functionality_ids) {\n\t\t\tnumClones += getNumClones_type2c_intra(fid);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_type2c() throws SQLException {\n\t\treturn getNumClones_type2c_inter() + getNumClones_type2c_intra();\n\t}\n\t\n\tpublic int getNumDetected_type2c_inter(long functionality_id) throws SQLException {\n\t\tif(numDetected_type2c_inter.get(functionality_id) == null) {\n\t\t\tint numDetected =\n\t\t\t\t\tEvaluateTools.numTrueDetected( \t /*tool_id*/\tthis.tool_id, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*matcher*/\tthis.matcher, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t2,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTER_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tthis.min_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tthis.max_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tthis.min_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tthis.max_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tthis.min_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tthis.max_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tthis.min_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tthis.min_confidence,\n\t\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal);\n\t\t\tnumDetected_type2c_inter.put(functionality_id, numDetected);\n\t\t}\n\t\treturn numDetected_type2c_inter.get(functionality_id);\n\t}\n\t\n\tpublic int getNumDetected_type2c_intra(long functionality_id) throws SQLException {\n\t\tif(numDetected_type2c_intra.get(functionality_id) == null) {\n\t\t\tint numDetected =\n\t\t\t\t\tEvaluateTools.numTrueDetected( \t /*tool_id*/\tthis.tool_id, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*matcher*/\tthis.matcher, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t2,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTRA_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tthis.min_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tthis.max_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tthis.min_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tthis.max_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tthis.min_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tthis.max_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tthis.min_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tthis.min_confidence,\n\t\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal);\n\t\t\tnumDetected_type2c_intra.put(functionality_id, numDetected);\n\t\t}\n\t\treturn numDetected_type2c_intra.get(functionality_id);\n\t}\n\t\n\tpublic int getNumDetected_type2c(long functionality_id) throws SQLException {\n\t\treturn getNumDetected_type2c_inter(functionality_id) + getNumDetected_type2c_intra(functionality_id); \n\t}\n\t\n\tpublic int getNumDetected_type2c_inter() throws SQLException {\n\t\tint numDetected = 0;\n\t\tfor(Long fid : functionality_ids)\n\t\t\tnumDetected += getNumDetected_type2c_inter(fid);\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_type2c_intra() throws SQLException {\n\t\tint numDetected = 0;\n\t\tfor(Long fid : functionality_ids)\n\t\t\tnumDetected += getNumDetected_type2c_intra(fid);\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_type2c() throws SQLException {\n\t\treturn getNumDetected_type2c_inter() + getNumDetected_type2c_intra();\n\t}\n\t\n\tpublic double getRecall_type2c_inter(long functionality_id) throws SQLException {\n\t\tint numDetected = getNumDetected_type2c_inter(functionality_id);\n\t\tint numClones = getNumClones_type2c_inter(functionality_id);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type2c_intra(long functionality_id) throws SQLException {\n\t\tint numDetected = getNumDetected_type2c_intra(functionality_id);\n\t\tint numClones = getNumClones_type2c_intra(functionality_id);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type2c(long functionality_id) throws SQLException {\n\t\tint numDetected = getNumDetected_type2c(functionality_id);\n\t\tint numClones = getNumClones_type2c(functionality_id);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type2c_inter() throws SQLException {\n\t\tint numDetected = getNumDetected_type2c_inter();\n\t\tint numClones = getNumClones_type2c_inter();\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type2c_intra() throws SQLException {\n\t\tint numDetected = getNumDetected_type2c_intra();\n\t\tint numClones = getNumClones_type2c_intra();\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type2c() throws SQLException {\n\t\tint numDetected = getNumDetected_type2c();\n\t\tint numClones = getNumClones_type2c();\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type2c_avg() throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getRecall_type2c(id);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\tpublic double getRecall_type2c_avg_inter() throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getRecall_type2c_inter(id);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\tpublic double getRecall_type2c_avg_intra() throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getRecall_type2c_intra(id);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\t\n// Type-2 Blind\n\t\n\tpublic int getNumClones_type2b_inter(long functionality_id) throws SQLException {\n\t\tif(numClones_type2b_inter.get(functionality_id) == null) {\n\t\t\tint numClones = \n\t\t\t\t\tEvaluateTools.numClones(\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTER_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\t1.0,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tmin_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tmax_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tmin_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tmax_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tmin_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tmax_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tmin_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tmin_confidence,\n\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t\t);\t\t\n\t\t\tnumClones_type2b_inter.put(functionality_id, numClones);\n\t\t}\n\t\treturn numClones_type2b_inter.get(functionality_id);\n\t}\n\t\n\tpublic int getNumClones_type2b_intra(long functionality_id) throws SQLException {\n\t\tif(numClones_type2b_intra.get(functionality_id) == null) {\n\t\t\tint numClones = \n\t\t\t\t\tEvaluateTools.numClones(\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTRA_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\t1.0,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tmin_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tmax_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tmin_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tmax_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tmin_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tmax_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tmin_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tmin_confidence,\n\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t\t);\t\t\n\t\t\tnumClones_type2b_intra.put(functionality_id, numClones);\n\t\t}\n\t\treturn numClones_type2b_intra.get(functionality_id);\n\t}\n\t\n\tpublic int getNumClones_type2b(long functionality_id) throws SQLException {\n\t\treturn getNumClones_type2b_inter(functionality_id) + getNumClones_type2b_intra(functionality_id);\n\t}\n\t\n\tpublic int getNumClones_type2b_inter() throws SQLException {\n\t\tint numClones = 0;\n\t\tfor(Long fid : functionality_ids) {\n\t\t\tnumClones += getNumClones_type2b_inter(fid);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_type2b_intra() throws SQLException {\n\t\tint numClones = 0;\n\t\tfor(Long fid : functionality_ids) {\n\t\t\tnumClones += getNumClones_type2b_intra(fid);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_type2b() throws SQLException {\n\t\treturn getNumClones_type2b_inter() + getNumClones_type2b_intra();\n\t}\n\t\n\tpublic int getNumDetected_type2b_inter(long functionality_id) throws SQLException {\n\t\tif(numDetected_type2b_inter.get(functionality_id) == null) {\n\t\t\tint numDetected =\n\t\t\t\t\tEvaluateTools.numTrueDetected( \t /*tool_id*/\tthis.tool_id, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*matcher*/\tthis.matcher, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTER_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\t1.0,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tthis.min_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tthis.max_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tthis.min_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tthis.max_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tthis.min_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tthis.max_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tthis.min_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tthis.min_confidence,\n\t\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal);\n\t\t\tnumDetected_type2b_inter.put(functionality_id, numDetected);\n\t\t}\n\t\treturn numDetected_type2b_inter.get(functionality_id);\n\t}\n\t\n\tpublic int getNumDetected_type2b_intra(long functionality_id) throws SQLException {\n\t\tif(numDetected_type2b_intra.get(functionality_id) == null) {\n\t\t\tint numDetected =\n\t\t\t\t\tEvaluateTools.numTrueDetected( \t /*tool_id*/\tthis.tool_id, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*matcher*/\tthis.matcher, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTRA_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\t1.0,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tthis.min_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tthis.max_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tthis.min_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tthis.max_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tthis.min_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tthis.max_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tthis.min_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tthis.min_confidence,\n\t\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal);\n\t\t\tnumDetected_type2b_intra.put(functionality_id, numDetected);\n\t\t}\n\t\treturn numDetected_type2b_intra.get(functionality_id);\n\t}\n\t\n\tpublic int getNumDetected_type2b(long functionality_id) throws SQLException {\n\t\treturn getNumDetected_type2b_inter(functionality_id) + getNumDetected_type2b_intra(functionality_id);\n\t}\n\t\n\tpublic int getNumDetected_type2b_inter() throws SQLException {\n\t\tint numDetected = 0;\n\t\tfor(Long fid : functionality_ids)\n\t\t\tnumDetected += getNumDetected_type2b_inter(fid);\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_type2b_intra() throws SQLException {\n\t\tint numDetected = 0;\n\t\tfor(Long fid : functionality_ids)\n\t\t\tnumDetected += getNumDetected_type2b_intra(fid);\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_type2b() throws SQLException {\n\t\treturn getNumDetected_type2b_inter() + getNumDetected_type2b_intra();\n\t}\n\t\n\tpublic double getRecall_type2b_inter(long functionality_id) throws SQLException {\n\t\tint numDetected = getNumDetected_type2b_inter(functionality_id);\n\t\tint numClones = getNumClones_type2b_inter(functionality_id);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type2b_intra(long functionality_id) throws SQLException {\n\t\tint numDetected = getNumDetected_type2b_intra(functionality_id);\n\t\tint numClones = getNumClones_type2b_intra(functionality_id);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type2b(long functionality_id) throws SQLException {\n\t\tint numDetected = getNumDetected_type2b(functionality_id);\n\t\tint numClones = getNumClones_type2b(functionality_id);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type2b_inter() throws SQLException {\n\t\tint numDetected = getNumDetected_type2b_inter();\n\t\tint numClones = getNumClones_type2b_inter();\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type2b_intra() throws SQLException {\n\t\tint numDetected = getNumDetected_type2b_intra();\n\t\tint numClones = getNumClones_type2b_intra();\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type2b() throws SQLException {\n\t\tint numDetected = getNumDetected_type2b();\n\t\tint numClones = getNumClones_type2b();\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type2b_avg() throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getRecall_type2b(id);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\tpublic double getRecall_type2b_avg_inter() throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getRecall_type2b_inter(id);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\tpublic double getRecall_type2b_avg_intra() throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getRecall_type2b_intra(id);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\t\n// Type-2\n\t\n\tpublic int getNumClones_type2_inter(long functionality_id) throws SQLException {\n\t\tint numClones = 0;\n\t\tnumClones += getNumClones_type2b_inter(functionality_id);\n\t\tnumClones += getNumClones_type2c_inter(functionality_id);\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_type2_intra(long functionality_id) throws SQLException {\n\t\tint numClones = 0;\n\t\tnumClones += getNumClones_type2b_intra(functionality_id);\n\t\tnumClones += getNumClones_type2c_intra(functionality_id);\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_type2(long functionality_id) throws SQLException {\n\t\treturn getNumClones_type2_inter(functionality_id) + getNumClones_type2_intra(functionality_id);\n\t}\n\t\n\t\n\tpublic int getNumClones_type2_inter() throws SQLException {\n\t\tint numClones = 0;\n\t\tfor(Long fid : functionality_ids) {\n\t\t\tnumClones += getNumClones_type2_inter(fid);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_type2_intra() throws SQLException {\n\t\tint numClones = 0;\n\t\tfor(Long fid : functionality_ids) {\n\t\t\tnumClones += getNumClones_type2_intra(fid);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_type2() throws SQLException {\n\t\treturn getNumClones_type2_inter() + getNumClones_type2_intra();\n\t}\n\t\n\t\n\tpublic int getNumDetected_type2_inter(long functionality_id) throws SQLException {\n\t\tint numDetected = 0;\n\t\tnumDetected += getNumDetected_type2c_inter(functionality_id);\n\t\tnumDetected += getNumDetected_type2b_inter(functionality_id);\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_type2_intra(long functionality_id) throws SQLException {\n\t\tint numDetected = 0;\n\t\tnumDetected += getNumDetected_type2c_intra(functionality_id);\n\t\tnumDetected += getNumDetected_type2b_intra(functionality_id);\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_type2(long functionality_id) throws SQLException {\n\t\treturn getNumDetected_type2_inter(functionality_id) + getNumDetected_type2_intra(functionality_id);\n\t}\n\t\n\t\n\tpublic int getNumDetected_type2_inter() throws SQLException {\n\t\tint numDetected = 0;\n\t\tfor(Long fid : functionality_ids)\n\t\t\tnumDetected += getNumDetected_type2_inter(fid);\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_type2_intra() throws SQLException {\n\t\tint numDetected = 0;\n\t\tfor(Long fid : functionality_ids)\n\t\t\tnumDetected += getNumDetected_type2_intra(fid);\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_type2() throws SQLException {\n\t\treturn getNumDetected_type2_inter() + getNumDetected_type2_intra();\n\t}\n\t\n\t\n\tpublic double getRecall_type2_inter(long functionality_id) throws SQLException {\n\t\tint numDetected = getNumDetected_type2_inter(functionality_id);\n\t\tint numClones = getNumClones_type2_inter(functionality_id);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type2_intra(long functionality_id) throws SQLException {\n\t\tint numDetected = getNumDetected_type2_intra(functionality_id);\n\t\tint numClones = getNumClones_type2_intra(functionality_id);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type2(long functionality_id) throws SQLException {\n\t\tint numDetected = getNumDetected_type2(functionality_id);\n\t\tint numClones = getNumClones_type2(functionality_id);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\t\n\tpublic double getRecall_type2_inter() throws SQLException {\n\t\tint numDetected = getNumDetected_type2_inter();\n\t\tint numClones = getNumClones_type2_inter();\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type2_intra() throws SQLException {\n\t\tint numDetected = getNumDetected_type2_intra();\n\t\tint numClones = getNumClones_type2_intra();\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type2() throws SQLException {\n\t\tint numDetected = getNumDetected_type2();\n\t\tint numClones = getNumClones_type2();\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type2_avg() throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getRecall_type2b(id);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\tpublic double getRecall_type2_avg_inter() throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getRecall_type2b_inter(id);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\tpublic double getRecall_type2_avg_intra() throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getRecall_type2_intra(id);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\t\n// Type-3\n\t\t\n\tpublic int getNumClones_type3_inter(long functionality_id, int similarity) throws SQLException {\n\t\tif(similarity % 5 != 0 || similarity >= 100 || similarity < 0)\n\t\t\tthrow new IllegalArgumentException(\"Similarity must be a multiple of 5 in range [0-100).\");\n\t\tint index = similarity/5;\n\t\tdouble start = similarity/100.0;\n\t\tdouble end = (similarity+5)/100.0;\n\t\tif(numClones_type3_inter[index].get(functionality_id) == null) {\n\t\t\tint numClones;\n\t\t\tif(this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_LINE) {\n\t\t\t\tnumClones = \n\t\t\t\tEvaluateTools.numClones(\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTER_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tstart, \n\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tend, \n\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tmin_size, \n\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tmax_size, \n\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tmin_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tmax_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tmin_tokens, \n\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tmax_tokens, \n\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tmin_judges, \n\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tmin_confidence,\n\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t} else if(this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_TOKEN) {\n\t\t\t\tnumClones = \n\t\t\t\tEvaluateTools.numClones(\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTER_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tstart, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tend, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tmin_size, \n\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tmax_size, \n\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tmin_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tmax_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tmin_tokens, \n\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tmax_tokens, \n\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tmin_judges, \n\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tmin_confidence,\n\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t} else if(this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_BOTH) {\n\t\t\t\tnumClones = \n\t\t\t\tEvaluateTools.numClones(\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTER_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tstart,\n\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tend,\n\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tmin_size, \n\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tmax_size, \n\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tmin_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tmax_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tmin_tokens, \n\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tmax_tokens, \n\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tmin_judges, \n\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tmin_confidence,\n\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t} else {//if(this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_AVG) {\n\t\t\t\tnumClones = \n\t\t\t\tEvaluateTools.numClones(\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTER_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tstart,\n\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tend,\n\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tmin_size, \n\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tmax_size, \n\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tmin_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tmax_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tmin_tokens, \n\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tmax_tokens, \n\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tmin_judges, \n\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tmin_confidence,\n\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t}\n\t\t\tnumClones_type3_inter[index].put(functionality_id, numClones);\n\t\t}\n\t\treturn numClones_type3_inter[index].get(functionality_id);\n\t}\n\t\n\tpublic int getNumClones_type3_intra(long functionality_id, int similarity) throws SQLException {\n\t\tif(similarity % 5 != 0 || similarity >= 100 || similarity < 0)\n\t\t\tthrow new IllegalArgumentException(\"Similarity must be a multiple of 5 in range [0-100).\");\n\t\tint index = similarity/5;\n\t\tdouble start = similarity/100.0;\n\t\tdouble end = (similarity+5)/100.0;\n\t\tif(numClones_type3_intra[index].get(functionality_id) == null) {\n\t\t\tint numClones;\n\t\t\tif(this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_LINE) {\n\t\t\t\tnumClones = \n\t\t\t\tEvaluateTools.numClones(\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTRA_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tstart, \n\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tend, \n\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tmin_size, \n\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tmax_size, \n\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tmin_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tmax_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tmin_tokens, \n\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tmax_tokens, \n\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tmin_judges, \n\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tmin_confidence,\n\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t} else if(this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_TOKEN) {\n\t\t\t\tnumClones = \n\t\t\t\tEvaluateTools.numClones(\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTRA_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tstart, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tend, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tmin_size, \n\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tmax_size, \n\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tmin_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tmax_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tmin_tokens, \n\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tmax_tokens, \n\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tmin_judges, \n\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tmin_confidence,\n\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t} else if(this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_BOTH) {\n\t\t\t\tnumClones = \n\t\t\t\tEvaluateTools.numClones(\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTRA_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tstart,\n\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tend,\n\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tmin_size, \n\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tmax_size, \n\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tmin_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tmax_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tmin_tokens, \n\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tmax_tokens, \n\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tmin_judges, \n\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tmin_confidence,\n\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t} else {//if(this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_AVG) {\n\t\t\t\tnumClones = \n\t\t\t\tEvaluateTools.numClones(\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTRA_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tstart,\n\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tend,\n\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tmin_size, \n\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tmax_size, \n\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tmin_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tmax_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tmin_tokens, \n\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tmax_tokens, \n\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tmin_judges, \n\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tmin_confidence,\n\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t}\n\t\t\tnumClones_type3_intra[index].put(functionality_id, numClones);\n\t\t}\n\t\treturn numClones_type3_intra[index].get(functionality_id);\n\t}\n\t\n\tpublic int getNumClones_type3(long functionality_id, int similarity) throws SQLException {\n\t\treturn getNumClones_type3_inter(functionality_id, similarity) + getNumClones_type3_intra(functionality_id, similarity); \n\t}\n\t\n\t\t\t\n\tpublic int getNumClones_type3_inter(long functionality_id, int similarity_start, int similarity_end) throws SQLException {\n\t\tif(similarity_start < 0) throw new IllegalArgumentException(\"similarity_start must be >= 0.\");\n\t\tif(similarity_end > 100) throw new IllegalArgumentException(\"similarity_end must be <= 100\");\n\t\tif(similarity_start > similarity_end) throw new IllegalArgumentException(\"similarity start must be < similarity_end\");\n\t\tif(similarity_start % 5 != 0) throw new IllegalArgumentException(\"similarity_start must be a multiple of 5\");\n\t\tif(similarity_end % 5 != 0) throw new IllegalArgumentException(\"similarity_end must be a multiple of 5\");\n\t\t\n\t\tint numClones = 0;\n\t\tfor(int i = similarity_start; i < similarity_end; i += 5) {\n\t\t\tnumClones += getNumClones_type3_inter(functionality_id, i);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_type3_intra(long functionality_id, int similarity_start, int similarity_end) throws SQLException {\n\t\tif(similarity_start < 0) throw new IllegalArgumentException(\"similarity_start must be >= 0.\");\n\t\tif(similarity_end > 100) throw new IllegalArgumentException(\"similarity_end must be <= 100\");\n\t\tif(similarity_start > similarity_end) throw new IllegalArgumentException(\"similarity start must be < similarity_end\");\n\t\tif(similarity_start % 5 != 0) throw new IllegalArgumentException(\"similarity_start must be a multiple of 5\");\n\t\tif(similarity_end % 5 != 0) throw new IllegalArgumentException(\"similarity_end must be a multiple of 5\");\n\t\t\n\t\tint numClones = 0;\n\t\tfor(int i = similarity_start; i < similarity_end; i += 5) {\n\t\t\tnumClones += getNumClones_type3_intra(functionality_id, i);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_type3(long functionality_id, int similarity_start, int similarity_end) throws SQLException {\n\t\treturn getNumClones_type3_intra(functionality_id, similarity_start, similarity_end) + getNumClones_type3_inter(functionality_id, similarity_start, similarity_end); \n\t}\n\t\n\t\n\tpublic int getNumClones_type3_inter(int similarity_start, int similarity_end) throws SQLException {\n\t\tif(similarity_start < 0) throw new IllegalArgumentException(\"similarity_start must be >= 0.\");\n\t\tif(similarity_end > 100) throw new IllegalArgumentException(\"similarity_end must be <= 100\");\n\t\tif(similarity_start > similarity_end) throw new IllegalArgumentException(\"similarity start must be < similarity_end\");\n\t\tif(similarity_start % 5 != 0) throw new IllegalArgumentException(\"similarity_start must be a multiple of 5\");\n\t\tif(similarity_end % 5 != 0) throw new IllegalArgumentException(\"similarity_end must be a multiple of 5\");\n\t\t\n\t\tint numClones = 0;\n\t\tfor(long fid : functionality_ids) {\n\t\t\tnumClones += getNumClones_type3_inter(fid, similarity_start, similarity_end);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_type3_intra(int similarity_start, int similarity_end) throws SQLException {\n\t\tif(similarity_start < 0) throw new IllegalArgumentException(\"similarity_start must be >= 0.\");\n\t\tif(similarity_end > 100) throw new IllegalArgumentException(\"similarity_end must be <= 100\");\n\t\tif(similarity_start > similarity_end) throw new IllegalArgumentException(\"similarity start must be < similarity_end\");\n\t\tif(similarity_start % 5 != 0) throw new IllegalArgumentException(\"similarity_start must be a multiple of 5\");\n\t\tif(similarity_end % 5 != 0) throw new IllegalArgumentException(\"similarity_end must be a multiple of 5\");\n\t\t\n\t\tint numClones = 0;\n\t\tfor(long fid : functionality_ids) {\n\t\t\tnumClones += getNumClones_type3_intra(fid, similarity_start, similarity_end);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_type3(int similarity_start, int similarity_end) throws SQLException {\n\t\treturn getNumClones_type3_inter(similarity_start, similarity_end) + getNumClones_type3_intra(similarity_start, similarity_end);\n\t}\n\t\n\t\n\tpublic int getNumClones_type3_inter(long functionality_id) throws SQLException {\n\t\tint numClones = 0;\n\t\tfor(int i = 0; i < 100; i += 5) {\n\t\t\tnumClones += getNumClones_type3_inter(functionality_id, i, i+5);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_type3_intra(long functionality_id) throws SQLException {\n\t\tint numClones = 0;\n\t\tfor(int i = 0; i < 100; i += 5) {\n\t\t\tnumClones += getNumClones_type3_intra(functionality_id, i, i+5);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_type3(long functionality_id) throws SQLException {\n\t\treturn getNumClones_type3_inter(functionality_id) + getNumClones_type3_intra(functionality_id);\n\t}\n\t\n\t\t\n\tpublic int getNumClones_type3_inter() throws SQLException {\n\t\tint numClones = 0;\n\t\tfor(int i = 0; i < 100; i = i + 5) {\n\t\t\tnumClones += getNumClones_type3_inter(i, i+5);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_type3_intra() throws SQLException {\n\t\tint numClones = 0;\n\t\tfor(int i = 0; i < 100; i = i + 5) {\n\t\t\tnumClones += getNumClones_type3_intra(i, i+5);\n\t\t}\n\t\treturn numClones;\n\t}\n\t\n\tpublic int getNumClones_type3() throws SQLException {\n\t\treturn getNumClones_type3_intra() + getNumClones_type3_inter();\n\t}\n\t\n\t\n\tpublic int getNumDetected_type3_inter(long functionality_id, int similarity) throws SQLException {\n\t\tif(similarity % 5 != 0 || similarity >= 100 || similarity < 0)\n\t\t\tthrow new IllegalArgumentException(\"Similarity must be a multiple of 5 in range [0-100).\");\n\t\tint index = similarity/5;\n\t\tdouble start = similarity/100.0;\n\t\tdouble end = (similarity+5)/100.0;\n\t\t\n\t\tif(numDetected_type3_inter[index].get(functionality_id) == null) {\n\t\t\tint numDetected;\n\t\t\tif(this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_LINE) {\n\t\t\t\tnumDetected =\n\t\t\t\tEvaluateTools.numTrueDetected( \t /*tool_id*/\tthis.tool_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*matcher*/\tthis.matcher, \n\t\t\t\t\t\t\t\t\t\t\t\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTER_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tstart, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tend, \n\t\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tthis.min_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tthis.max_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tthis.min_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tthis.max_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tthis.min_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tthis.max_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tthis.min_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tthis.min_confidence,\n\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t} else if(this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_TOKEN) {\n\t\t\t\tnumDetected =\n\t\t\t\tEvaluateTools.numTrueDetected( \t /*tool_id*/\tthis.tool_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*matcher*/\tthis.matcher, \n\t\t\t\t\t\t\t\t\t\t\t\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTER_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tstart, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tend, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tthis.min_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tthis.max_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tthis.min_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tthis.max_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tthis.min_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tthis.max_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tthis.min_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tthis.min_confidence,\n\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t} else if(this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_BOTH) {\n\t\t\t\tnumDetected =\n\t\t\t\tEvaluateTools.numTrueDetected( \t /*tool_id*/\tthis.tool_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*matcher*/\tthis.matcher, \n\t\t\t\t\t\t\t\t\t\t\t\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTER_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tstart,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tend,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tthis.min_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tthis.max_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tthis.min_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tthis.max_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tthis.min_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tthis.max_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tthis.min_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tthis.min_confidence,\n\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t} else {//if(this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_AVG) {\n\t\t\t\tnumDetected =\n\t\t\t\tEvaluateTools.numTrueDetected( \t /*tool_id*/\tthis.tool_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*matcher*/\tthis.matcher, \n\t\t\t\t\t\t\t\t\t\t\t\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTER_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tstart,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tend,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tthis.min_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tthis.max_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tthis.min_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tthis.max_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tthis.min_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tthis.max_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tthis.min_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tthis.min_confidence,\n\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t}\n\t\t\tnumDetected_type3_inter[index].put(functionality_id, numDetected);\n\t\t}\n\t\treturn numDetected_type3_inter[index].get(functionality_id);\n\t}\n\t\n\tpublic int getNumDetected_type3_intra(long functionality_id, int similarity) throws SQLException {\n\t\tif(similarity % 5 != 0 || similarity >= 100 || similarity < 0)\n\t\t\tthrow new IllegalArgumentException(\"Similarity must be a multiple of 5 in range [0-100).\");\n\t\tint index = similarity/5;\n\t\tdouble start = similarity/100.0;\n\t\tdouble end = (similarity+5)/100.0;\n\t\t\n\t\tif(numDetected_type3_intra[index].get(functionality_id) == null) {\n\t\t\tint numDetected;\n\t\t\tif(this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_LINE) {\n\t\t\t\tnumDetected =\n\t\t\t\tEvaluateTools.numTrueDetected( \t /*tool_id*/\tthis.tool_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*matcher*/\tthis.matcher, \n\t\t\t\t\t\t\t\t\t\t\t\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTRA_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tstart, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tend, \n\t\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tthis.min_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tthis.max_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tthis.min_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tthis.max_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tthis.min_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tthis.max_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tthis.min_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tthis.min_confidence,\n\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t} else if(this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_TOKEN) {\n\t\t\t\tnumDetected =\n\t\t\t\tEvaluateTools.numTrueDetected( \t /*tool_id*/\tthis.tool_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*matcher*/\tthis.matcher, \n\t\t\t\t\t\t\t\t\t\t\t\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTRA_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tstart, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tend, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tthis.min_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tthis.max_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tthis.min_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tthis.max_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tthis.min_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tthis.max_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tthis.min_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tthis.min_confidence,\n\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t} else if(this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_BOTH) {\n\t\t\t\tnumDetected =\n\t\t\t\tEvaluateTools.numTrueDetected( \t /*tool_id*/\tthis.tool_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*matcher*/\tthis.matcher, \n\t\t\t\t\t\t\t\t\t\t\t\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTRA_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tstart,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tend,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tthis.min_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tthis.max_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tthis.min_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tthis.max_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tthis.min_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tthis.max_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tthis.min_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tthis.min_confidence,\n\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t} else {//if(this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_AVG) {\n\t\t\t\tnumDetected =\n\t\t\t\tEvaluateTools.numTrueDetected( \t /*tool_id*/\tthis.tool_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*matcher*/\tthis.matcher, \n\t\t\t\t\t\t\t\t\t\t\t\t /*functionality_id*/\tfunctionality_id, \n\t\t\t\t\t\t\t\t\t\t\t\t /*type*/\t3,\n\t\t\t\t\t\t\t\t\t\t\t\t /*Project Granularity*/\tEvaluateTools.INTRA_PROJECT_CLONES,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*token_gt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_gte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_gte_similarity*/\tstart,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_gte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*token_lt_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lt_similarity*/\tend,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lt_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*line_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t/*token_lte_similarity*/\tnull, \n\t\t\t\t\t\t\t\t\t\t\t\t /*avg_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*both_lte_similarity*/\tnull,\n\t\t\t\t\t\t\t\t\t\t\t\t /*min_size*/\tthis.min_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_size*/\tthis.max_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_pretty_size*/\tthis.min_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_pretty_size*/\tthis.max_pretty_size, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_tokens*/\tthis.min_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*max_tokens*/\tthis.max_tokens, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_judges*/\tthis.min_judges, \n\t\t\t\t\t\t\t\t\t\t\t\t /*min_confidence*/\tthis.min_confidence,\n\t\t \t\t\t\t\t\t\t\t\t\t\tinclude_internal\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t}\n\t\t\tnumDetected_type3_intra[index].put(functionality_id, numDetected);\n\t\t}\n\t\treturn numDetected_type3_intra[index].get(functionality_id);\n\t}\n\t\n\tpublic int getNumDetected_type3(long functionality_id, int similarity) throws SQLException {\n\t\treturn getNumDetected_type3_intra(functionality_id, similarity) + getNumDetected_type3_inter(functionality_id, similarity);\n\t}\n\t\n\t\n\tpublic int getNumDetected_type3_inter(long functionality_id, int similarity_start, int similarity_end) throws SQLException {\n\t\tif(similarity_start < 0) throw new IllegalArgumentException(\"similarity_start must be >= 0.\");\n\t\tif(similarity_end > 100) throw new IllegalArgumentException(\"similarity_end must be <= 100\");\n\t\tif(similarity_start > similarity_end) throw new IllegalArgumentException(\"similarity start must be < similarity_end\");\n\t\tif(similarity_start % 5 != 0) throw new IllegalArgumentException(\"similarity_start must be a multiple of 5\");\n\t\tif(similarity_end % 5 != 0) throw new IllegalArgumentException(\"similarity_end must be a multiple of 5\");\n\t\t\n\t\tint numDetected = 0;\n\t\tfor(int i = similarity_start; i < similarity_end; i += 5) {\n\t\t\tnumDetected += getNumDetected_type3_inter(functionality_id, i);\n\t\t}\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_type3_intra(long functionality_id, int similarity_start, int similarity_end) throws SQLException {\n\t\tif(similarity_start < 0) throw new IllegalArgumentException(\"similarity_start must be >= 0.\");\n\t\tif(similarity_end > 100) throw new IllegalArgumentException(\"similarity_end must be <= 100\");\n\t\tif(similarity_start > similarity_end) throw new IllegalArgumentException(\"similarity start must be < similarity_end\");\n\t\tif(similarity_start % 5 != 0) throw new IllegalArgumentException(\"similarity_start must be a multiple of 5\");\n\t\tif(similarity_end % 5 != 0) throw new IllegalArgumentException(\"similarity_end must be a multiple of 5\");\n\t\t\n\t\tint numDetected = 0;\n\t\tfor(int i = similarity_start; i < similarity_end; i += 5) {\n\t\t\tnumDetected += getNumDetected_type3_intra(functionality_id, i);\n\t\t}\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_type3(long functionality_id, int similarity_start, int similarity_end) throws SQLException {\n\t\treturn getNumDetected_type3_intra(functionality_id, similarity_start, similarity_end) +\n\t\t\t getNumDetected_type3_inter(functionality_id, similarity_start, similarity_end);\n\t}\n\t\n\t\n\tpublic int getNumDetected_type3_inter(int similarity_start, int similarity_end) throws SQLException {\n\t\tif(similarity_start < 0) throw new IllegalArgumentException(\"similarity_start must be >= 0.\");\n\t\tif(similarity_end > 100) throw new IllegalArgumentException(\"similarity_end must be <= 100\");\n\t\tif(similarity_start > similarity_end) throw new IllegalArgumentException(\"similarity start must be < similarity_end\");\n\t\tif(similarity_start % 5 != 0) throw new IllegalArgumentException(\"similarity_start must be a multiple of 5\");\n\t\tif(similarity_end % 5 != 0) throw new IllegalArgumentException(\"similarity_end must be a multiple of 5\");\n\t\t\n\t\tint numDetected = 0;\n\t\tfor(long fid : functionality_ids) {\n\t\t\tnumDetected += getNumDetected_type3_inter(fid, similarity_start, similarity_end);\n\t\t}\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_type3_intra(int similarity_start, int similarity_end) throws SQLException {\n\t\tif(similarity_start < 0) throw new IllegalArgumentException(\"similarity_start must be >= 0.\");\n\t\tif(similarity_end > 100) throw new IllegalArgumentException(\"similarity_end must be <= 100\");\n\t\tif(similarity_start > similarity_end) throw new IllegalArgumentException(\"similarity start must be < similarity_end\");\n\t\tif(similarity_start % 5 != 0) throw new IllegalArgumentException(\"similarity_start must be a multiple of 5\");\n\t\tif(similarity_end % 5 != 0) throw new IllegalArgumentException(\"similarity_end must be a multiple of 5\");\n\t\t\n\t\tint numDetected = 0;\n\t\tfor(long fid : functionality_ids) {\n\t\t\tnumDetected += getNumDetected_type3_intra(fid, similarity_start, similarity_end);\n\t\t}\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_type3(int similarity_start, int similarity_end) throws SQLException {\n\t\treturn getNumDetected_type3_intra(similarity_start, similarity_end) +\n\t\t\t getNumDetected_type3_inter(similarity_start, similarity_end);\n\t}\n\t\n\t\n\tpublic int getNumDetected_type3_inter(long functionality_id) throws SQLException {\n\t\tint numDetected = 0;\n\t\tfor(int i = 0; i < 100; i += 5) {\n\t\t\tnumDetected += getNumDetected_type3_inter(functionality_id, i, i+5);\n\t\t}\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_type3_intra(long functionality_id) throws SQLException {\n\t\tint numDetected = 0;\n\t\tfor(int i = 0; i < 100; i += 5) {\n\t\t\tnumDetected += getNumDetected_type3_intra(functionality_id, i, i+5);\n\t\t}\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_type3(long functionality_id) throws SQLException {\n\t\treturn getNumDetected_type3_intra(functionality_id) + \n\t\t\t getNumDetected_type3_inter(functionality_id);\n\t}\n\t\n\t\n\tpublic int getNumDetected_type3_inter() throws SQLException {\n\t\tint numDetected = 0;\n\t\tfor(int i = 0; i < 100; i = i + 5) {\n\t\t\tnumDetected += getNumDetected_type3_inter(i, i+5);\n\t\t}\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_type3_intra() throws SQLException {\n\t\tint numDetected = 0;\n\t\tfor(int i = 0; i < 100; i = i + 5) {\n\t\t\tnumDetected += getNumDetected_type3_intra(i, i+5);\n\t\t}\n\t\treturn numDetected;\n\t}\n\t\n\tpublic int getNumDetected_type3() throws SQLException {\n\t\treturn getNumDetected_type3_intra() + getNumDetected_type3_inter();\n\t}\n\t\n\t\n\tpublic double getRecall_type3_inter(long functionality_id, int similarity_start, int similarity_end) throws SQLException {\n\t\tif(similarity_start < 0) throw new IllegalArgumentException(\"similarity_start must be >= 0.\");\n\t\tif(similarity_end > 100) throw new IllegalArgumentException(\"similarity_end must be <= 100\");\n\t\tif(similarity_start > similarity_end) throw new IllegalArgumentException(\"similarity start must be < similarity_end\");\n\t\tif(similarity_start % 5 != 0) throw new IllegalArgumentException(\"similarity_start must be a multiple of 5\");\n\t\tif(similarity_end % 5 != 0) throw new IllegalArgumentException(\"similarity_end must be a multiple of 5\");\n\t\t\n\t\tint numDetected = getNumDetected_type3_inter(functionality_id, similarity_start, similarity_end);\n\t\tint numClones = getNumClones_type3_inter(functionality_id, similarity_start, similarity_end);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type3_intra(long functionality_id, int similarity_start, int similarity_end) throws SQLException {\n\t\tif(similarity_start < 0) throw new IllegalArgumentException(\"similarity_start must be >= 0.\");\n\t\tif(similarity_end > 100) throw new IllegalArgumentException(\"similarity_end must be <= 100\");\n\t\tif(similarity_start > similarity_end) throw new IllegalArgumentException(\"similarity start must be < similarity_end\");\n\t\tif(similarity_start % 5 != 0) throw new IllegalArgumentException(\"similarity_start must be a multiple of 5\");\n\t\tif(similarity_end % 5 != 0) throw new IllegalArgumentException(\"similarity_end must be a multiple of 5\");\n\t\t\n\t\tint numDetected = getNumDetected_type3_intra(functionality_id, similarity_start, similarity_end);\n\t\tint numClones = getNumClones_type3_intra(functionality_id, similarity_start, similarity_end);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type3(long functionality_id, int similarity_start, int similarity_end) throws SQLException {\n\t\tif(similarity_start < 0) throw new IllegalArgumentException(\"similarity_start must be >= 0.\");\n\t\tif(similarity_end > 100) throw new IllegalArgumentException(\"similarity_end must be <= 100\");\n\t\tif(similarity_start > similarity_end) throw new IllegalArgumentException(\"similarity start must be < similarity_end\");\n\t\tif(similarity_start % 5 != 0) throw new IllegalArgumentException(\"similarity_start must be a multiple of 5\");\n\t\tif(similarity_end % 5 != 0) throw new IllegalArgumentException(\"similarity_end must be a multiple of 5\");\n\t\t\n\t\tint numDetected = getNumDetected_type3(functionality_id, similarity_start, similarity_end);\n\t\tint numClones = getNumClones_type3 (functionality_id, similarity_start, similarity_end);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\t\n\tpublic double getRecall_type3_inter(int similarity_start, int similarity_end) throws SQLException {\n\t\tif(similarity_start < 0) throw new IllegalArgumentException(\"similarity_start must be >= 0.\");\n\t\tif(similarity_end > 100) throw new IllegalArgumentException(\"similarity_end must be <= 100\");\n\t\tif(similarity_start > similarity_end) throw new IllegalArgumentException(\"similarity start must be < similarity_end\");\n\t\tif(similarity_start % 5 != 0) throw new IllegalArgumentException(\"similarity_start must be a multiple of 5\");\n\t\tif(similarity_end % 5 != 0) throw new IllegalArgumentException(\"similarity_end must be a multiple of 5\");\n\t\t\n\t\tint numDetected = getNumDetected_type3_inter(similarity_start, similarity_end);\n\t\tint numClones = getNumClones_type3_inter(similarity_start, similarity_end);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type3_avg_inter(int similarity_start, int similarity_end) throws SQLException {\n\t\tif(similarity_start < 0) throw new IllegalArgumentException(\"similarity_start must be >= 0.\");\n\t\tif(similarity_end > 100) throw new IllegalArgumentException(\"similarity_end must be <= 100\");\n\t\tif(similarity_start > similarity_end) throw new IllegalArgumentException(\"similarity start must be < similarity_end\");\n\t\tif(similarity_start % 5 != 0) throw new IllegalArgumentException(\"similarity_start must be a multiple of 5\");\n\t\tif(similarity_end % 5 != 0) throw new IllegalArgumentException(\"similarity_end must be a multiple of 5\");\n\t\t\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = this.getRecall_type3_inter(id, similarity_start, similarity_end);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\t\n\tpublic double getRecall_type3_intra(int similarity_start, int similarity_end) throws SQLException {\n\t\tif(similarity_start < 0) throw new IllegalArgumentException(\"similarity_start must be >= 0.\");\n\t\tif(similarity_end > 100) throw new IllegalArgumentException(\"similarity_end must be <= 100\");\n\t\tif(similarity_start > similarity_end) throw new IllegalArgumentException(\"similarity start must be < similarity_end\");\n\t\tif(similarity_start % 5 != 0) throw new IllegalArgumentException(\"similarity_start must be a multiple of 5\");\n\t\tif(similarity_end % 5 != 0) throw new IllegalArgumentException(\"similarity_end must be a multiple of 5\");\n\t\t\n\t\tint numDetected = getNumDetected_type3_intra(similarity_start, similarity_end);\n\t\tint numClones = getNumClones_type3_intra(similarity_start, similarity_end);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type3_avg_intra(int similarity_start, int similarity_end) throws SQLException {\n\t\tif(similarity_start < 0) throw new IllegalArgumentException(\"similarity_start must be >= 0.\");\n\t\tif(similarity_end > 100) throw new IllegalArgumentException(\"similarity_end must be <= 100\");\n\t\tif(similarity_start > similarity_end) throw new IllegalArgumentException(\"similarity start must be < similarity_end\");\n\t\tif(similarity_start % 5 != 0) throw new IllegalArgumentException(\"similarity_start must be a multiple of 5\");\n\t\tif(similarity_end % 5 != 0) throw new IllegalArgumentException(\"similarity_end must be a multiple of 5\");\n\t\t\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = this.getRecall_type3_intra(id, similarity_start, similarity_end);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\t\n\tpublic double getRecall_type3(int similarity_start, int similarity_end) throws SQLException {\n\t\tif(similarity_start < 0) throw new IllegalArgumentException(\"similarity_start must be >= 0.\");\n\t\tif(similarity_end > 100) throw new IllegalArgumentException(\"similarity_end must be <= 100\");\n\t\tif(similarity_start > similarity_end) throw new IllegalArgumentException(\"similarity start must be < similarity_end\");\n\t\tif(similarity_start % 5 != 0) throw new IllegalArgumentException(\"similarity_start must be a multiple of 5\");\n\t\tif(similarity_end % 5 != 0) throw new IllegalArgumentException(\"similarity_end must be a multiple of 5\");\n\t\t\n\t\tint numDetected = getNumDetected_type3(similarity_start, similarity_end);\n\t\tint numClones = getNumClones_type3(similarity_start, similarity_end);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type3_avg(int similarity_start, int similarity_end) throws SQLException {\n\t\tdouble avg = 0.0;\n\t\tint num = 0;\n\t\tfor(long id : functionality_ids) {\n\t\t\tdouble recall = getRecall_type3(id, similarity_start, similarity_end);\n\t\t\tif(!Double.isNaN(recall)) {\n\t\t\t\tavg += recall;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn avg/num;\n\t}\n\t\n\t\t\n\tpublic double getRecall_type3_inter(long functionality_id) throws SQLException {\n\t\tint numDetected = getNumDetected_type3_inter(functionality_id);\n\t\tint numClones = getNumClones_type3_inter(functionality_id);\n\t\t//System.out.println(numDetected + \" \" + numClones);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type3_intra(long functionality_id) throws SQLException {\n\t\tint numDetected = getNumDetected_type3_intra(functionality_id);\n\t\tint numClones = getNumClones_type3_intra(functionality_id);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type3(long functionality_id) throws SQLException {\n\t\tint numDetected = getNumDetected_type3(functionality_id);\n\t\tint numClones = getNumClones_type3(functionality_id);\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\t\n\tpublic double getRecall_type3_inter() throws SQLException {\n\t\tint numDetected = getNumDetected_type3_inter();\n\t\tint numClones = getNumClones_type3_inter();\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type3_intra() throws SQLException {\n\t\tint numDetected = getNumDetected_type3_intra();\n\t\tint numClones = getNumClones_type3_intra();\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\tpublic double getRecall_type3() throws SQLException {\n\t\tint numDetected = getNumDetected_type3();\n\t\tint numClones = getNumClones_type3();\n\t\treturn 1.0*numDetected/numClones;\n\t}\n\t\n\t\n\tpublic CloneMatcher getMatcher() {\n\t\treturn this.matcher;\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\tpublic ToolEvaluator(Long tool_id, CloneMatcher matcher, int similarity_type,\n\t\t\t \t\t\t Integer min_size, Integer max_size, Integer min_pretty_size, Integer max_pretty_size, Integer min_tokens, Integer max_tokens,\n\t\t\t \t\t\t Integer min_judges, Integer min_confidence, boolean includeInternal) throws SQLException {\n\t\t\n\t\tthis.similarity_type = similarity_type;\n\t\tthis.tool_id = tool_id;\n\t\tthis.matcher = matcher;\n\t\tthis.min_size = min_size;\n\t\tthis.max_size = max_size;\n\t\tthis.min_pretty_size = min_pretty_size;\n\t\tthis.max_pretty_size = max_pretty_size;\n\t\tthis.min_tokens = min_tokens;\n\t\tthis.max_tokens = max_tokens;\n\t\tthis.min_judges = min_judges;\n\t\tthis.min_confidence = min_confidence;\n\t\tthis.include_internal = includeInternal;\n\t\t\n\t\tnumClones_type1_inter = new HashMap<Long,Integer>();\n\t\tnumClones_type1_intra = new HashMap<Long,Integer>();\n\t\t\n\t\tnumDetected_type1_inter = new HashMap<Long,Integer>();\n\t\tnumDetected_type1_intra = new HashMap<Long,Integer>();\n\t\t\n\t\tnumClones_type2c_inter = new HashMap<Long,Integer>();\n\t\tnumClones_type2c_intra = new HashMap<Long,Integer>();\n\t\t\n\t\tnumDetected_type2c_inter = new HashMap<Long,Integer>();\n\t\tnumDetected_type2c_intra = new HashMap<Long,Integer>();\n\t\t\n\t\tnumClones_type2b_inter = new HashMap<Long,Integer>();\n\t\tnumClones_type2b_intra = new HashMap<Long,Integer>();\n\t\t\n\t\tnumDetected_type2b_inter = new HashMap<Long,Integer>();\n\t\tnumDetected_type2b_intra = new HashMap<Long,Integer>();\n\t\t\n\t\tnumClones_type3_inter = (HashMap<Long,Integer>[]) new HashMap[20];\n\t\tnumClones_type3_intra = (HashMap<Long,Integer>[]) new HashMap[20];\n\t\t\n\t\tnumDetected_type3_inter = (HashMap<Long,Integer>[]) new HashMap[20];\n\t\tnumDetected_type3_intra = (HashMap<Long,Integer>[]) new HashMap[20];\n\t\t\n\t\tnumClones_false_inter = new HashMap<Long,Integer>();\n\t\tnumClones_false_intra = new HashMap<Long,Integer>();\n\t\t\n\t\tnumDetected_false_inter = new HashMap<Long,Integer>();\n\t\tnumDetected_false_intra = new HashMap<Long,Integer>();\n\t\t\n\t\tfor(int i = 0; i < 20; i++) {\n\t\t\tnumClones_type3_inter[i] = new HashMap<Long,Integer>();\n\t\t\tnumClones_type3_intra[i] = new HashMap<Long,Integer>();\n\t\t\tnumDetected_type3_inter[i] = new HashMap<Long,Integer>();\n\t\t\tnumDetected_type3_intra[i] = new HashMap<Long,Integer>();\n\t\t}\n\t\t\n\t\tfunctionality_ids = Functionalities.getFunctionalityIds();\n\t\tfor(long id : functionality_ids) {\n\t\t\tnumClones_type1_inter.put(id, null);\n\t\t\tnumDetected_type1_inter.put(id, null);\n\t\t\tnumClones_type2c_inter.put(id, null);\n\t\t\tnumDetected_type2c_inter.put(id, null);\n\t\t\tnumClones_type1_intra.put(id, null);\n\t\t\tnumDetected_type1_intra.put(id, null);\n\t\t\tnumClones_type2c_intra.put(id, null);\n\t\t\tnumDetected_type2c_intra.put(id, null);\n\t\t\tfor(int i = 0; i < 19; i++) {\n\t\t\t\tnumClones_type3_inter[i].put(id, null);\n\t\t\t\tnumDetected_type3_inter[i].put(id, null);\n\t\t\t\tnumClones_type3_intra[i].put(id, null);\n\t\t\t\tnumDetected_type3_intra[i].put(id, null);\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime\n\t\t\t\t* result\n\t\t\t\t+ ((functionality_ids == null) ? 0 : functionality_ids\n\t\t\t\t\t\t.hashCode());\n\t\tresult = prime * result + ((matcher == null) ? 0 : matcher.hashCode());\n\t\tresult = prime * result\n\t\t\t\t+ ((max_pretty_size == null) ? 0 : max_pretty_size.hashCode());\n\t\tresult = prime * result\n\t\t\t\t+ ((max_size == null) ? 0 : max_size.hashCode());\n\t\tresult = prime * result\n\t\t\t\t+ ((max_tokens == null) ? 0 : max_tokens.hashCode());\n\t\tresult = prime * result\n\t\t\t\t+ ((min_confidence == null) ? 0 : min_confidence.hashCode());\n\t\tresult = prime * result\n\t\t\t\t+ ((min_judges == null) ? 0 : min_judges.hashCode());\n\t\tresult = prime * result\n\t\t\t\t+ ((min_pretty_size == null) ? 0 : min_pretty_size.hashCode());\n\t\tresult = prime * result\n\t\t\t\t+ ((min_size == null) ? 0 : min_size.hashCode());\n\t\tresult = prime * result\n\t\t\t\t+ ((min_tokens == null) ? 0 : min_tokens.hashCode());\n\t\tresult = prime\n\t\t\t\t* result\n\t\t\t\t+ ((numClones_false_inter == null) ? 0 : numClones_false_inter\n\t\t\t\t\t\t.hashCode());\n\t\tresult = prime\n\t\t\t\t* result\n\t\t\t\t+ ((numClones_false_intra == null) ? 0 : numClones_false_intra\n\t\t\t\t\t\t.hashCode());\n\t\tresult = prime\n\t\t\t\t* result\n\t\t\t\t+ ((numClones_type1_inter == null) ? 0 : numClones_type1_inter\n\t\t\t\t\t\t.hashCode());\n\t\tresult = prime\n\t\t\t\t* result\n\t\t\t\t+ ((numClones_type1_intra == null) ? 0 : numClones_type1_intra\n\t\t\t\t\t\t.hashCode());\n\t\tresult = prime\n\t\t\t\t* result\n\t\t\t\t+ ((numClones_type2b_inter == null) ? 0\n\t\t\t\t\t\t: numClones_type2b_inter.hashCode());\n\t\tresult = prime\n\t\t\t\t* result\n\t\t\t\t+ ((numClones_type2b_intra == null) ? 0\n\t\t\t\t\t\t: numClones_type2b_intra.hashCode());\n\t\tresult = prime\n\t\t\t\t* result\n\t\t\t\t+ ((numClones_type2c_inter == null) ? 0\n\t\t\t\t\t\t: numClones_type2c_inter.hashCode());\n\t\tresult = prime\n\t\t\t\t* result\n\t\t\t\t+ ((numClones_type2c_intra == null) ? 0\n\t\t\t\t\t\t: numClones_type2c_intra.hashCode());\n\t\tresult = prime * result + Arrays.hashCode(numClones_type3_inter);\n\t\tresult = prime * result + Arrays.hashCode(numClones_type3_intra);\n\t\tresult = prime\n\t\t\t\t* result\n\t\t\t\t+ ((numDetected_false_inter == null) ? 0\n\t\t\t\t\t\t: numDetected_false_inter.hashCode());\n\t\tresult = prime\n\t\t\t\t* result\n\t\t\t\t+ ((numDetected_false_intra == null) ? 0\n\t\t\t\t\t\t: numDetected_false_intra.hashCode());\n\t\tresult = prime\n\t\t\t\t* result\n\t\t\t\t+ ((numDetected_type1_inter == null) ? 0\n\t\t\t\t\t\t: numDetected_type1_inter.hashCode());\n\t\tresult = prime\n\t\t\t\t* result\n\t\t\t\t+ ((numDetected_type1_intra == null) ? 0\n\t\t\t\t\t\t: numDetected_type1_intra.hashCode());\n\t\tresult = prime\n\t\t\t\t* result\n\t\t\t\t+ ((numDetected_type2b_inter == null) ? 0\n\t\t\t\t\t\t: numDetected_type2b_inter.hashCode());\n\t\tresult = prime\n\t\t\t\t* result\n\t\t\t\t+ ((numDetected_type2b_intra == null) ? 0\n\t\t\t\t\t\t: numDetected_type2b_intra.hashCode());\n\t\tresult = prime\n\t\t\t\t* result\n\t\t\t\t+ ((numDetected_type2c_inter == null) ? 0\n\t\t\t\t\t\t: numDetected_type2c_inter.hashCode());\n\t\tresult = prime\n\t\t\t\t* result\n\t\t\t\t+ ((numDetected_type2c_intra == null) ? 0\n\t\t\t\t\t\t: numDetected_type2c_intra.hashCode());\n\t\tresult = prime * result + Arrays.hashCode(numDetected_type3_inter);\n\t\tresult = prime * result + Arrays.hashCode(numDetected_type3_intra);\n\t\tresult = prime * result + similarity_type;\n\t\tresult = prime * result + ((tool_id == null) ? 0 : tool_id.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tToolEvaluator other = (ToolEvaluator) obj;\n\t\tif (functionality_ids == null) {\n\t\t\tif (other.functionality_ids != null)\n\t\t\t\treturn false;\n\t\t} else if (!functionality_ids.equals(other.functionality_ids))\n\t\t\treturn false;\n\t\tif (matcher == null) {\n\t\t\tif (other.matcher != null)\n\t\t\t\treturn false;\n\t\t} else if (!matcher.equals(other.matcher))\n\t\t\treturn false;\n\t\tif (max_pretty_size == null) {\n\t\t\tif (other.max_pretty_size != null)\n\t\t\t\treturn false;\n\t\t} else if (!max_pretty_size.equals(other.max_pretty_size))\n\t\t\treturn false;\n\t\tif (max_size == null) {\n\t\t\tif (other.max_size != null)\n\t\t\t\treturn false;\n\t\t} else if (!max_size.equals(other.max_size))\n\t\t\treturn false;\n\t\tif (max_tokens == null) {\n\t\t\tif (other.max_tokens != null)\n\t\t\t\treturn false;\n\t\t} else if (!max_tokens.equals(other.max_tokens))\n\t\t\treturn false;\n\t\tif (min_confidence == null) {\n\t\t\tif (other.min_confidence != null)\n\t\t\t\treturn false;\n\t\t} else if (!min_confidence.equals(other.min_confidence))\n\t\t\treturn false;\n\t\tif (min_judges == null) {\n\t\t\tif (other.min_judges != null)\n\t\t\t\treturn false;\n\t\t} else if (!min_judges.equals(other.min_judges))\n\t\t\treturn false;\n\t\tif (min_pretty_size == null) {\n\t\t\tif (other.min_pretty_size != null)\n\t\t\t\treturn false;\n\t\t} else if (!min_pretty_size.equals(other.min_pretty_size))\n\t\t\treturn false;\n\t\tif (min_size == null) {\n\t\t\tif (other.min_size != null)\n\t\t\t\treturn false;\n\t\t} else if (!min_size.equals(other.min_size))\n\t\t\treturn false;\n\t\tif (min_tokens == null) {\n\t\t\tif (other.min_tokens != null)\n\t\t\t\treturn false;\n\t\t} else if (!min_tokens.equals(other.min_tokens))\n\t\t\treturn false;\n\t\tif (numClones_false_inter == null) {\n\t\t\tif (other.numClones_false_inter != null)\n\t\t\t\treturn false;\n\t\t} else if (!numClones_false_inter.equals(other.numClones_false_inter))\n\t\t\treturn false;\n\t\tif (numClones_false_intra == null) {\n\t\t\tif (other.numClones_false_intra != null)\n\t\t\t\treturn false;\n\t\t} else if (!numClones_false_intra.equals(other.numClones_false_intra))\n\t\t\treturn false;\n\t\tif (numClones_type1_inter == null) {\n\t\t\tif (other.numClones_type1_inter != null)\n\t\t\t\treturn false;\n\t\t} else if (!numClones_type1_inter.equals(other.numClones_type1_inter))\n\t\t\treturn false;\n\t\tif (numClones_type1_intra == null) {\n\t\t\tif (other.numClones_type1_intra != null)\n\t\t\t\treturn false;\n\t\t} else if (!numClones_type1_intra.equals(other.numClones_type1_intra))\n\t\t\treturn false;\n\t\tif (numClones_type2b_inter == null) {\n\t\t\tif (other.numClones_type2b_inter != null)\n\t\t\t\treturn false;\n\t\t} else if (!numClones_type2b_inter.equals(other.numClones_type2b_inter))\n\t\t\treturn false;\n\t\tif (numClones_type2b_intra == null) {\n\t\t\tif (other.numClones_type2b_intra != null)\n\t\t\t\treturn false;\n\t\t} else if (!numClones_type2b_intra.equals(other.numClones_type2b_intra))\n\t\t\treturn false;\n\t\tif (numClones_type2c_inter == null) {\n\t\t\tif (other.numClones_type2c_inter != null)\n\t\t\t\treturn false;\n\t\t} else if (!numClones_type2c_inter.equals(other.numClones_type2c_inter))\n\t\t\treturn false;\n\t\tif (numClones_type2c_intra == null) {\n\t\t\tif (other.numClones_type2c_intra != null)\n\t\t\t\treturn false;\n\t\t} else if (!numClones_type2c_intra.equals(other.numClones_type2c_intra))\n\t\t\treturn false;\n\t\tif (!Arrays.equals(numClones_type3_inter, other.numClones_type3_inter))\n\t\t\treturn false;\n\t\tif (!Arrays.equals(numClones_type3_intra, other.numClones_type3_intra))\n\t\t\treturn false;\n\t\tif (numDetected_false_inter == null) {\n\t\t\tif (other.numDetected_false_inter != null)\n\t\t\t\treturn false;\n\t\t} else if (!numDetected_false_inter\n\t\t\t\t.equals(other.numDetected_false_inter))\n\t\t\treturn false;\n\t\tif (numDetected_false_intra == null) {\n\t\t\tif (other.numDetected_false_intra != null)\n\t\t\t\treturn false;\n\t\t} else if (!numDetected_false_intra\n\t\t\t\t.equals(other.numDetected_false_intra))\n\t\t\treturn false;\n\t\tif (numDetected_type1_inter == null) {\n\t\t\tif (other.numDetected_type1_inter != null)\n\t\t\t\treturn false;\n\t\t} else if (!numDetected_type1_inter\n\t\t\t\t.equals(other.numDetected_type1_inter))\n\t\t\treturn false;\n\t\tif (numDetected_type1_intra == null) {\n\t\t\tif (other.numDetected_type1_intra != null)\n\t\t\t\treturn false;\n\t\t} else if (!numDetected_type1_intra\n\t\t\t\t.equals(other.numDetected_type1_intra))\n\t\t\treturn false;\n\t\tif (numDetected_type2b_inter == null) {\n\t\t\tif (other.numDetected_type2b_inter != null)\n\t\t\t\treturn false;\n\t\t} else if (!numDetected_type2b_inter\n\t\t\t\t.equals(other.numDetected_type2b_inter))\n\t\t\treturn false;\n\t\tif (numDetected_type2b_intra == null) {\n\t\t\tif (other.numDetected_type2b_intra != null)\n\t\t\t\treturn false;\n\t\t} else if (!numDetected_type2b_intra\n\t\t\t\t.equals(other.numDetected_type2b_intra))\n\t\t\treturn false;\n\t\tif (numDetected_type2c_inter == null) {\n\t\t\tif (other.numDetected_type2c_inter != null)\n\t\t\t\treturn false;\n\t\t} else if (!numDetected_type2c_inter\n\t\t\t\t.equals(other.numDetected_type2c_inter))\n\t\t\treturn false;\n\t\tif (numDetected_type2c_intra == null) {\n\t\t\tif (other.numDetected_type2c_intra != null)\n\t\t\t\treturn false;\n\t\t} else if (!numDetected_type2c_intra\n\t\t\t\t.equals(other.numDetected_type2c_intra))\n\t\t\treturn false;\n\t\tif (!Arrays.equals(numDetected_type3_inter,\n\t\t\t\tother.numDetected_type3_inter))\n\t\t\treturn false;\n\t\tif (!Arrays.equals(numDetected_type3_intra,\n\t\t\t\tother.numDetected_type3_intra))\n\t\t\treturn false;\n\t\tif (similarity_type != other.similarity_type)\n\t\t\treturn false;\n\t\tif (tool_id == null) {\n\t\t\tif (other.tool_id != null)\n\t\t\t\treturn false;\n\t\t} else if (!tool_id.equals(other.tool_id))\n\t\t\treturn false;\n\t\treturn true;\n\t}\t\n\t\n//\tpublic static boolean exists(ToolEvaluator te, Path dir) throws SQLException {\n//\t\tPath pserialized = dir.resolve(te.getSerializedFileName());\n//\t\treturn Files.exists(pserialized);\n//\t}\n//\t\n//\tpublic static ToolEvaluator load(ToolEvaluator te, Path dir) throws FileNotFoundException, IOException, ClassNotFoundException, SQLException {\n//\t\tPath pserialized = dir.resolve(te.getSerializedFileName());\n//\t\tObjectInputStream ois = new ObjectInputStream(new FileInputStream(pserialized.toFile()));\n//\t\tToolEvaluator check = (ToolEvaluator) ois.readObject();\n//\t\tois.close();\n//\t\treturn check;\n//\t}\n//\t\n//\tpublic static void save(ToolEvaluator te, Path dir) throws FileNotFoundException, IOException, SQLException {\n//\t\tFiles.createDirectories(dir);\n//\t\tPath pserialized = dir.resolve(te.getSerializedFileName());\n//\t\tif(Files.exists(pserialized))\n//\t\t\tFiles.delete(pserialized);\n//\t\tFiles.createFile(pserialized);\n//\t\tObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(pserialized.toFile()));\n//\t\toos.writeObject(te);\n//\t\toos.close();\n//\t}\n\n\tpublic Long getTool_id() {\n\t\treturn tool_id;\n\t}\n\n\tpublic Integer getMin_size() {\n\t\treturn min_size;\n\t}\n\n\tpublic Integer getMax_size() {\n\t\treturn max_size;\n\t}\n\n\tpublic Integer getMin_pretty_size() {\n\t\treturn min_pretty_size;\n\t}\n\n\tpublic Integer getMax_pretty_size() {\n\t\treturn max_pretty_size;\n\t}\n\n\tpublic Integer getMin_tokens() {\n\t\treturn min_tokens;\n\t}\n\n\tpublic Integer getMax_tokens() {\n\t\treturn max_tokens;\n\t}\n\n\tpublic Integer getMin_judges() {\n\t\treturn min_judges;\n\t}\n\n\tpublic Integer getMin_confidence() {\n\t\treturn min_confidence;\n\t}\n\n\tpublic int getSimilarity_type() {\n\t\treturn similarity_type;\n\t}\n\n\tpublic String getSimilarity_type_string() {\n\t\tif(this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_AVG) {\n\t\t\treturn \"AVG\";\n\t\t} else if (this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_BOTH) {\n\t\t\treturn \"BOTH\";\n\t\t} else if (this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_LINE) {\n\t\t\treturn \"LINE\";\n\t\t} else if (this.similarity_type == ToolEvaluator.SIMILARITY_TYPE_TOKEN) {\n\t\t\treturn \"TOKEN\";\n\t\t} else {\n\t\t\treturn \"UNKNOWN\";\n\t\t}\n\t}\n\t\n\tpublic boolean isInclude_internal() {\n\t\treturn include_internal;\n\t}\n\n\tpublic Set<Long> getFunctionality_ids() {\n\t\treturn functionality_ids;\n\t}\n\t\n}" ]
import cloneMatchingAlgorithms.CloneMatcher; import cloneMatchingAlgorithms.CoverageMatcher; import database.Clones; import database.Tool; import database.Tools; import evaluate.ToolEvaluator; import picocli.CommandLine; import util.FixPath; import java.io.FileWriter; import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.Path; import java.util.UUID; import java.util.concurrent.Callable; import static evaluate.ToolEvaluator.*;
package tasks; @CommandLine.Command( name = "evaluateRecall", description = "Measures the recall of the clones given. Highly configureable." + "Summarizes recall per clone type, per inter vs intra-project clones, per functionality in " + "BigCloneBench and for different syntactical similarity regions in the output tool evaluation report.", mixinStandardHelpOptions = true, versionProvider = util.Version.class) public class EvaluateRecall implements Callable<Void> { @CommandLine.Spec private CommandLine.Model.CommandSpec spec; @CommandLine.Mixin private MixinOptions.OutputFile output; @CommandLine.Mixin private MixinOptions.EvaluationOptions evaluationOptions; @CommandLine.Mixin private MixinOptions.InputFile input; private Double matcher_coverage = null; @CommandLine.Option( names = {"-m", "--matcher-coverage"}, description = "Minimum coverage of clone-matcher: [0.0,1.0].", paramLabel = "double", required = true ) private void setMatcherCoverage(double matcher_coverage) { if (matcher_coverage < 0.0 && matcher_coverage > 1.0) { throw new CommandLine.ParameterException(spec.commandLine(), "Clone matcher coverage must be in range [0.0,1.0]."); } this.matcher_coverage = matcher_coverage; } public static void main(String[] args) { new CommandLine(new EvaluateRecall()).execute(args); } @Override public Void call() { // Create Temporary Tool String name = UUID.randomUUID().toString(); String desc = UUID.randomUUID().toString(); Long toolID = null; try { // Create Tool toolID = Tools.addTool(name, desc); // Import Clones System.out.println("Importing clones..."); Clones.importClones(toolID, input.input.toPath()); // Tool Evaluator CloneMatcher matcher = new CoverageMatcher(toolID, matcher_coverage, null, null);
ToolEvaluator te = new ToolEvaluator(toolID,
7
jboss-logging/jboss-logmanager
ext/src/test/java/org/jboss/logmanager/ext/PropertyConfigurationTests.java
[ "public abstract class ExtHandler extends Handler implements AutoCloseable, Flushable {\n\n private static final ErrorManager DEFAULT_ERROR_MANAGER = new OnlyOnceErrorManager();\n private static final Permission CONTROL_PERMISSION = new LoggingPermission(\"control\", null);\n\n private volatile boolean autoFlush = true;\n private volatile boolean enabled = true;\n private volatile boolean closeChildren;\n private volatile Charset charset = Charset.defaultCharset();\n\n /**\n * The sub-handlers for this handler. May only be updated using the {@link #handlersUpdater} atomic updater. The array\n * instance should not be modified (treat as immutable).\n */\n @SuppressWarnings(\"unused\")\n protected volatile Handler[] handlers;\n\n /**\n * The atomic updater for the {@link #handlers} field.\n */\n protected static final AtomicArray<ExtHandler, Handler> handlersUpdater = AtomicArray.create(AtomicReferenceFieldUpdater.newUpdater(ExtHandler.class, Handler[].class, \"handlers\"), Handler.class);\n\n /**\n * Construct a new instance.\n */\n protected ExtHandler() {\n handlersUpdater.clear(this);\n closeChildren = true;\n super.setErrorManager(DEFAULT_ERROR_MANAGER);\n }\n\n /** {@inheritDoc} */\n public void publish(final LogRecord record) {\n if (enabled && record != null && isLoggable(record)) {\n doPublish(ExtLogRecord.wrap(record));\n }\n }\n\n /**\n * Publish an {@code ExtLogRecord}.\n * <p/>\n * The logging request was made initially to a Logger object, which initialized the LogRecord and forwarded it here.\n * <p/>\n * The {@code ExtHandler} is responsible for formatting the message, when and if necessary. The formatting should\n * include localization.\n *\n * @param record the log record to publish\n */\n public void publish(final ExtLogRecord record) {\n if (enabled && record != null && isLoggable(record)) {\n doPublish(record);\n }\n }\n\n /**\n * Do the actual work of publication; the record will have been filtered already. The default implementation\n * does nothing except to flush if the {@code autoFlush} property is set to {@code true}; if this behavior is to be\n * preserved in a subclass then this method should be called after the record is physically written.\n *\n * @param record the log record to publish\n */\n protected void doPublish(final ExtLogRecord record) {\n if (autoFlush) flush();\n }\n\n /**\n * Add a sub-handler to this handler. Some handler types do not utilize sub-handlers.\n *\n * @param handler the handler to add\n *\n * @throws SecurityException if a security manager exists and if the caller does not have {@code\n * LoggingPermission(control)}\n */\n public void addHandler(Handler handler) throws SecurityException {\n checkAccess();\n if (handler == null) {\n throw new NullPointerException(\"handler is null\");\n }\n handlersUpdater.add(this, handler);\n }\n\n /**\n * Remove a sub-handler from this handler. Some handler types do not utilize sub-handlers.\n *\n * @param handler the handler to remove\n *\n * @throws SecurityException if a security manager exists and if the caller does not have {@code\n * LoggingPermission(control)}\n */\n public void removeHandler(Handler handler) throws SecurityException {\n checkAccess();\n if (handler == null) {\n return;\n }\n handlersUpdater.remove(this, handler, true);\n }\n\n /**\n * Get a copy of the sub-handlers array. Since the returned value is a copy, it may be freely modified.\n *\n * @return a copy of the sub-handlers array\n */\n public Handler[] getHandlers() {\n final Handler[] handlers = this.handlers;\n return handlers.length > 0 ? handlers.clone() : handlers;\n }\n\n /**\n * A convenience method to atomically get and clear all sub-handlers.\n *\n * @return the old sub-handler array\n *\n * @throws SecurityException if a security manager exists and if the caller does not have {@code\n * LoggingPermission(control)}\n */\n public Handler[] clearHandlers() throws SecurityException {\n checkAccess();\n final Handler[] handlers = this.handlers;\n handlersUpdater.clear(this);\n return handlers.length > 0 ? handlers.clone() : handlers;\n }\n\n /**\n * A convenience method to atomically get and replace the sub-handler array.\n *\n * @param newHandlers the new sub-handlers\n * @return the old sub-handler array\n *\n * @throws SecurityException if a security manager exists and if the caller does not have {@code\n * LoggingPermission(control)}\n */\n public Handler[] setHandlers(final Handler[] newHandlers) throws SecurityException {\n if (newHandlers == null) {\n throw new IllegalArgumentException(\"newHandlers is null\");\n }\n if (newHandlers.length == 0) {\n return clearHandlers();\n } else {\n checkAccess();\n final Handler[] handlers = handlersUpdater.getAndSet(this, newHandlers);\n return handlers.length > 0 ? handlers.clone() : handlers;\n }\n }\n\n /**\n * Determine if this handler will auto-flush.\n *\n * @return {@code true} if auto-flush is enabled\n */\n public boolean isAutoFlush() {\n return autoFlush;\n }\n\n /**\n * Change the autoflush setting for this handler.\n *\n * @param autoFlush {@code true} to automatically flush after each write; {@code false} otherwise\n *\n * @throws SecurityException if a security manager exists and if the caller does not have {@code\n * LoggingPermission(control)}\n */\n public void setAutoFlush(final boolean autoFlush) throws SecurityException {\n checkAccess();\n this.autoFlush = autoFlush;\n if (autoFlush) {\n flush();\n }\n }\n\n /**\n * Enables or disables the handler based on the value passed in.\n *\n * @param enabled {@code true} to enable the handler or {@code false} to disable the handler.\n *\n * @throws SecurityException if a security manager exists and if the caller does not have {@code\n * LoggingPermission(control)}\n */\n public final void setEnabled(final boolean enabled) throws SecurityException {\n checkAccess();\n this.enabled = enabled;\n }\n\n /**\n * Determine if the handler is enabled.\n *\n * @return {@code true} if the handler is enabled, otherwise {@code false}.\n */\n public final boolean isEnabled() {\n return enabled;\n }\n\n /**\n * Indicates whether or not children handlers should be closed when this handler is {@linkplain #close() closed}.\n *\n * @return {@code true} if the children handlers should be closed when this handler is closed, {@code false} if\n * children handlers should not be closed when this handler is closed\n */\n public boolean isCloseChildren() {\n return closeChildren;\n }\n\n /**\n * Sets whether or not children handlers should be closed when this handler is {@linkplain #close() closed}.\n *\n * @param closeChildren {@code true} if all children handlers should be closed when this handler is closed,\n * {@code false} if children handlers will <em>not</em> be closed when this handler\n * is closed\n */\n public void setCloseChildren(final boolean closeChildren) {\n checkAccess();\n this.closeChildren = closeChildren;\n }\n\n /**\n * Check access.\n *\n * @throws SecurityException if a security manager is installed and the caller does not have the {@code \"control\" LoggingPermission}\n */\n protected static void checkAccess() throws SecurityException {\n final SecurityManager sm = System.getSecurityManager();\n if (sm != null) {\n sm.checkPermission(CONTROL_PERMISSION);\n }\n }\n\n /**\n * Check access.\n *\n * @param handler the handler to check access on.\n *\n * @throws SecurityException if a security manager exists and if the caller does not have {@code\n * LoggingPermission(control)}\n */\n @Deprecated\n protected static void checkAccess(final ExtHandler handler) throws SecurityException {\n checkAccess();\n }\n\n /**\n * Flush all child handlers.\n */\n @Override\n public void flush() {\n for (Handler handler : handlers) try {\n handler.flush();\n } catch (Exception ex) {\n reportError(\"Failed to flush child handler\", ex, ErrorManager.FLUSH_FAILURE);\n } catch (Throwable ignored) {}\n }\n\n /**\n * Close all child handlers.\n */\n @Override\n public void close() throws SecurityException {\n checkAccess();\n if (closeChildren) {\n for (Handler handler : handlers)\n try {\n handler.close();\n } catch (Exception ex) {\n reportError(\"Failed to close child handler\", ex, ErrorManager.CLOSE_FAILURE);\n } catch (Throwable ignored) {\n }\n }\n }\n\n @Override\n public void setFormatter(final Formatter newFormatter) throws SecurityException {\n checkAccess();\n super.setFormatter(newFormatter);\n }\n\n @Override\n public void setFilter(final Filter newFilter) throws SecurityException {\n checkAccess();\n super.setFilter(newFilter);\n }\n\n /**\n * Set the handler's character set by name. This is roughly equivalent to calling {@link #setCharset(Charset)} with\n * the results of {@link Charset#forName(String)}.\n *\n * @param encoding the name of the encoding\n * @throws SecurityException if a security manager is installed and the caller does not have the {@code \"control\" LoggingPermission}\n * @throws UnsupportedEncodingException if no character set could be found for the encoding name\n */\n @Override\n public void setEncoding(final String encoding) throws SecurityException, UnsupportedEncodingException {\n try {\n setCharset(Charset.forName(encoding));\n } catch (IllegalArgumentException e) {\n final UnsupportedEncodingException e2 = new UnsupportedEncodingException(\"Unable to set encoding to \\\"\" + encoding + \"\\\"\");\n e2.initCause(e);\n throw e2;\n }\n }\n\n /**\n * Get the name of the {@linkplain #getCharset() handler's character set}.\n *\n * @return the handler character set name\n */\n @Override\n public String getEncoding() {\n return getCharset().name();\n }\n\n /**\n * Set the handler's character set. If not set, the handler's character set is initialized to the platform default\n * character set.\n *\n * @param charset the character set (must not be {@code null})\n * @throws SecurityException if a security manager is installed and the caller does not have the {@code \"control\" LoggingPermission}\n */\n public void setCharset(final Charset charset) throws SecurityException {\n checkAccess();\n setCharsetPrivate(charset);\n }\n\n /**\n * Set the handler's character set from within this handler. If not set, the handler's character set is initialized\n * to the platform default character set.\n *\n * @param charset the character set (must not be {@code null})\n */\n protected void setCharsetPrivate(final Charset charset) throws SecurityException {\n Objects.requireNonNull(charset, \"charset\");\n this.charset = charset;\n }\n\n /**\n * Get the handler's character set.\n *\n * @return the character set in use (not {@code null})\n */\n public Charset getCharset() {\n return charset;\n }\n\n @Override\n public void setErrorManager(final ErrorManager em) {\n checkAccess();\n super.setErrorManager(em);\n }\n\n @Override\n public void setLevel(final Level newLevel) throws SecurityException {\n checkAccess();\n super.setLevel(newLevel);\n }\n\n /**\n * Indicates whether or not the {@linkplain #getFormatter() formatter} associated with this handler or a formatter\n * from a {@linkplain #getHandlers() child handler} requires the caller to be calculated.\n * <p>\n * Calculating the caller on a {@linkplain ExtLogRecord log record} can be an expensive operation. Some handlers\n * may be required to copy some data from the log record, but may not need the caller information. If the\n * {@linkplain #getFormatter() formatter} is a {@link ExtFormatter} the\n * {@link ExtFormatter#isCallerCalculationRequired()} is used to determine if calculation of the caller is\n * required.\n * </p>\n *\n * @return {@code true} if the caller should be calculated, otherwise {@code false} if it can be skipped\n *\n * @see LogRecord#getSourceClassName()\n * @see ExtLogRecord#getSourceFileName()\n * @see ExtLogRecord#getSourceLineNumber()\n * @see LogRecord#getSourceMethodName()\n */\n @SuppressWarnings(\"WeakerAccess\")\n public boolean isCallerCalculationRequired() {\n Formatter formatter = getFormatter();\n if (formatterRequiresCallerCalculation(formatter)) {\n return true;\n } else for (Handler handler : getHandlers()) {\n if (handler instanceof ExtHandler) {\n if (((ExtHandler) handler).isCallerCalculationRequired()) {\n return true;\n }\n } else {\n formatter = handler.getFormatter();\n if (formatterRequiresCallerCalculation(formatter)) {\n return true;\n }\n }\n }\n return false;\n }\n\n private static boolean formatterRequiresCallerCalculation(final Formatter formatter) {\n return formatter != null && (!(formatter instanceof ExtFormatter) || ((ExtFormatter) formatter).isCallerCalculationRequired());\n }\n}", "public class ExtLogRecord extends LogRecord {\n\n private static final long serialVersionUID = -9174374711278052369L;\n\n /**\n * The format style to use.\n */\n public enum FormatStyle {\n\n /**\n * Format the message using the {@link java.text.MessageFormat} parameter style.\n */\n MESSAGE_FORMAT,\n /**\n * Format the message using the {@link java.util.Formatter} (also known as {@code printf()}) parameter style.\n */\n PRINTF,\n /**\n * Do not format the message; parameters are ignored.\n */\n NO_FORMAT,\n }\n\n /**\n * Construct a new instance. Grabs the current NDC immediately. MDC is deferred.\n *\n * @param level a logging level value\n * @param msg the raw non-localized logging message (may be null)\n * @param loggerClassName the name of the logger class\n */\n public ExtLogRecord(final java.util.logging.Level level, final String msg, final String loggerClassName) {\n this(level, msg, FormatStyle.MESSAGE_FORMAT, loggerClassName);\n }\n\n /**\n * Construct a new instance. Grabs the current NDC immediately. MDC is deferred.\n *\n * @param level a logging level value\n * @param msg the raw non-localized logging message (may be null)\n * @param formatStyle the parameter format style to use\n * @param loggerClassName the name of the logger class\n */\n public ExtLogRecord(final java.util.logging.Level level, final String msg, final FormatStyle formatStyle, final String loggerClassName) {\n super(level, msg);\n this.formatStyle = formatStyle == null ? FormatStyle.MESSAGE_FORMAT : formatStyle;\n this.loggerClassName = loggerClassName;\n ndc = NDC.get();\n threadName = Thread.currentThread().getName();\n hostName = HostName.getQualifiedHostName();\n processName = Process.getProcessName();\n processId = Process.getProcessId();\n }\n\n /**\n * Make a copy of a log record.\n *\n * @param original the original\n */\n public ExtLogRecord(final ExtLogRecord original) {\n super(original.getLevel(), original.getMessage());\n // LogRecord fields\n setLoggerName(original.getLoggerName());\n setMillis(original.getMillis());\n setParameters(original.getParameters());\n setResourceBundle(original.getResourceBundle());\n setResourceBundleName(original.getResourceBundleName());\n setSequenceNumber(original.getSequenceNumber());\n setThreadID(original.getThreadID());\n setThrown(original.getThrown());\n if (!original.calculateCaller) {\n setSourceClassName(original.getSourceClassName());\n setSourceMethodName(original.getSourceMethodName());\n sourceFileName = original.sourceFileName;\n sourceLineNumber = original.sourceLineNumber;\n sourceModuleName = original.sourceModuleName;\n sourceModuleVersion = original.sourceModuleVersion;\n }\n formatStyle = original.formatStyle;\n mdcCopy = original.mdcCopy;\n ndc = original.ndc;\n loggerClassName = original.loggerClassName;\n threadName = original.threadName;\n hostName = original.hostName;\n processName = original.processName;\n processId = original.processId;\n }\n\n /**\n * Wrap a JDK log record. If the target record is already an {@code ExtLogRecord}, it is simply returned. Otherwise\n * a wrapper record is created and returned.\n *\n * @param rec the original record\n * @return the wrapped record\n */\n public static ExtLogRecord wrap(LogRecord rec) {\n if (rec == null) {\n return null;\n } else if (rec instanceof ExtLogRecord) {\n return (ExtLogRecord) rec;\n } else {\n return new WrappedExtLogRecord(rec);\n }\n }\n\n private final transient String loggerClassName;\n private transient boolean calculateCaller = true;\n\n private String ndc;\n private FormatStyle formatStyle;\n private FastCopyHashMap<String, Object> mdcCopy;\n private int sourceLineNumber = -1;\n private String sourceFileName;\n private String threadName;\n private String hostName;\n private String processName;\n private long processId = -1;\n private String sourceModuleName;\n private String sourceModuleVersion;\n private Object marker;\n\n private void writeObject(ObjectOutputStream oos) throws IOException {\n copyAll();\n oos.defaultWriteObject();\n }\n\n @SuppressWarnings(\"unchecked\")\n private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {\n final ObjectInputStream.GetField fields = ois.readFields();\n ndc = (String) fields.get(\"ndc\", null);\n formatStyle = (FormatStyle) fields.get(\"formatStyle\", FormatStyle.MESSAGE_FORMAT);\n mdcCopy = (FastCopyHashMap<String, Object>) fields.get(\"mdcCopy\", new FastCopyHashMap<>());\n sourceLineNumber = fields.get(\"sourceLineNumber\", -1);\n sourceFileName = (String) fields.get(\"sourceFileName\", null);\n threadName = (String) fields.get(\"threadName\", null);\n hostName = (String) fields.get(\"hostName\", null);\n processName = (String) fields.get(\"processName\", null);\n processId = fields.get(\"processId\", -1L);\n sourceModuleName = (String) fields.get(\"sourceModuleName\", null);\n sourceModuleVersion = (String) fields.get(\"sourceModuleVersion\", null);\n marker = fields.get(\"marker\", null);\n }\n\n /**\n * Disable caller calculation for this record. If the caller has already been calculated, leave it; otherwise\n * set the caller to {@code \"unknown\"}.\n */\n public void disableCallerCalculation() {\n if (calculateCaller) {\n setUnknownCaller();\n }\n }\n\n /**\n * Copy all fields and prepare this object to be passed to another thread or to be serialized. Calling this method\n * more than once has no additional effect and will not incur extra copies.\n */\n public void copyAll() {\n copyMdc();\n calculateCaller();\n }\n\n /**\n * Copy the MDC. Call this method before passing this log record to another thread. Calling this method\n * more than once has no additional effect and will not incur extra copies.\n */\n public void copyMdc() {\n if (mdcCopy == null) {\n mdcCopy = MDC.fastCopyObject();\n }\n }\n\n /**\n * Get the value of an MDC property.\n *\n * @param key the property key\n * @return the property value\n */\n public String getMdc(String key) {\n final Map<String, Object> mdcCopy = this.mdcCopy;\n if (mdcCopy == null) {\n return MDC.get(key);\n }\n final Object value = mdcCopy.get(key);\n return value == null ? null : value.toString();\n }\n\n /**\n * Get a copy of all the MDC properties for this log record. If the MDC has not yet been copied, this method will copy it.\n *\n * @return a copy of the MDC map\n */\n public Map<String, String> getMdcCopy() {\n if (mdcCopy == null) {\n mdcCopy = MDC.fastCopyObject();\n }\n // Create a new map with string values\n final FastCopyHashMap<String, String> newMdc = new FastCopyHashMap<String, String>();\n for (Map.Entry<String, Object> entry : mdcCopy.entrySet()) {\n final String key = entry.getKey();\n final Object value = entry.getValue();\n newMdc.put(key, (value == null ? null : value.toString()));\n }\n return newMdc;\n }\n\n /**\n * Change an MDC value on this record. If the MDC has not yet been copied, this method will copy it.\n *\n * @param key the key to set\n * @param value the value to set it to\n * @return the old value, if any\n */\n public String putMdc(String key, String value) {\n copyMdc();\n final Object oldValue = mdcCopy.put(key, value);\n return oldValue == null ? null : oldValue.toString();\n }\n\n /**\n * Remove an MDC value on this record. If the MDC has not yet been copied, this method will copy it.\n *\n * @param key the key to remove\n * @return the old value, if any\n */\n public String removeMdc(String key) {\n copyMdc();\n final Object oldValue = mdcCopy.remove(key);\n return oldValue == null ? null : oldValue.toString();\n }\n\n /**\n * Create a new MDC using a copy of the source map.\n *\n * @param sourceMap the source man, must not be {@code null}\n */\n public void setMdc(Map<?, ?> sourceMap) {\n final FastCopyHashMap<String, Object> newMdc = new FastCopyHashMap<String, Object>();\n for (Map.Entry<?, ?> entry : sourceMap.entrySet()) {\n final Object key = entry.getKey();\n final Object value = entry.getValue();\n if (key != null && value != null) {\n newMdc.put(key.toString(), value);\n }\n }\n mdcCopy = newMdc;\n }\n\n /**\n * Get the NDC for this log record.\n *\n * @return the NDC\n */\n public String getNdc() {\n return ndc;\n }\n\n /**\n * Change the NDC for this log record.\n *\n * @param value the new NDC value\n */\n public void setNdc(String value) {\n ndc = value;\n }\n\n /**\n * Get the class name of the logger which created this record.\n *\n * @return the class name\n */\n public String getLoggerClassName() {\n return loggerClassName;\n }\n\n /**\n * Get the format style for the record.\n *\n * @return the format style\n */\n public FormatStyle getFormatStyle() {\n return formatStyle;\n }\n\n /**\n * Find the first stack frame below the call to the logger, and populate the log record with that information.\n */\n private void calculateCaller() {\n if (! calculateCaller) {\n return;\n }\n calculateCaller = false;\n JDKSpecific.calculateCaller(this);\n }\n\n void setUnknownCaller() {\n setSourceClassName(null);\n setSourceMethodName(null);\n setSourceLineNumber(-1);\n setSourceFileName(null);\n setSourceModuleName(null);\n setSourceModuleVersion(null);\n }\n\n /**\n * Get the source line number for this log record.\n * <p/>\n * Note that this line number is not verified and may be spoofed. This information may either have been\n * provided as part of the logging call, or it may have been inferred automatically by the logging framework. In the\n * latter case, the information may only be approximate and may in fact describe an earlier call on the stack frame.\n * May be -1 if no information could be obtained.\n *\n * @return the source line number\n */\n public int getSourceLineNumber() {\n calculateCaller();\n return sourceLineNumber;\n }\n\n /**\n * Set the source line number for this log record.\n *\n * @param sourceLineNumber the source line number\n */\n public void setSourceLineNumber(final int sourceLineNumber) {\n calculateCaller = false;\n this.sourceLineNumber = sourceLineNumber;\n }\n\n /**\n * Get the source file name for this log record.\n * <p/>\n * Note that this file name is not verified and may be spoofed. This information may either have been\n * provided as part of the logging call, or it may have been inferred automatically by the logging framework. In the\n * latter case, the information may only be approximate and may in fact describe an earlier call on the stack frame.\n * May be {@code null} if no information could be obtained.\n *\n * @return the source file name\n */\n public String getSourceFileName() {\n calculateCaller();\n return sourceFileName;\n }\n\n /**\n * Set the source file name for this log record.\n *\n * @param sourceFileName the source file name\n */\n public void setSourceFileName(final String sourceFileName) {\n calculateCaller = false;\n this.sourceFileName = sourceFileName;\n }\n\n /** {@inheritDoc} */\n public String getSourceClassName() {\n calculateCaller();\n return super.getSourceClassName();\n }\n\n /** {@inheritDoc} */\n public void setSourceClassName(final String sourceClassName) {\n calculateCaller = false;\n super.setSourceClassName(sourceClassName);\n }\n\n /** {@inheritDoc} */\n public String getSourceMethodName() {\n calculateCaller();\n return super.getSourceMethodName();\n }\n\n /** {@inheritDoc} */\n public void setSourceMethodName(final String sourceMethodName) {\n calculateCaller = false;\n super.setSourceMethodName(sourceMethodName);\n }\n\n /**\n * Get the name of the module that initiated the logging request, if known.\n *\n * @return the name of the module that initiated the logging request\n */\n public String getSourceModuleName() {\n calculateCaller();\n return sourceModuleName;\n }\n\n /**\n * Set the source module name of this record.\n *\n * @param sourceModuleName the source module name\n */\n public void setSourceModuleName(final String sourceModuleName) {\n calculateCaller = false;\n this.sourceModuleName = sourceModuleName;\n }\n\n /**\n * Get the version of the module that initiated the logging request, if known.\n *\n * @return the version of the module that initiated the logging request\n */\n public String getSourceModuleVersion() {\n calculateCaller();\n return sourceModuleVersion;\n }\n\n /**\n * Set the source module version of this record.\n *\n * @param sourceModuleVersion the source module version\n */\n public void setSourceModuleVersion(final String sourceModuleVersion) {\n calculateCaller = false;\n this.sourceModuleVersion = sourceModuleVersion;\n }\n\n /**\n * Get the fully formatted log record, with resources resolved and parameters applied.\n *\n * @return the formatted log record\n * @deprecated The formatter should normally be used to format the message contents.\n */\n @Deprecated\n public String getFormattedMessage() {\n final ResourceBundle bundle = getResourceBundle();\n String msg = getMessage();\n if (msg == null)\n return null;\n if (bundle != null) {\n try {\n msg = bundle.getString(msg);\n } catch (MissingResourceException ex) {\n // ignore\n }\n }\n final Object[] parameters = getParameters();\n if (parameters == null || parameters.length == 0) {\n return msg;\n }\n switch (formatStyle) {\n case PRINTF: {\n return String.format(msg, parameters);\n }\n case MESSAGE_FORMAT: {\n return msg.indexOf('{') >= 0 ? MessageFormat.format(msg, parameters) : msg;\n }\n }\n // should be unreachable\n return msg;\n }\n\n /**\n * Get the resource key, if any. If the log message is not localized, then the key is {@code null}.\n *\n * @return the resource key\n */\n public String getResourceKey() {\n final String msg = getMessage();\n if (msg == null) return null;\n if (getResourceBundleName() == null && getResourceBundle() == null) return null;\n return msg;\n }\n\n /**\n * Get the thread name of this logging event.\n *\n * @return the thread name\n */\n public String getThreadName() {\n return threadName;\n }\n\n /**\n * Set the thread name of this logging event.\n *\n * @param threadName the thread name\n */\n public void setThreadName(final String threadName) {\n this.threadName = threadName;\n }\n\n /**\n * Get the host name of the record, if known.\n *\n * @return the host name of the record, if known\n */\n public String getHostName() {\n return hostName;\n }\n\n /**\n * Set the host name of the record.\n *\n * @param hostName the host name of the record\n */\n public void setHostName(final String hostName) {\n this.hostName = hostName;\n }\n\n /**\n * Get the process name of the record, if known.\n *\n * @return the process name of the record, if known\n */\n public String getProcessName() {\n return processName;\n }\n\n /**\n * Set the process name of the record.\n *\n * @param processName the process name of the record\n */\n public void setProcessName(final String processName) {\n this.processName = processName;\n }\n\n /**\n * Get the process ID of the record, if known.\n *\n * @return the process ID of the record, or -1 if not known\n */\n public long getProcessId() {\n return processId;\n }\n\n /**\n * Set the process ID of the record.\n *\n * @param processId the process ID of the record\n */\n public void setProcessId(final long processId) {\n this.processId = processId;\n }\n\n /**\n * Set the raw message. Any cached formatted message is discarded. The parameter format is set to be\n * {@link java.text.MessageFormat}-style.\n *\n * @param message the new raw message\n */\n public void setMessage(final String message) {\n setMessage(message, FormatStyle.MESSAGE_FORMAT);\n }\n\n /**\n * Set the raw message. Any cached formatted message is discarded. The parameter format is set according to the\n * given argument.\n *\n * @param message the new raw message\n * @param formatStyle the format style to use\n */\n public void setMessage(final String message, final FormatStyle formatStyle) {\n this.formatStyle = formatStyle == null ? FormatStyle.MESSAGE_FORMAT : formatStyle;\n super.setMessage(message);\n }\n\n /**\n * Set the parameters to the log message. Any cached formatted message is discarded.\n *\n * @param parameters the log message parameters. (may be null)\n */\n public void setParameters(final Object[] parameters) {\n super.setParameters(parameters);\n }\n\n /**\n * Set the localization resource bundle. Any cached formatted message is discarded.\n *\n * @param bundle localization bundle (may be null)\n */\n public void setResourceBundle(final ResourceBundle bundle) {\n super.setResourceBundle(bundle);\n }\n\n /**\n * Set the localization resource bundle name. Any cached formatted message is discarded.\n *\n * @param name localization bundle name (may be null)\n */\n public void setResourceBundleName(final String name) {\n super.setResourceBundleName(name);\n }\n\n /**\n * Set the marker for this event. Markers are used mostly by SLF4J and Log4j.\n */\n public void setMarker(Object marker) {\n this.marker = marker;\n }\n\n public Object getMarker() {\n return marker;\n }\n}", "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\npublic final class LogContext implements AutoCloseable {\n private static final LogContext SYSTEM_CONTEXT = new LogContext(false, discoverDefaultInitializer());\n\n private static LogContextInitializer discoverDefaultInitializer() {\n final SecurityManager sm = System.getSecurityManager();\n if (sm != null) {\n return AccessController.doPrivileged((PrivilegedAction<LogContextInitializer>) LogContext::discoverDefaultInitializer0);\n } else {\n return discoverDefaultInitializer0();\n }\n }\n\n private static LogContextInitializer discoverDefaultInitializer0() {\n // allow exceptions to bubble up, otherwise logging won't work with no indication as to why\n final ServiceLoader<LogContextInitializer> loader = ServiceLoader.load(LogContextInitializer.class, LogContext.class.getClassLoader());\n final Iterator<LogContextInitializer> iterator = loader.iterator();\n return iterator.hasNext() ? iterator.next() : LogContextInitializer.DEFAULT;\n }\n\n static final Permission CREATE_CONTEXT_PERMISSION = new RuntimePermission(\"createLogContext\", null);\n static final Permission SET_CONTEXT_SELECTOR_PERMISSION = new RuntimePermission(\"setLogContextSelector\", null);\n static final Permission CONTROL_PERMISSION = new LoggingPermission(\"control\", null);\n\n private final LoggerNode rootLogger;\n @SuppressWarnings({ \"ThisEscapedInObjectConstruction\" })\n private final LoggingMXBean mxBean = new LoggingMXBeanImpl(this);\n private final boolean strong;\n private final LogContextInitializer initializer;\n\n /**\n * The first attachment key.\n */\n private Logger.AttachmentKey<?> attachmentKey1;\n\n /**\n * The first attachment value.\n */\n private Object attachmentValue1;\n\n /**\n * The second attachment key.\n */\n private Logger.AttachmentKey<?> attachmentKey2;\n\n /**\n * The second attachment value.\n */\n private Object attachmentValue2;\n\n /**\n * This lazy holder class is required to prevent a problem due to a LogContext instance being constructed\n * before the class init is complete.\n */\n private static final class LazyHolder {\n private static final HashMap<String, Reference<Level, Void>> INITIAL_LEVEL_MAP;\n\n private LazyHolder() {\n }\n\n private static void addStrong(Map<String, Reference<Level, Void>> map, Level level) {\n map.put(level.getName().toUpperCase(), References.create(Reference.Type.STRONG, level, null));\n }\n\n static {\n final HashMap<String, Reference<Level, Void>> map = new HashMap<String, Reference<Level, Void>>();\n addStrong(map, Level.OFF);\n addStrong(map, Level.ALL);\n addStrong(map, Level.SEVERE);\n addStrong(map, Level.WARNING);\n addStrong(map, Level.CONFIG);\n addStrong(map, Level.INFO);\n addStrong(map, Level.FINE);\n addStrong(map, Level.FINER);\n addStrong(map, Level.FINEST);\n\n addStrong(map, org.jboss.logmanager.Level.FATAL);\n addStrong(map, org.jboss.logmanager.Level.ERROR);\n addStrong(map, org.jboss.logmanager.Level.WARN);\n addStrong(map, org.jboss.logmanager.Level.INFO);\n addStrong(map, org.jboss.logmanager.Level.DEBUG);\n addStrong(map, org.jboss.logmanager.Level.TRACE);\n\n INITIAL_LEVEL_MAP = map;\n }\n }\n\n private final AtomicReference<Map<String, Reference<Level, Void>>> levelMapReference;\n // Guarded by treeLock\n private final Set<AutoCloseable> closeHandlers;\n\n /**\n * This lock is taken any time a change is made which affects multiple nodes in the hierarchy.\n */\n final Object treeLock = new Object();\n\n LogContext(final boolean strong, LogContextInitializer initializer) {\n this.strong = strong;\n this.initializer = initializer;\n levelMapReference = new AtomicReference<Map<String, Reference<Level, Void>>>(LazyHolder.INITIAL_LEVEL_MAP);\n rootLogger = new LoggerNode(this);\n closeHandlers = new LinkedHashSet<>();\n }\n\n /**\n * Create a new log context. If a security manager is installed, the caller must have the {@code \"createLogContext\"}\n * {@link RuntimePermission RuntimePermission} to invoke this method.\n *\n * @param strong {@code true} if the context should use strong references, {@code false} to use (default) weak\n * references for automatic logger GC\n * @return a new log context\n */\n public static LogContext create(boolean strong) {\n return create(strong, LogContextInitializer.DEFAULT);\n }\n\n /**\n * Create a new log context. If a security manager is installed, the caller must have the {@code \"createLogContext\"}\n * {@link RuntimePermission RuntimePermission} to invoke this method.\n *\n * @param strong {@code true} if the context should use strong references, {@code false} to use (default) weak\n * references for automatic logger GC\n * @param initializer the log context initializer to use (must not be {@code null})\n * @return a new log context\n */\n public static LogContext create(boolean strong, LogContextInitializer initializer) {\n Assert.checkNotNullParam(\"initializer\", initializer);\n final SecurityManager sm = System.getSecurityManager();\n if (sm != null) {\n sm.checkPermission(CREATE_CONTEXT_PERMISSION);\n }\n return new LogContext(strong, initializer);\n }\n\n /**\n * Create a new log context. If a security manager is installed, the caller must have the {@code \"createLogContext\"}\n * {@link RuntimePermission RuntimePermission} to invoke this method.\n *\n * @return a new log context\n */\n public static LogContext create() {\n return create(false);\n }\n\n /**\n * Create a new log context. If a security manager is installed, the caller must have the {@code \"createLogContext\"}\n * {@link RuntimePermission RuntimePermission} to invoke this method.\n *\n * @param initializer the log context initializer to use (must not be {@code null})\n * @return a new log context\n */\n public static LogContext create(LogContextInitializer initializer) {\n return create(false, initializer);\n }\n\n // Attachment mgmt\n\n /**\n * Get the attachment value for a given key, or {@code null} if there is no such attachment.\n * Log context attachments are placed on the root logger and can also be accessed there.\n *\n * @param key the key\n * @param <V> the attachment value type\n * @return the attachment, or {@code null} if there is none for this key\n */\n @SuppressWarnings(\"unchecked\")\n public <V> V getAttachment(Logger.AttachmentKey<V> key) {\n Assert.checkNotNullParam(\"key\", key);\n synchronized (this) {\n if (key == attachmentKey1) return (V) attachmentValue1;\n if (key == attachmentKey2) return (V) attachmentValue2;\n }\n return null;\n }\n\n /**\n * Attach an object to this log context under a given key.\n * A strong reference is maintained to the key and value for as long as this log context exists.\n * Log context attachments are placed on the root logger and can also be accessed there.\n *\n * @param key the attachment key\n * @param value the attachment value\n * @param <V> the attachment value type\n * @return the old attachment, if there was one\n * @throws SecurityException if a security manager exists and if the caller does not have {@code LoggingPermission(control)}\n * @throws IllegalArgumentException if the attachment cannot be added because the maximum has been reached\n */\n @SuppressWarnings(\"unchecked\")\n public <V> V attach(Logger.AttachmentKey<V> key, V value) throws SecurityException {\n checkAccess();\n Assert.checkNotNullParam(\"key\", key);\n Assert.checkNotNullParam(\"value\", value);\n V old;\n synchronized (this) {\n if (key == attachmentKey1) {\n old = (V) attachmentValue1;\n attachmentValue1 = value;\n } else if (key == attachmentKey2) {\n old = (V) attachmentValue2;\n attachmentValue2 = value;\n } else if (attachmentKey1 == null) {\n old = null;\n attachmentKey1 = key;\n attachmentValue1 = value;\n } else if (attachmentKey2 == null) {\n old = null;\n attachmentKey2 = key;\n attachmentValue2 = value;\n } else {\n throw attachmentsFull();\n }\n }\n return old;\n }\n\n /**\n * Attach an object to this log context under a given key, if such an attachment does not already exist.\n * A strong reference is maintained to the key and value for as long as this log context exists.\n * Log context attachments are placed on the root logger and can also be accessed there.\n *\n * @param key the attachment key\n * @param value the attachment value\n * @param <V> the attachment value type\n * @return the current attachment, if there is one, or {@code null} if the value was successfully attached\n * @throws SecurityException if a security manager exists and if the caller does not have {@code LoggingPermission(control)}\n * @throws IllegalArgumentException if the attachment cannot be added because the maximum has been reached\n */\n @SuppressWarnings(\"unchecked\")\n public <V> V attachIfAbsent(Logger.AttachmentKey<V> key, V value) throws SecurityException {\n checkAccess();\n Assert.checkNotNullParam(\"key\", key);\n Assert.checkNotNullParam(\"value\", value);\n V old;\n synchronized (this) {\n if (key == attachmentKey1) {\n old = (V) attachmentValue1;\n } else if (key == attachmentKey2) {\n old = (V) attachmentValue2;\n } else if (attachmentKey1 == null) {\n old = null;\n attachmentKey1 = key;\n attachmentValue1 = value;\n } else if (attachmentKey2 == null) {\n old = null;\n attachmentKey2 = key;\n attachmentValue2 = value;\n } else {\n throw attachmentsFull();\n }\n }\n return old;\n }\n\n /**\n * Remove an attachment.\n * Log context attachments are placed on the root logger and can also be accessed there.\n *\n * @param key the attachment key\n * @param <V> the attachment value type\n * @return the old value, or {@code null} if there was none\n * @throws SecurityException if a security manager exists and if the caller does not have {@code LoggingPermission(control)}\n */\n @SuppressWarnings(\"unchecked\")\n public <V> V detach(Logger.AttachmentKey<V> key) throws SecurityException {\n checkAccess();\n Assert.checkNotNullParam(\"key\", key);\n V old;\n synchronized (this) {\n if (key == attachmentKey1) {\n old = (V) attachmentValue1;\n attachmentValue1 = null;\n } else if (key == attachmentKey2) {\n old = (V) attachmentValue2;\n attachmentValue2 = null;\n } else {\n old = null;\n }\n }\n return old;\n }\n\n /**\n * Get a logger with the given name from this logging context.\n *\n * @param name the logger name\n * @return the logger instance\n * @see java.util.logging.LogManager#getLogger(String)\n */\n public Logger getLogger(String name) {\n return rootLogger.getOrCreate(name).createLogger();\n }\n\n /**\n * Get a logger with the given name from this logging context, if a logger node exists at that location.\n *\n * @param name the logger name\n * @return the logger instance, or {@code null} if no such logger node exists\n */\n public Logger getLoggerIfExists(String name) {\n final LoggerNode node = rootLogger.getIfExists(name);\n return node == null ? null : node.createLogger();\n }\n\n /**\n * Get a logger attachment for a logger name, if it exists.\n *\n * @param loggerName the logger name\n * @param key the attachment key\n * @param <V> the attachment value type\n * @return the attachment or {@code null} if the logger or the attachment does not exist\n */\n public <V> V getAttachment(String loggerName, Logger.AttachmentKey<V> key) {\n final LoggerNode node = rootLogger.getIfExists(loggerName);\n if (node == null) return null;\n return node.getAttachment(key);\n }\n\n /**\n * Get the {@code LoggingMXBean} associated with this log context.\n *\n * @return the {@code LoggingMXBean} instance\n */\n public LoggingMXBean getLoggingMXBean() {\n return mxBean;\n }\n\n /**\n * Get the level for a name.\n *\n * @param name the name\n * @return the level\n * @throws IllegalArgumentException if the name is not known\n */\n public Level getLevelForName(String name) throws IllegalArgumentException {\n if (name != null) {\n final Map<String, Reference<Level, Void>> map = levelMapReference.get();\n final Reference<Level, Void> levelRef = map.get(name);\n if (levelRef != null) {\n final Level level = levelRef.get();\n if (level != null) {\n return level;\n }\n }\n }\n throw new IllegalArgumentException(\"Unknown level \\\"\" + name + \"\\\"\");\n }\n\n /**\n * Register a level instance with this log context. The level can then be looked up by name. Only a weak\n * reference to the level instance will be kept. Any previous level registration for the given level's name\n * will be overwritten.\n *\n * @param level the level to register\n */\n public void registerLevel(Level level) {\n registerLevel(level, false);\n }\n\n /**\n * Register a level instance with this log context. The level can then be looked up by name. Any previous level\n * registration for the given level's name will be overwritten.\n *\n * @param level the level to register\n * @param strong {@code true} to strongly reference the level, or {@code false} to weakly reference it\n */\n public void registerLevel(Level level, boolean strong) {\n final SecurityManager sm = System.getSecurityManager();\n if (sm != null) {\n sm.checkPermission(CONTROL_PERMISSION);\n }\n for (;;) {\n final Map<String, Reference<Level, Void>> oldLevelMap = levelMapReference.get();\n final Map<String, Reference<Level, Void>> newLevelMap = new HashMap<>(oldLevelMap.size());\n for (Map.Entry<String, Reference<Level, Void>> entry : oldLevelMap.entrySet()) {\n final String name = entry.getKey();\n final Reference<Level, Void> levelRef = entry.getValue();\n if (levelRef.get() != null) {\n newLevelMap.put(name, levelRef);\n }\n }\n newLevelMap.put(level.getName(), References.create(strong ? Reference.Type.STRONG : Reference.Type.WEAK, level, null));\n if (levelMapReference.compareAndSet(oldLevelMap, newLevelMap)) {\n return;\n }\n }\n }\n\n /**\n * Unregister a previously registered level. Log levels that are not registered may still be used, they just will\n * not be findable by name.\n *\n * @param level the level to unregister\n */\n public void unregisterLevel(Level level) {\n final SecurityManager sm = System.getSecurityManager();\n if (sm != null) {\n sm.checkPermission(CONTROL_PERMISSION);\n }\n for (;;) {\n final Map<String, Reference<Level, Void>> oldLevelMap = levelMapReference.get();\n final Reference<Level, Void> oldRef = oldLevelMap.get(level.getName());\n if (oldRef == null || oldRef.get() != level) {\n // not registered, or the registration expired naturally\n return;\n }\n final Map<String, Reference<Level, Void>> newLevelMap = new HashMap<>(oldLevelMap.size());\n for (Map.Entry<String, Reference<Level, Void>> entry : oldLevelMap.entrySet()) {\n final String name = entry.getKey();\n final Reference<Level, Void> levelRef = entry.getValue();\n final Level oldLevel = levelRef.get();\n if (oldLevel != null && oldLevel != level) {\n newLevelMap.put(name, levelRef);\n }\n }\n newLevelMap.put(level.getName(), References.create(Reference.Type.WEAK, level, null));\n if (levelMapReference.compareAndSet(oldLevelMap, newLevelMap)) {\n return;\n }\n }\n }\n\n /**\n * Get the system log context.\n *\n * @return the system log context\n */\n public static LogContext getSystemLogContext() {\n return SYSTEM_CONTEXT;\n }\n\n /**\n * The default log context selector, which always returns the system log context.\n */\n public static final LogContextSelector DEFAULT_LOG_CONTEXT_SELECTOR = new LogContextSelector() {\n public LogContext getLogContext() {\n return SYSTEM_CONTEXT;\n }\n };\n\n private static volatile LogContextSelector logContextSelector = DEFAULT_LOG_CONTEXT_SELECTOR;\n\n /**\n * Get the currently active log context.\n *\n * @return the currently active log context\n */\n public static LogContext getLogContext() {\n return logContextSelector.getLogContext();\n }\n\n /**\n * Set a new log context selector. If a security manager is installed, the caller must have the {@code \"setLogContextSelector\"}\n * {@link RuntimePermission RuntimePermission} to invoke this method.\n *\n * @param newSelector the new selector.\n */\n public static void setLogContextSelector(LogContextSelector newSelector) {\n if (newSelector == null) {\n throw new NullPointerException(\"newSelector is null\");\n }\n final SecurityManager sm = System.getSecurityManager();\n if (sm != null) {\n sm.checkPermission(SET_CONTEXT_SELECTOR_PERMISSION);\n }\n logContextSelector = newSelector;\n }\n\n /**\n * Returns the currently set log context selector.\n *\n * @return the log context selector\n */\n public static LogContextSelector getLogContextSelector() {\n return logContextSelector;\n }\n\n @Override\n public void close() throws Exception {\n synchronized (treeLock) {\n // First we want to close all loggers\n recursivelyClose(rootLogger);\n // Next process the close handlers associated with this log context\n for (AutoCloseable handler : closeHandlers) {\n handler.close();\n }\n }\n }\n\n /**\n * Returns an enumeration of the logger names that have been created. This does not return names of loggers that\n * may have been garbage collected. Logger names added after the enumeration has been retrieved may also be added to\n * the enumeration.\n *\n * @return an enumeration of the logger names\n *\n * @see java.util.logging.LogManager#getLoggerNames()\n */\n public Enumeration<String> getLoggerNames() {\n return rootLogger.getLoggerNames();\n }\n\n /**\n * Adds a handler invoked during the {@linkplain #close() close} of this log context. The close handlers will be\n * invoked in the order they are added.\n * <p>\n * The loggers associated with this context will always be closed.\n * </p>\n *\n * @param closeHandler the close handler to use\n */\n public void addCloseHandler(final AutoCloseable closeHandler) {\n final SecurityManager sm = System.getSecurityManager();\n if (sm != null) {\n sm.checkPermission(CONTROL_PERMISSION);\n }\n synchronized (treeLock) {\n closeHandlers.add(closeHandler);\n }\n }\n\n /**\n * Gets the current close handlers associated with this log context.\n *\n * @return the current close handlers\n */\n public Set<AutoCloseable> getCloseHandlers() {\n synchronized (treeLock) {\n return new LinkedHashSet<>(closeHandlers);\n }\n }\n\n /**\n * Clears any current close handlers associated with log context, then adds the handlers to be invoked during\n * the {@linkplain #close() close} of this log context. The close handlers will be invoked in the order they are\n * added.\n * <p>\n * The loggers associated with this context will always be closed.\n * </p>\n *\n * @param closeHandlers the close handlers to use\n */\n public void setCloseHandlers(final Collection<AutoCloseable> closeHandlers) {\n final SecurityManager sm = System.getSecurityManager();\n if (sm != null) {\n sm.checkPermission(CONTROL_PERMISSION);\n }\n synchronized (treeLock) {\n this.closeHandlers.clear();\n this.closeHandlers.addAll(closeHandlers);\n }\n }\n\n private static SecurityException accessDenied() {\n return new SecurityException(\"Log context modification access denied\");\n }\n\n static void checkAccess() {\n final SecurityManager sm = System.getSecurityManager();\n if (sm != null) {\n sm.checkPermission(CONTROL_PERMISSION);\n }\n }\n\n LoggerNode getRootLoggerNode() {\n return rootLogger;\n }\n\n ConcurrentMap<String, LoggerNode> createChildMap() {\n return strong ? new CopyOnWriteMap<String, LoggerNode>() : new CopyOnWriteWeakMap<String, LoggerNode>();\n }\n\n LogContextInitializer getInitializer() {\n return initializer;\n }\n\n private void recursivelyClose(final LoggerNode loggerNode) {\n assert Thread.holdsLock(treeLock);\n for (LoggerNode child : loggerNode.getChildren()) {\n recursivelyClose(child);\n }\n loggerNode.close();\n }\n}", "public class PatternFormatter extends MultistepFormatter {\n\n private volatile String pattern;\n\n private volatile ColorMap colors;\n /**\n * Construct a new instance.\n */\n public PatternFormatter() {\n this.colors = ColorMap.DEFAULT_COLOR_MAP;\n }\n\n /**\n * Construct a new instance.\n *\n * @param pattern the initial pattern\n */\n public PatternFormatter(String pattern) {\n super(FormatStringParser.getSteps(pattern, ColorMap.DEFAULT_COLOR_MAP));\n this.colors = ColorMap.DEFAULT_COLOR_MAP;\n this.pattern = pattern;\n }\n\n /**\n * Construct a new instance.\n *\n * @param pattern the initial pattern\n * @param colors the color map to use\n */\n public PatternFormatter(String pattern, String colors) {\n ColorMap colorMap = ColorMap.create(colors);\n this.colors = colorMap;\n this.pattern = pattern;\n setSteps(FormatStringParser.getSteps(pattern, colorMap));\n }\n\n /**\n * Get the current format pattern.\n *\n * @return the pattern\n */\n public String getPattern() {\n return pattern;\n }\n\n /**\n * Set the format pattern.\n *\n * @param pattern the pattern\n */\n public void setPattern(final String pattern) {\n if (pattern == null) {\n setSteps(null);\n } else {\n setSteps(FormatStringParser.getSteps(pattern, colors));\n }\n this.pattern = pattern;\n }\n\n /**\n * Set the color map to use for log levels when %K{level} is used.\n *\n * <p>The format is level:color,level:color,...\n *\n * <p>Where level is either a numerical value or one of the following constants:</p>\n *\n * <table>\n * <tr><td>fatal</td></tr>\n * <tr><td>error</td></tr>\n * <tr><td>severe</td></tr>\n * <tr><td>warn</td></tr>\n * <tr><td>warning</td></tr>\n * <tr><td>info</td></tr>\n * <tr><td>config</td></tr>\n * <tr><td>debug</td></tr>\n * <tr><td>trace</td></tr>\n * <tr><td>fine</td></tr>\n * <tr><td>finer</td></tr>\n * <tr><td>finest</td></tr>\n * </table>\n *\n * <p>Color is one of the following constants:</p>\n *\n * <table>\n * <tr><td>clear</td></tr>\n * <tr><td>black</td></tr>\n * <tr><td>red</td></tr>\n * <tr><td>green</td></tr>\n * <tr><td>yellow</td></tr>\n * <tr><td>blue</td></tr>\n * <tr><td>magenta</td></tr>\n * <tr><td>cyan</td></tr>\n * <tr><td>white</td></tr>\n * <tr><td>brightblack</td></tr>\n * <tr><td>brightred</td></tr>\n * <tr><td>brightgreen</td></tr>\n * <tr><td>brightyellow</td></tr>\n * <tr><td>brightblue</td></tr>\n * <tr><td>brightmagenta</td></tr>\n * <tr><td>brightcyan</td></tr>\n * <tr><td>brightwhite</td></tr>\n * </table>\n *\n * @param colors a colormap expression string described above\n */\n public void setColors(String colors) {\n ColorMap colorMap = ColorMap.create(colors);\n this.colors = colorMap;\n if (pattern != null) {\n setSteps(FormatStringParser.getSteps(pattern, colorMap));\n }\n }\n\n public String getColors() {\n return this.colors.toString();\n }\n}", "public class ConsoleHandler extends OutputStreamHandler {\n private static final OutputStream out = System.out;\n private static final OutputStream err = System.err;\n\n /**\n * The target stream type.\n */\n public enum Target {\n\n /**\n * The target for {@link System#out}.\n */\n SYSTEM_OUT,\n /**\n * The target for {@link System#err}.\n */\n SYSTEM_ERR,\n /**\n * The target for {@link System#console()}.\n */\n CONSOLE,\n }\n\n private static final PrintWriter console;\n\n private final ErrorManager localErrorManager = new HandlerErrorManager(this);\n\n static {\n final Console con = System.console();\n console = con == null ? null : con.writer();\n }\n\n /**\n * Construct a new instance.\n */\n public ConsoleHandler() {\n this(Formatters.nullFormatter());\n }\n\n /**\n * Construct a new instance.\n *\n * @param formatter the formatter to use\n */\n public ConsoleHandler(final Formatter formatter) {\n this(console == null ? Target.SYSTEM_OUT : Target.CONSOLE, formatter);\n }\n\n /**\n * Construct a new instance.\n *\n * @param target the target to write to, or {@code null} to start with an uninitialized target\n */\n public ConsoleHandler(final Target target) {\n this(target, Formatters.nullFormatter());\n }\n\n /**\n * Construct a new instance.\n *\n * @param target the target to write to, or {@code null} to start with an uninitialized target\n * @param formatter the formatter to use\n */\n public ConsoleHandler(final Target target, final Formatter formatter) {\n super(formatter);\n switch (target) {\n case SYSTEM_OUT: setOutputStream(wrap(out)); break;\n case SYSTEM_ERR: setOutputStream(wrap(err)); break;\n case CONSOLE: setWriter(wrap(console)); break;\n default: throw new IllegalArgumentException();\n }\n }\n\n /**\n * Set the target for this console handler.\n *\n * @param target the target to write to, or {@code null} to clear the target\n */\n public void setTarget(Target target) {\n final Target t = (target == null ? console == null ? Target.SYSTEM_OUT : Target.CONSOLE : target);\n switch (t) {\n case SYSTEM_OUT: setOutputStream(wrap(out)); break;\n case SYSTEM_ERR: setOutputStream(wrap(err)); break;\n case CONSOLE: setWriter(wrap(console)); break;\n default: throw new IllegalArgumentException();\n }\n }\n\n public void setErrorManager(final ErrorManager em) {\n if (em == localErrorManager) {\n // ignore to avoid loops\n super.setErrorManager(new ErrorManager());\n return;\n }\n super.setErrorManager(em);\n }\n\n /**\n * Get the local error manager. This is an error manager that will publish errors to this console handler.\n * The console handler itself should not use this error manager.\n *\n * @return the local error manager\n */\n public ErrorManager getLocalErrorManager() {\n return localErrorManager;\n }\n\n private static OutputStream wrap(final OutputStream outputStream) {\n return outputStream == null ?\n null :\n outputStream instanceof UncloseableOutputStream ?\n outputStream :\n new UncloseableOutputStream(outputStream);\n }\n\n private static Writer wrap(final Writer writer) {\n return writer == null ?\n null :\n writer instanceof UncloseableWriter ?\n writer :\n new UncloseableWriter(writer);\n }\n\n /** {@inheritDoc} */\n public void setOutputStream(final OutputStream outputStream) {\n super.setOutputStream(wrap(outputStream));\n }\n}" ]
import java.io.PrintWriter; import java.io.Reader; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Properties; import java.util.logging.ErrorManager; import java.util.logging.Filter; import java.util.logging.Formatter; import java.util.logging.Handler; import java.util.logging.LogRecord; import java.util.logging.Logger; import org.jboss.logmanager.ExtHandler; import org.jboss.logmanager.ExtLogRecord; import org.jboss.logmanager.Level; import org.jboss.logmanager.LogContext; import org.jboss.logmanager.formatters.PatternFormatter; import org.jboss.logmanager.handlers.ConsoleHandler; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test;
/* * JBoss, Home of Professional Open Source. * * Copyright 2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logmanager.ext; /** * @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a> */ public class PropertyConfigurationTests { private static final String DEFAULT_PATTERN = "%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%e%n";
private LogContext logContext;
2
NanYoMy/mybatis-generator
src/main/java/org/mybatis/generator/codegen/ibatis2/dao/elements/DeleteByExampleMethodGenerator.java
[ "public class FullyQualifiedJavaType implements\n Comparable<FullyQualifiedJavaType> {\n private static final String JAVA_LANG = \"java.lang\"; //$NON-NLS-1$\n private static FullyQualifiedJavaType intInstance = null;\n private static FullyQualifiedJavaType stringInstance = null;\n private static FullyQualifiedJavaType booleanPrimitiveInstance = null;\n private static FullyQualifiedJavaType objectInstance = null;\n private static FullyQualifiedJavaType dateInstance = null;\n private static FullyQualifiedJavaType criteriaInstance = null;\n private static FullyQualifiedJavaType generatedCriteriaInstance = null;\n\n /**\n * The short name without any generic arguments\n */\n private String baseShortName;\n\n /**\n * The fully qualified name without any generic arguments\n */\n private String baseQualifiedName;\n\n private boolean explicitlyImported;\n private String packageName;\n private boolean primitive;\n private PrimitiveTypeWrapper primitiveTypeWrapper;\n private List<FullyQualifiedJavaType> typeArguments;\n\n // the following three values are used for dealing with wildcard types\n private boolean wildcardType;\n private boolean boundedWildcard;\n private boolean extendsBoundedWildcard;\n\n /**\n * Use this constructor to construct a generic type with the specified type\n * parameters\n * \n * @param fullTypeSpecification\n */\n public FullyQualifiedJavaType(String fullTypeSpecification) {\n super();\n typeArguments = new ArrayList<FullyQualifiedJavaType>();\n parse(fullTypeSpecification);\n }\n\n /**\n * @return Returns the explicitlyImported.\n */\n public boolean isExplicitlyImported() {\n return explicitlyImported;\n }\n\n /**\n * This method returns the fully qualified name - including any generic type\n * parameters\n * \n * @return Returns the fullyQualifiedName.\n */\n public String getFullyQualifiedName() {\n StringBuilder sb = new StringBuilder();\n if (wildcardType) {\n sb.append('?');\n if (boundedWildcard) {\n if (extendsBoundedWildcard) {\n sb.append(\" extends \"); //$NON-NLS-1$\n } else {\n sb.append(\" super \"); //$NON-NLS-1$\n }\n\n sb.append(baseQualifiedName);\n }\n } else {\n sb.append(baseQualifiedName);\n }\n\n if (typeArguments.size() > 0) {\n boolean first = true;\n sb.append('<');\n for (FullyQualifiedJavaType fqjt : typeArguments) {\n if (first) {\n first = false;\n } else {\n sb.append(\", \"); //$NON-NLS-1$\n }\n sb.append(fqjt.getFullyQualifiedName());\n\n }\n sb.append('>');\n }\n\n return sb.toString();\n }\n\n /**\n * Returns a list of Strings that are the fully qualified names of this\n * type, and any generic type argument associated with this type.\n */\n public List<String> getImportList() {\n List<String> answer = new ArrayList<String>();\n if (isExplicitlyImported()) {\n int index = baseShortName.indexOf('.');\n if (index == -1) {\n answer.add(baseQualifiedName);\n } else {\n // an inner class is specified, only import the top\n // level class\n StringBuilder sb = new StringBuilder();\n sb.append(packageName);\n sb.append('.');\n sb.append(baseShortName.substring(0, index));\n answer.add(sb.toString());\n }\n }\n\n for (FullyQualifiedJavaType fqjt : typeArguments) {\n answer.addAll(fqjt.getImportList());\n }\n\n return answer;\n }\n\n /**\n * @return Returns the packageName.\n */\n public String getPackageName() {\n return packageName;\n }\n\n /**\n * @return Returns the shortName - including any type arguments.\n */\n public String getShortName() {\n StringBuilder sb = new StringBuilder();\n if (wildcardType) {\n sb.append('?');\n if (boundedWildcard) {\n if (extendsBoundedWildcard) {\n sb.append(\" extends \"); //$NON-NLS-1$\n } else {\n sb.append(\" super \"); //$NON-NLS-1$\n }\n\n sb.append(baseShortName);\n }\n } else {\n sb.append(baseShortName);\n }\n\n if (typeArguments.size() > 0) {\n boolean first = true;\n sb.append('<');\n for (FullyQualifiedJavaType fqjt : typeArguments) {\n if (first) {\n first = false;\n } else {\n sb.append(\", \"); //$NON-NLS-1$\n }\n sb.append(fqjt.getShortName());\n\n }\n sb.append('>');\n }\n\n return sb.toString();\n }\n\n /*\n * (non-Javadoc)\n * \n * @see java.lang.Object#equals(java.lang.Object)\n */\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n\n if (!(obj instanceof FullyQualifiedJavaType)) {\n return false;\n }\n\n FullyQualifiedJavaType other = (FullyQualifiedJavaType) obj;\n\n return getFullyQualifiedName().equals(other.getFullyQualifiedName());\n }\n\n /*\n * (non-Javadoc)\n * \n * @see java.lang.Object#hashCode()\n */\n @Override\n public int hashCode() {\n return getFullyQualifiedName().hashCode();\n }\n\n /*\n * (non-Javadoc)\n * \n * @see java.lang.Object#toString()\n */\n @Override\n public String toString() {\n return getFullyQualifiedName();\n }\n\n /**\n * @return Returns the primitive.\n */\n public boolean isPrimitive() {\n return primitive;\n }\n\n /**\n * @return Returns the wrapperClass.\n */\n public PrimitiveTypeWrapper getPrimitiveTypeWrapper() {\n return primitiveTypeWrapper;\n }\n\n public static final FullyQualifiedJavaType getIntInstance() {\n if (intInstance == null) {\n intInstance = new FullyQualifiedJavaType(\"int\"); //$NON-NLS-1$\n }\n\n return intInstance;\n }\n\n public static final FullyQualifiedJavaType getNewMapInstance() {\n // always return a new instance because the type may be parameterized\n return new FullyQualifiedJavaType(\"java.util.Map\"); //$NON-NLS-1$\n }\n\n public static final FullyQualifiedJavaType getNewListInstance() {\n // always return a new instance because the type may be parameterized\n return new FullyQualifiedJavaType(\"java.util.List\"); //$NON-NLS-1$\n }\n\n public static final FullyQualifiedJavaType getNewHashMapInstance() {\n // always return a new instance because the type may be parameterized\n return new FullyQualifiedJavaType(\"java.util.HashMap\"); //$NON-NLS-1$\n }\n\n public static final FullyQualifiedJavaType getNewArrayListInstance() {\n // always return a new instance because the type may be parameterized\n return new FullyQualifiedJavaType(\"java.util.ArrayList\"); //$NON-NLS-1$\n }\n\n public static final FullyQualifiedJavaType getNewIteratorInstance() {\n // always return a new instance because the type may be parameterized\n return new FullyQualifiedJavaType(\"java.util.Iterator\"); //$NON-NLS-1$\n }\n\n public static final FullyQualifiedJavaType getStringInstance() {\n if (stringInstance == null) {\n stringInstance = new FullyQualifiedJavaType(\"java.lang.String\"); //$NON-NLS-1$\n }\n\n return stringInstance;\n }\n\n public static final FullyQualifiedJavaType getBooleanPrimitiveInstance() {\n if (booleanPrimitiveInstance == null) {\n booleanPrimitiveInstance = new FullyQualifiedJavaType(\"boolean\"); //$NON-NLS-1$\n }\n\n return booleanPrimitiveInstance;\n }\n\n public static final FullyQualifiedJavaType getObjectInstance() {\n if (objectInstance == null) {\n objectInstance = new FullyQualifiedJavaType(\"java.lang.Object\"); //$NON-NLS-1$\n }\n\n return objectInstance;\n }\n\n public static final FullyQualifiedJavaType getDateInstance() {\n if (dateInstance == null) {\n dateInstance = new FullyQualifiedJavaType(\"java.util.Date\"); //$NON-NLS-1$\n }\n\n return dateInstance;\n }\n\n public static final FullyQualifiedJavaType getCriteriaInstance() {\n if (criteriaInstance == null) {\n criteriaInstance = new FullyQualifiedJavaType(\"Criteria\"); //$NON-NLS-1$\n }\n\n return criteriaInstance;\n }\n\n public static final FullyQualifiedJavaType getGeneratedCriteriaInstance() {\n if (generatedCriteriaInstance == null) {\n generatedCriteriaInstance = new FullyQualifiedJavaType(\n \"GeneratedCriteria\"); //$NON-NLS-1$\n }\n\n return generatedCriteriaInstance;\n }\n\n /*\n * (non-Javadoc)\n * \n * @see java.lang.Comparable#compareTo(java.lang.Object)\n */\n public int compareTo(FullyQualifiedJavaType other) {\n return getFullyQualifiedName().compareTo(other.getFullyQualifiedName());\n }\n\n public void addTypeArgument(FullyQualifiedJavaType type) {\n typeArguments.add(type);\n }\n\n private void parse(String fullTypeSpecification) {\n String spec = fullTypeSpecification.trim();\n\n if (spec.startsWith(\"?\")) { //$NON-NLS-1$\n wildcardType = true;\n spec = spec.substring(1).trim();\n if (spec.startsWith(\"extends \")) { //$NON-NLS-1$\n boundedWildcard = true;\n extendsBoundedWildcard = true;\n spec = spec.substring(8);\n } else if (spec.startsWith(\"super \")) { //$NON-NLS-1$\n boundedWildcard = true;\n extendsBoundedWildcard = false;\n spec = spec.substring(6);\n } else {\n boundedWildcard = false;\n }\n parse(spec);\n } else {\n int index = fullTypeSpecification.indexOf('<');\n if (index == -1) {\n simpleParse(fullTypeSpecification);\n } else {\n simpleParse(fullTypeSpecification.substring(0, index));\n genericParse(fullTypeSpecification.substring(index));\n }\n }\n }\n\n private void simpleParse(String typeSpecification) {\n baseQualifiedName = typeSpecification.trim();\n if (baseQualifiedName.contains(\".\")) { //$NON-NLS-1$\n packageName = getPackage(baseQualifiedName);\n baseShortName = baseQualifiedName\n .substring(packageName.length() + 1);\n int index = baseShortName.lastIndexOf('.');\n if (index != -1) {\n baseShortName = baseShortName.substring(index + 1);\n }\n \n if (JAVA_LANG.equals(packageName)) { //$NON-NLS-1$\n explicitlyImported = false;\n } else {\n explicitlyImported = true;\n }\n } else {\n baseShortName = baseQualifiedName;\n explicitlyImported = false;\n packageName = \"\"; //$NON-NLS-1$\n\n if (\"byte\".equals(baseQualifiedName)) { //$NON-NLS-1$\n primitive = true;\n primitiveTypeWrapper = PrimitiveTypeWrapper.getByteInstance();\n } else if (\"short\".equals(baseQualifiedName)) { //$NON-NLS-1$\n primitive = true;\n primitiveTypeWrapper = PrimitiveTypeWrapper.getShortInstance();\n } else if (\"int\".equals(baseQualifiedName)) { //$NON-NLS-1$\n primitive = true;\n primitiveTypeWrapper = PrimitiveTypeWrapper\n .getIntegerInstance();\n } else if (\"long\".equals(baseQualifiedName)) { //$NON-NLS-1$\n primitive = true;\n primitiveTypeWrapper = PrimitiveTypeWrapper.getLongInstance();\n } else if (\"char\".equals(baseQualifiedName)) { //$NON-NLS-1$\n primitive = true;\n primitiveTypeWrapper = PrimitiveTypeWrapper\n .getCharacterInstance();\n } else if (\"float\".equals(baseQualifiedName)) { //$NON-NLS-1$\n primitive = true;\n primitiveTypeWrapper = PrimitiveTypeWrapper.getFloatInstance();\n } else if (\"double\".equals(baseQualifiedName)) { //$NON-NLS-1$\n primitive = true;\n primitiveTypeWrapper = PrimitiveTypeWrapper.getDoubleInstance();\n } else if (\"boolean\".equals(baseQualifiedName)) { //$NON-NLS-1$\n primitive = true;\n primitiveTypeWrapper = PrimitiveTypeWrapper\n .getBooleanInstance();\n } else {\n primitive = false;\n primitiveTypeWrapper = null;\n }\n }\n }\n\n private void genericParse(String genericSpecification) {\n int lastIndex = genericSpecification.lastIndexOf('>');\n if (lastIndex == -1) {\n throw new RuntimeException(getString(\n \"RuntimeError.22\", genericSpecification)); //$NON-NLS-1$\n }\n String argumentString = genericSpecification.substring(1, lastIndex);\n // need to find \",\" outside of a <> bounds\n StringTokenizer st = new StringTokenizer(argumentString, \",<>\", true); //$NON-NLS-1$\n int openCount = 0;\n StringBuilder sb = new StringBuilder();\n while (st.hasMoreTokens()) {\n String token = st.nextToken();\n if (\"<\".equals(token)) { //$NON-NLS-1$\n sb.append(token);\n openCount++;\n } else if (\">\".equals(token)) { //$NON-NLS-1$\n sb.append(token);\n openCount--;\n } else if (\",\".equals(token)) { //$NON-NLS-1$\n if (openCount == 0) {\n typeArguments\n .add(new FullyQualifiedJavaType(sb.toString()));\n sb.setLength(0);\n } else {\n sb.append(token);\n }\n } else {\n sb.append(token);\n }\n }\n\n if (openCount != 0) {\n throw new RuntimeException(getString(\n \"RuntimeError.22\", genericSpecification)); //$NON-NLS-1$\n }\n\n String finalType = sb.toString();\n if (stringHasValue(finalType)) {\n typeArguments.add(new FullyQualifiedJavaType(finalType));\n }\n }\n\n /**\n * Returns the package name of a fully qualified type.\n * \n * This method calculates the package as the part of the fully\n * qualified name up to, but not including, the last element. Therefore,\n * it does not support fully qualified inner classes.\n * Not totally fool proof, but correct in most instances.\n * \n * @param baseQualifiedName\n * @return\n */\n private static String getPackage(String baseQualifiedName) {\n int index = baseQualifiedName.lastIndexOf('.');\n return baseQualifiedName.substring(0, index);\n }\n}", "public class Interface extends JavaElement implements CompilationUnit {\n private Set<FullyQualifiedJavaType> importedTypes;\n \n private Set<String> staticImports;\n\n private FullyQualifiedJavaType type;\n\n private Set<FullyQualifiedJavaType> superInterfaceTypes;\n\n private List<Method> methods;\n\n private List<String> fileCommentLines;\n\n /**\n * \n */\n public Interface(FullyQualifiedJavaType type) {\n super();\n this.type = type;\n superInterfaceTypes = new LinkedHashSet<FullyQualifiedJavaType>();\n methods = new ArrayList<Method>();\n importedTypes = new TreeSet<FullyQualifiedJavaType>();\n fileCommentLines = new ArrayList<String>();\n staticImports = new TreeSet<String>();\n }\n\n public Interface(String type) {\n this(new FullyQualifiedJavaType(type));\n }\n\n public Set<FullyQualifiedJavaType> getImportedTypes() {\n return Collections.unmodifiableSet(importedTypes);\n }\n\n public void addImportedType(FullyQualifiedJavaType importedType) {\n if (importedType.isExplicitlyImported()\n && !importedType.getPackageName().equals(type.getPackageName())) {\n importedTypes.add(importedType);\n }\n }\n\n public String getFormattedContent() {\n StringBuilder sb = new StringBuilder();\n\n for (String commentLine : fileCommentLines) {\n sb.append(commentLine);\n newLine(sb);\n }\n\n if (stringHasValue(getType().getPackageName())) {\n sb.append(\"package \"); //$NON-NLS-1$\n sb.append(getType().getPackageName());\n sb.append(';');\n newLine(sb);\n newLine(sb);\n }\n\n for (String staticImport : staticImports) {\n sb.append(\"import static \"); //$NON-NLS-1$\n sb.append(staticImport);\n sb.append(';');\n newLine(sb);\n }\n \n if (staticImports.size() > 0) {\n newLine(sb);\n }\n \n Set<String> importStrings = calculateImports(importedTypes);\n for (String importString : importStrings) {\n sb.append(importString);\n newLine(sb);\n }\n\n if (importStrings.size() > 0) {\n newLine(sb);\n }\n\n int indentLevel = 0;\n\n addFormattedJavadoc(sb, indentLevel);\n addFormattedAnnotations(sb, indentLevel);\n\n sb.append(getVisibility().getValue());\n\n if (isStatic()) {\n sb.append(\"static \"); //$NON-NLS-1$\n }\n\n if (isFinal()) {\n sb.append(\"final \"); //$NON-NLS-1$\n }\n\n sb.append(\"interface \"); //$NON-NLS-1$\n sb.append(getType().getShortName());\n\n if (getSuperInterfaceTypes().size() > 0) {\n sb.append(\" extends \"); //$NON-NLS-1$\n\n boolean comma = false;\n for (FullyQualifiedJavaType fqjt : getSuperInterfaceTypes()) {\n if (comma) {\n sb.append(\", \"); //$NON-NLS-1$\n } else {\n comma = true;\n }\n\n sb.append(fqjt.getShortName());\n }\n }\n\n sb.append(\" {\"); //$NON-NLS-1$\n indentLevel++;\n\n Iterator<Method> mtdIter = getMethods().iterator();\n while (mtdIter.hasNext()) {\n newLine(sb);\n Method method = mtdIter.next();\n sb.append(method.getFormattedContent(indentLevel, true));\n if (mtdIter.hasNext()) {\n newLine(sb);\n }\n }\n\n indentLevel--;\n newLine(sb);\n javaIndent(sb, indentLevel);\n sb.append('}');\n\n return sb.toString();\n }\n\n public void addSuperInterface(FullyQualifiedJavaType superInterface) {\n superInterfaceTypes.add(superInterface);\n }\n\n /**\n * @return Returns the methods.\n */\n public List<Method> getMethods() {\n return methods;\n }\n\n public void addMethod(Method method) {\n methods.add(method);\n }\n\n /**\n * @return Returns the type.\n */\n public FullyQualifiedJavaType getType() {\n return type;\n }\n\n public FullyQualifiedJavaType getSuperClass() {\n // interfaces do not have superclasses\n return null;\n }\n\n public Set<FullyQualifiedJavaType> getSuperInterfaceTypes() {\n return superInterfaceTypes;\n }\n\n public boolean isJavaInterface() {\n return true;\n }\n\n public boolean isJavaEnumeration() {\n return false;\n }\n\n public void addFileCommentLine(String commentLine) {\n fileCommentLines.add(commentLine);\n }\n\n public List<String> getFileCommentLines() {\n return fileCommentLines;\n }\n\n public void addImportedTypes(Set<FullyQualifiedJavaType> importedTypes) {\n this.importedTypes.addAll(importedTypes);\n }\n\n public Set<String> getStaticImports() {\n return staticImports;\n }\n\n public void addStaticImport(String staticImport) {\n staticImports.add(staticImport);\n }\n\n public void addStaticImports(Set<String> staticImports) {\n this.staticImports.addAll(staticImports);\n }\n}", "public class Method extends JavaElement {\n\n private List<String> bodyLines;\n\n private boolean constructor;\n\n private FullyQualifiedJavaType returnType;\n\n private String name;\n\n private List<Parameter> parameters;\n\n private List<FullyQualifiedJavaType> exceptions;\n \n private boolean isSynchronized;\n \n private boolean isNative;\n\n /**\n * \n */\n public Method() {\n // use a default name to avoid malformed code\n this(\"bar\"); //$NON-NLS-1$\n }\n \n public Method(String name) {\n super();\n bodyLines = new ArrayList<String>();\n parameters = new ArrayList<Parameter>();\n exceptions = new ArrayList<FullyQualifiedJavaType>();\n this.name = name;\n }\n \n /**\n * Copy constructor. Not a truly deep copy, but close enough\n * for most purposes.\n * \n * @param original\n */\n public Method(Method original) {\n super(original);\n bodyLines = new ArrayList<String>();\n parameters = new ArrayList<Parameter>();\n exceptions = new ArrayList<FullyQualifiedJavaType>();\n this.bodyLines.addAll(original.bodyLines);\n this.constructor = original.constructor;\n this.exceptions.addAll(original.exceptions);\n this.name = original.name;\n this.parameters.addAll(original.parameters);\n this.returnType = original.returnType;\n this.isNative = original.isNative;\n this.isSynchronized = original.isSynchronized;\n }\n\n /**\n * @return Returns the bodyLines.\n */\n public List<String> getBodyLines() {\n return bodyLines;\n }\n\n public void addBodyLine(String line) {\n bodyLines.add(line);\n }\n\n public void addBodyLine(int index, String line) {\n bodyLines.add(index, line);\n }\n\n public void addBodyLines(Collection<String> lines) {\n bodyLines.addAll(lines);\n }\n\n public void addBodyLines(int index, Collection<String> lines) {\n bodyLines.addAll(index, lines);\n }\n\n public String getFormattedContent(int indentLevel, boolean interfaceMethod) {\n StringBuilder sb = new StringBuilder();\n\n addFormattedJavadoc(sb, indentLevel);\n addFormattedAnnotations(sb, indentLevel);\n\n OutputUtilities.javaIndent(sb, indentLevel);\n\n if (!interfaceMethod) {\n sb.append(getVisibility().getValue());\n\n if (isStatic()) {\n sb.append(\"static \"); //$NON-NLS-1$\n }\n\n if (isFinal()) {\n sb.append(\"final \"); //$NON-NLS-1$\n }\n \n if (isSynchronized()) {\n sb.append(\"synchronized \"); //$NON-NLS-1$\n }\n \n if (isNative()) {\n sb.append(\"native \"); //$NON-NLS-1$\n } else if (bodyLines.size() == 0) {\n sb.append(\"abstract \"); //$NON-NLS-1$\n }\n }\n\n if (!constructor) {\n if (getReturnType() == null) {\n sb.append(\"void\"); //$NON-NLS-1$\n } else {\n sb.append(getReturnType().getShortName());\n }\n sb.append(' ');\n }\n\n sb.append(getName());\n sb.append('(');\n\n boolean comma = false;\n for (Parameter parameter : getParameters()) {\n if (comma) {\n sb.append(\", \"); //$NON-NLS-1$\n } else {\n comma = true;\n }\n\n sb.append(parameter.getFormattedContent());\n }\n\n sb.append(')');\n\n if (getExceptions().size() > 0) {\n sb.append(\" throws \"); //$NON-NLS-1$\n comma = false;\n for (FullyQualifiedJavaType fqjt : getExceptions()) {\n if (comma) {\n sb.append(\", \"); //$NON-NLS-1$\n } else {\n comma = true;\n }\n\n sb.append(fqjt.getShortName());\n }\n }\n\n // if no body lines, then this is an abstract method\n if (bodyLines.size() == 0 || isNative()) {\n sb.append(';');\n } else {\n sb.append(\" {\"); //$NON-NLS-1$\n indentLevel++;\n\n ListIterator<String> listIter = bodyLines.listIterator();\n while (listIter.hasNext()) {\n String line = listIter.next();\n if (line.startsWith(\"}\")) { //$NON-NLS-1$\n indentLevel--;\n }\n\n OutputUtilities.newLine(sb);\n OutputUtilities.javaIndent(sb, indentLevel);\n sb.append(line);\n\n if ((line.endsWith(\"{\") && !line.startsWith(\"switch\")) //$NON-NLS-1$ //$NON-NLS-2$\n || line.endsWith(\":\")) { //$NON-NLS-1$\n indentLevel++;\n }\n\n if (line.startsWith(\"break\")) { //$NON-NLS-1$\n // if the next line is '}', then don't outdent\n if (listIter.hasNext()) {\n String nextLine = listIter.next();\n if (nextLine.startsWith(\"}\")) { //$NON-NLS-1$\n indentLevel++;\n }\n\n // set back to the previous element\n listIter.previous();\n }\n indentLevel--;\n }\n }\n\n indentLevel--;\n OutputUtilities.newLine(sb);\n OutputUtilities.javaIndent(sb, indentLevel);\n sb.append('}');\n }\n\n return sb.toString();\n }\n\n /**\n * @return Returns the constructor.\n */\n public boolean isConstructor() {\n return constructor;\n }\n\n /**\n * @param constructor\n * The constructor to set.\n */\n public void setConstructor(boolean constructor) {\n this.constructor = constructor;\n }\n\n /**\n * @return Returns the name.\n */\n public String getName() {\n return name;\n }\n\n /**\n * @param name\n * The name to set.\n */\n public void setName(String name) {\n this.name = name;\n }\n\n public List<Parameter> getParameters() {\n return parameters;\n }\n\n public void addParameter(Parameter parameter) {\n parameters.add(parameter);\n }\n\n public void addParameter(int index, Parameter parameter) {\n parameters.add(index, parameter);\n }\n\n /**\n * @return Returns the returnType.\n */\n public FullyQualifiedJavaType getReturnType() {\n return returnType;\n }\n\n /**\n * @param returnType\n * The returnType to set.\n */\n public void setReturnType(FullyQualifiedJavaType returnType) {\n this.returnType = returnType;\n }\n\n /**\n * @return Returns the exceptions.\n */\n public List<FullyQualifiedJavaType> getExceptions() {\n return exceptions;\n }\n\n public void addException(FullyQualifiedJavaType exception) {\n exceptions.add(exception);\n }\n\n public boolean isSynchronized() {\n return isSynchronized;\n }\n\n public void setSynchronized(boolean isSynchronized) {\n this.isSynchronized = isSynchronized;\n }\n\n public boolean isNative() {\n return isNative;\n }\n\n public void setNative(boolean isNative) {\n this.isNative = isNative;\n }\n}", "public class Parameter {\n private String name;\n private FullyQualifiedJavaType type;\n private boolean isVarargs;\n\n private List<String> annotations;\n\n public Parameter(FullyQualifiedJavaType type, String name, boolean isVarargs) {\n super();\n this.name = name;\n this.type = type;\n this.isVarargs = isVarargs;\n annotations = new ArrayList<String>();\n }\n\n public Parameter(FullyQualifiedJavaType type, String name) {\n this(type, name, false);\n }\n\n public Parameter(FullyQualifiedJavaType type, String name, String annotation) {\n this(type, name, false);\n addAnnotation(annotation);\n }\n\n public Parameter(FullyQualifiedJavaType type, String name, String annotation, boolean isVarargs) {\n this(type, name, isVarargs);\n addAnnotation(annotation);\n }\n\n /**\n * @return Returns the name.\n */\n public String getName() {\n return name;\n }\n\n /**\n * @return Returns the type.\n */\n public FullyQualifiedJavaType getType() {\n return type;\n }\n\n public List<String> getAnnotations() {\n return annotations;\n }\n\n public void addAnnotation(String annotation) {\n annotations.add(annotation);\n }\n\n public String getFormattedContent() {\n StringBuilder sb = new StringBuilder();\n\n for (String annotation : annotations) {\n sb.append(annotation);\n sb.append(' ');\n }\n\n sb.append(type.getShortName());\n sb.append(' ');\n if (isVarargs) {\n sb.append(\"... \"); //$NON-NLS-1$\n }\n sb.append(name);\n\n return sb.toString();\n }\n\n @Override\n public String toString() {\n return getFormattedContent();\n }\n\n public boolean isVarargs() {\n return isVarargs;\n }\n}", "public class TopLevelClass extends InnerClass implements CompilationUnit {\n private Set<FullyQualifiedJavaType> importedTypes;\n\n private Set<String> staticImports;\n \n private List<String> fileCommentLines;\n\n /**\n * \n */\n public TopLevelClass(FullyQualifiedJavaType type) {\n super(type);\n importedTypes = new TreeSet<FullyQualifiedJavaType>();\n fileCommentLines = new ArrayList<String>();\n staticImports = new TreeSet<String>();\n }\n\n public TopLevelClass(String typeName) {\n this(new FullyQualifiedJavaType(typeName));\n }\n\n /**\n * @return Returns the importedTypes.\n */\n public Set<FullyQualifiedJavaType> getImportedTypes() {\n return Collections.unmodifiableSet(importedTypes);\n }\n\n public void addImportedType(String importedType) {\n addImportedType(new FullyQualifiedJavaType(importedType));\n }\n \n public void addImportedType(FullyQualifiedJavaType importedType) {\n if (importedType != null\n && importedType.isExplicitlyImported()\n && !importedType.getPackageName().equals(\n getType().getPackageName())) {\n importedTypes.add(importedType);\n }\n }\n\n public String getFormattedContent() {\n StringBuilder sb = new StringBuilder();\n\n for (String fileCommentLine : fileCommentLines) {\n sb.append(fileCommentLine);\n newLine(sb);\n }\n\n if (stringHasValue(getType().getPackageName())) {\n sb.append(\"package \"); //$NON-NLS-1$\n sb.append(getType().getPackageName());\n sb.append(';');\n newLine(sb);\n newLine(sb);\n }\n\n for (String staticImport : staticImports) {\n sb.append(\"import static \"); //$NON-NLS-1$\n sb.append(staticImport);\n sb.append(';');\n newLine(sb);\n }\n \n if (staticImports.size() > 0) {\n newLine(sb);\n }\n \n Set<String> importStrings = calculateImports(importedTypes);\n for (String importString : importStrings) {\n sb.append(importString);\n newLine(sb);\n }\n\n if (importStrings.size() > 0) {\n newLine(sb);\n }\n\n sb.append(super.getFormattedContent(0));\n\n return sb.toString();\n }\n\n public boolean isJavaInterface() {\n return false;\n }\n\n public boolean isJavaEnumeration() {\n return false;\n }\n\n public void addFileCommentLine(String commentLine) {\n fileCommentLines.add(commentLine);\n }\n\n public List<String> getFileCommentLines() {\n return fileCommentLines;\n }\n\n public void addImportedTypes(Set<FullyQualifiedJavaType> importedTypes) {\n this.importedTypes.addAll(importedTypes);\n }\n\n public Set<String> getStaticImports() {\n return staticImports;\n }\n\n public void addStaticImport(String staticImport) {\n staticImports.add(staticImport);\n }\n\n public void addStaticImports(Set<String> staticImports) {\n this.staticImports.addAll(staticImports);\n }\n}" ]
import java.util.Set; import java.util.TreeSet; import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType; import org.mybatis.generator.api.dom.java.Interface; import org.mybatis.generator.api.dom.java.JavaVisibility; import org.mybatis.generator.api.dom.java.Method; import org.mybatis.generator.api.dom.java.Parameter; import org.mybatis.generator.api.dom.java.TopLevelClass;
/* * Copyright 2008 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mybatis.generator.codegen.ibatis2.dao.elements; /** * * @author Jeff Butler * */ public class DeleteByExampleMethodGenerator extends AbstractDAOElementGenerator { public DeleteByExampleMethodGenerator() { super(); } @Override public void addImplementationElements(TopLevelClass topLevelClass) { Set<FullyQualifiedJavaType> importedTypes = new TreeSet<FullyQualifiedJavaType>();
Method method = getMethodShell(importedTypes);
2
rodhilton/jasome
src/main/java/org/jasome/metrics/calculators/TypeAggregatorCalculator.java
[ "public class Method extends Code {\n private final MethodDeclaration declaration;\n\n public final static Method UNKNOWN = new Method();\n\n private Method() {\n super(\"unknownMethod\");\n this.declaration = null;\n }\n\n public Method(MethodDeclaration declaration) {\n super(declaration.getDeclarationAsString());\n this.declaration = declaration;\n }\n\n public MethodDeclaration getSource() {\n return declaration;\n }\n\n public Type getParentType() {\n return (Type) getParent();\n }\n\n @Override\n public String toString() {\n return \"Method(\" + this.getName() + \")\";\n }\n}", "public class Type extends Code {\n private final ClassOrInterfaceDeclaration declaration;\n private Map<String, Method> methodLookup;\n\n public Type(ClassOrInterfaceDeclaration declaration) {\n super(getClassNameFromDeclaration(declaration));\n this.declaration = declaration;\n this.methodLookup = new HashMap<>();\n }\n\n public ClassOrInterfaceDeclaration getSource() {\n return declaration;\n }\n\n private static String getClassNameFromDeclaration(ClassOrInterfaceDeclaration classDefinition) {\n String className = classDefinition.getNameAsString();\n\n if (classDefinition.getParentNode().isPresent()) {\n Node parentNode = classDefinition.getParentNode().get();\n if (parentNode instanceof ClassOrInterfaceDeclaration) {\n className = ((ClassOrInterfaceDeclaration) parentNode).getNameAsString() + \".\" +\n classDefinition.getNameAsString();\n }\n }\n return className;\n }\n\n @SuppressWarnings(\"unchecked\")\n public Set<Method> getMethods() {\n return (Set<Method>)(Set<?>)getChildren();\n }\n\n public void addMethod(Method method) {\n methodLookup.put(method.getSource().getSignature().asString(), method);\n addChild(method);\n }\n\n public Package getParentPackage() {\n return (Package)getParent();\n }\n\n @Override\n public String toString() {\n return \"Type(\"+this.getName()+\")\";\n }\n\n public Optional<Method> lookupMethodBySignature(String methodSignature) {\n if(methodLookup.containsKey(methodSignature)) {\n return Optional.of(methodLookup.get(methodSignature));\n } else {\n return Optional.empty();\n }\n }\n}", "public interface Calculator<T extends Code> {\n\n Set<Metric> calculate(T t);\n\n}", "public class Metric {\n private String name;\n private String description;\n private NumericValue value;\n\n protected Metric(String name, String description, NumericValue value) {\n this.name = name;\n this.description = description;\n this.value = value;\n }\n\n public static Metric of(String name, String description, NumericValue value) {\n return new Metric(name, description, value);\n }\n \n public static Metric of(String name, String description, long value) {\n return new Metric(name, description, NumericValue.of(value));\n }\n\n public static Metric of(String name, String description, double value) {\n return new Metric(name, description, NumericValue.of(value));\n }\n\n public String getName() {\n return name;\n }\n\n public String getDescription() {\n return description;\n }\n\n public NumericValue getValue() {\n return value;\n }\n \n @Override\n public String toString() {\n return name + \": \" + value;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (!(o instanceof Metric)) return false;\n Metric that = (Metric) o;\n return Objects.equal(name, that.name) &&\n Objects.equal(description, that.description) &&\n Objects.equal(value, that.value);\n }\n\n @Override\n public int hashCode() {\n return Objects.hashCode(name, description, value);\n }\n\n public String getFormattedValue() {\n return value.toString();\n }\n}", "public class NumericValue implements Comparable<NumericValue> {\n private static final DecimalFormat METRIC_VALUE_FORMAT = new DecimalFormat(\"0.0########\");\n\n private Number value;\n\n public static final NumericValue ZERO=new NumericValue(LargeInteger.ZERO);\n public static final NumericValue ONE=new NumericValue(LargeInteger.ONE);\n\n public static NumericValue of(long l) {\n return new NumericValue(LargeInteger.valueOf(l));\n }\n\n public static NumericValue ofRational(long numerator, long denominator) {\n return new NumericValue(Rational.valueOf(numerator, denominator));\n }\n\n public static NumericValue of(double d) {\n return new NumericValue(Real.valueOf(d));\n }\n\n public static NumericValue of(BigInteger value) {\n return new NumericValue(LargeInteger.valueOf(value));\n }\n\n public static NumericValue of(Number n) {\n assert(n!=null);\n return new NumericValue(n);\n }\n\n private NumericValue(Number value) {\n assert(value!=null);\n this.value=value;\n }\n\n public NumericValue plus(NumericValue that) {\n assert(that!=null);\n\n Number other = that.value;\n if(value instanceof LargeInteger) {\n if(other instanceof LargeInteger) {\n return new NumericValue(((LargeInteger) value).plus((LargeInteger)other));\n } else if(other instanceof Rational) {\n return new NumericValue(((Rational)other).plus(Coerce.toRational((LargeInteger)value)));\n } else if(other instanceof Real) {\n return new NumericValue(((Real)other).plus(Coerce.toReal((LargeInteger)value)));\n }\n\n } else if (value instanceof Rational) {\n if(other instanceof LargeInteger) {\n return that.plus(this);\n } else if(other instanceof Rational) {\n return new NumericValue(((Rational)other).plus((Rational) value));\n } else if(other instanceof Real) {\n return new NumericValue(((Real)other).plus(Coerce.toReal((Rational)value)));\n }\n\n } else if( value instanceof Real) {\n if(other instanceof LargeInteger) {\n return that.plus(this);\n } else if (other instanceof Real) {\n return new NumericValue(((Real)other).plus((Real) value));\n } else if(other instanceof Rational) {\n return that.plus(this);\n }\n }\n\n throw new UnsupportedOperationException(\"Unable to add \"+value.getClass()+\" to \"+value.getClass());\n }\n\n public NumericValue negate() {\n if(value instanceof LargeInteger) {\n return new NumericValue(LargeInteger.ZERO.minus((LargeInteger)value));\n } else if (value instanceof Rational) {\n return new NumericValue(Rational.ZERO.minus((Rational)value));\n } else if(value instanceof Real) {\n return new NumericValue(Real.ZERO.minus((Real)value));\n }\n\n throw new UnsupportedOperationException(\"Unable to negate \"+value.getClass());\n }\n\n public NumericValue minus(NumericValue that) {\n assert(that!=null);\n return this.plus(that.negate());\n }\n\n public NumericValue times(NumericValue that) {\n assert(that!=null);\n\n Number other = that.value;\n if(value instanceof LargeInteger) {\n if(other instanceof LargeInteger) {\n return new NumericValue(((LargeInteger) value).times((LargeInteger)other));\n } else if(other instanceof Rational) {\n return new NumericValue(((Rational)other).times(Coerce.toRational((LargeInteger)value)));\n } else if(other instanceof Real) {\n return new NumericValue(((Real)other).times(Coerce.toReal((LargeInteger)value)));\n }\n\n } else if (value instanceof Rational) {\n if(other instanceof LargeInteger) {\n return that.times(this);\n } else if(other instanceof Rational) {\n return new NumericValue(((Rational)other).times((Rational) value));\n } else if(other instanceof Real) {\n return new NumericValue(((Real)other).times(Coerce.toReal((Rational)value)));\n }\n\n } else if( value instanceof Real) {\n if(other instanceof LargeInteger) {\n return that.times(this);\n } else if (other instanceof Real) {\n return new NumericValue(((Real)other).times((Real) value));\n } else if(other instanceof Rational) {\n return that.times(this);\n }\n }\n\n throw new UnsupportedOperationException(\"Unable to multiply \"+value.getClass()+\" to \"+value.getClass());\n }\n\n public NumericValue divide(NumericValue that) {\n assert(that!=null);\n\n Number other = that.value;\n if(value instanceof LargeInteger) {\n if(other instanceof LargeInteger) {\n return new NumericValue(Rational.valueOf((LargeInteger)value, (LargeInteger)other));\n } else if(other instanceof Rational) {\n return new NumericValue(Coerce.toRational((LargeInteger)value).divide((Rational)other));\n } else if(other instanceof Real) {\n return new NumericValue(Coerce.toReal((LargeInteger)value).divide((Real)other));\n }\n\n } else if (value instanceof Rational) {\n if(other instanceof LargeInteger) {\n return new NumericValue(((Rational) value).divide(Coerce.toRational((LargeInteger)other)));\n } else if(other instanceof Rational) {\n return new NumericValue(((Rational) value).divide((Rational) other));\n } else if(other instanceof Real) {\n return new NumericValue(Coerce.toReal((Rational)value).divide((Real)other));\n }\n\n } else if( value instanceof Real) {\n if(other instanceof LargeInteger) {\n return new NumericValue(((Real)value).divide(Coerce.toReal((LargeInteger)other)));\n } else if(other instanceof Rational) {\n return new NumericValue(((Real)value).divide(Coerce.toReal((Rational)other)));\n } else if (other instanceof Real) {\n return new NumericValue(((Real)value).divide((Real) other));\n }\n }\n\n throw new UnsupportedOperationException(\"Unable to divide \"+value.getClass()+\" to \"+value.getClass());\n }\n\n public NumericValue pow(int exp) {\n return new NumericValue(value.pow(exp));\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n NumericValue numericValue = (NumericValue) o;\n if(value instanceof Real && numericValue.value instanceof Real) {\n return ((Real)value).approximates((Real) numericValue.value);\n } else {\n return Objects.equals(value, numericValue.value);\n }\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(value);\n }\n\n @Override\n public String toString() {\n if(value instanceof LargeInteger) {\n return value.toString();\n } else {\n return METRIC_VALUE_FORMAT.format(value.doubleValue());\n }\n }\n\n public long longValue() {\n return value.longValue();\n }\n\n public double doubleValue() {\n return value.doubleValue();\n }\n\n public static NumericValue max(NumericValue left, NumericValue right) {\n if(left.minus(right).compareTo(NumericValue.ZERO) < 0) return right;\n else return left;\n }\n\n public static NumericValue min(NumericValue left, NumericValue right) {\n if(left.minus(right).compareTo(NumericValue.ZERO) < 0) return left;\n else return right;\n }\n\n @Override\n public int compareTo(NumericValue that) {\n assert(that!=null);\n Number other = that.value;\n if(value instanceof LargeInteger) {\n if(other instanceof LargeInteger) {\n return ((LargeInteger) value).compareTo((LargeInteger)other);\n } else if(other instanceof Rational) {\n return Coerce.toRational((LargeInteger)value).compareTo((Rational)other);\n } else if(other instanceof Real) {\n return compareReals(Coerce.toReal((LargeInteger)value), (Real)other);\n }\n\n } else if (value instanceof Rational) {\n if(other instanceof LargeInteger) {\n return 0-that.compareTo(this);\n } else if(other instanceof Rational) {\n return ((Rational) value).compareTo((Rational) other);\n } else if(other instanceof Real) {\n return compareReals(Coerce.toReal((Rational)value), (Real)other);\n }\n\n } else if( value instanceof Real) {\n if(other instanceof LargeInteger) {\n return 0-that.compareTo(this);\n } else if(other instanceof Rational) {\n return 0-that.compareTo(this);\n } else if (other instanceof Real) {\n return compareReals((Real) this.value, (Real) other);\n }\n }\n\n throw new UnsupportedOperationException(\"Unable to compare \"+value.getClass()+\" to \"+value.getClass());\n }\n\n private int compareReals(Real left, Real right) {\n if(left.approximates(right))\n return 0;\n else\n return left.compareTo(right);\n }\n\n public static Collector<? super NumericValue, NumericValueSummaryStatistics, NumericValueSummaryStatistics> summarizingCollector() {\n return new Collector<NumericValue, NumericValueSummaryStatistics, NumericValueSummaryStatistics>() {\n @Override\n public Supplier<NumericValueSummaryStatistics> supplier() {\n return () -> new NumericValueSummaryStatistics();\n }\n\n @Override\n public BiConsumer<NumericValueSummaryStatistics, NumericValue> accumulator() {\n return NumericValueSummaryStatistics::accumulate;\n }\n\n @Override\n public BinaryOperator<NumericValueSummaryStatistics> combiner() {\n return NumericValueSummaryStatistics::combine;\n }\n\n @Override\n public Function<NumericValueSummaryStatistics, NumericValueSummaryStatistics> finisher() {\n return NumericValueSummaryStatistics::finish;\n }\n\n @Override\n public Set<Characteristics> characteristics() {\n return Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.IDENTITY_FINISH));\n }\n };\n }\n\n public boolean isGreaterThan(NumericValue other) {\n return this.compareTo(other) > 0;\n }\n\n public boolean isLessThan(NumericValue other) {\n return this.compareTo(other) < 0;\n }\n\n public NumericValue abs() {\n if(this.isLessThan(NumericValue.ZERO)) {\n return this.negate();\n } else {\n return this;\n }\n }\n}", "public class NumericValueSummaryStatistics {\n\n private NumericValue total = null;\n private NumericValue count = NumericValue.ZERO;\n\n public NumericValue getSum() {\n return total != null ? total : NumericValue.ZERO;\n }\n\n public NumericValue getCount() {\n return count;\n }\n\n public NumericValue getMax() {\n return max != null ? max : NumericValue.ZERO;\n }\n\n public NumericValue getMin() {\n return min != null ? min : NumericValue.ZERO;\n }\n\n public NumericValue getAverage() {\n return total != null ? total.divide(count) : NumericValue.ZERO;\n }\n\n private NumericValue max = null;\n private NumericValue min = null;\n\n public NumericValueSummaryStatistics() {\n\n }\n\n public NumericValueSummaryStatistics(NumericValue total, NumericValue count, NumericValue max, NumericValue min) {\n this.total = total;\n this.count = count;\n this.max = max;\n this.min = min;\n }\n\n public static void accumulate(NumericValueSummaryStatistics numericValueSummaryStatistics, NumericValue numericValue) {\n numericValueSummaryStatistics.add(numericValue);\n }\n\n private void add(NumericValue numericValue) {\n \n if(total == null) {\n total = numericValue;\n } else {\n total = total.plus(numericValue);\n }\n\n if(max==null) {\n max = numericValue;\n } else {\n max = NumericValue.max(max, numericValue);\n }\n\n if(min == null) {\n min = numericValue;\n } else {\n min = NumericValue.min(max, numericValue);\n }\n\n count = count.plus(NumericValue.ONE);\n\n }\n\n public static NumericValueSummaryStatistics combine(NumericValueSummaryStatistics left, NumericValueSummaryStatistics right) {\n if(left.count == NumericValue.ZERO) return right;\n if(right.count == NumericValue.ZERO) return left;\n\n return new NumericValueSummaryStatistics(\n left.total.plus(right.total),\n left.count.plus(right.count),\n NumericValue.max(left.max, right.max),\n NumericValue.min(left.min, right.min)\n );\n }\n\n public static NumericValueSummaryStatistics finish(NumericValueSummaryStatistics numericValueSummaryStatistics) {\n return numericValueSummaryStatistics;\n }\n}" ]
import com.google.common.collect.ImmutableSet; import org.jasome.input.Method; import org.jasome.input.Type; import org.jasome.metrics.Calculator; import org.jasome.metrics.Metric; import org.jasome.metrics.value.NumericValue; import org.jasome.metrics.value.NumericValueSummaryStatistics; import java.util.Optional; import java.util.Set; import java.util.stream.Stream;
package org.jasome.metrics.calculators; public class TypeAggregatorCalculator implements Calculator<Type> { @Override
public Set<Metric> calculate(Type type) {
3
AEminium/AeminiumRuntime
src/aeminium/runtime/implementations/implicitworkstealing/datagroup/FifoDataGroup.java
[ "public interface DataGroup {}", "public final class Configuration {\n\tprotected static final String GLOBAL_PREFIX = \"global.\";\n\tprotected static int processorCount;\n\tprotected static String implementation;\n\tprotected static final Properties properties; \n\t\n\tstatic {\n\t\tString filename = System.getenv(\"AEMINIUMRT_CONFIG\");\n\t\tif ( filename == null ) {\n\t\t\tfilename = \"aeminiumrt.config\";\n\t\t}\n\t\tFile file = new File(filename);\n\t\tproperties = new Properties();\n\t\tif ( file.exists() && file.canRead()) {\n\t\t\tFileReader freader;\n\t\t\ttry {\n\t\t\t\tfreader = new FileReader(file);\n\t\t\t\tproperties.load(freader);\n\t\t\t\tfreader.close();\n\t\t\t} catch (IOException e) {\n\t\t\t} \n\t\t} \n\t\t\n\t\t// processor count\n\t\tString processorCount = properties.getProperty(GLOBAL_PREFIX + \"processorCount\");\n\t\tif (processorCount != null ) {\n\t\t\tConfiguration.processorCount = Integer.valueOf(processorCount);\n\t\t} else {\n\t\t\tConfiguration.processorCount = Runtime.getRuntime().availableProcessors();\n\t\t}\n\t\t\t\n\t\t// implementation\n\t\tString implementation = properties.getProperty(GLOBAL_PREFIX + \"implementation\");\n\t\tif ( implementation != null ) {\n\t\t\tConfiguration.implementation = implementation;\n\t\t} else {\n\t\t\tConfiguration.implementation = \"default\";\n\t\t}\n\t}\n\t\n\tprotected Configuration() {}\n\t\n\tpublic final static int getProcessorCount() {\n\t\treturn processorCount;\n\t}\n\t\n\tpublic final static String getImplementation() {\n\t\treturn implementation;\n\t}\n\n\tpublic final static String getProperty(Class<?> klazz, String key, String defaultValue) {\n\t\tString value = properties.getProperty(klazz.getSimpleName() + \".\" + key);\n\t\tif ( value != null ) {\n\t\t\treturn value.trim();\n\t\t} else {\n\t\t\treturn defaultValue;\n\t\t}\n\t}\n\t\n\tpublic final static int getProperty(Class<?> klazz, String key, int defaultValue) {\n\t\tString value = properties.getProperty(klazz.getSimpleName()+ \".\" + key);\n\t\tif ( value != null ) {\n\t\t\treturn Integer.valueOf(value.trim());\n\t\t} else {\n\t\t\treturn defaultValue;\n\t\t}\n\t}\n\t\n\tpublic final static boolean getProperty(Class<?> klazz, String key, boolean defaultValue) {\n\t\tString value = properties.getProperty(klazz.getSimpleName()+ \".\" + key);\n\t\tif ( value != null ) {\n\t\t\treturn Boolean.valueOf(value.trim());\n\t\t} else {\n\t\t\treturn defaultValue;\n\t\t}\n\t}\n\n}", "public final class ImplicitWorkStealingRuntime implements Runtime {\n\tpublic final ImplicitGraph graph;\n\tpublic final BlockingWorkStealingScheduler scheduler;\n\tprotected ExecutorService executorService;\n\tprotected ParallelizationDecider decider;\n\tprotected boolean shouldParallelizeCached = true;\n\tprotected int shouldParallelizeCacheCounter = 0;\n\tprotected Timer deciderTimer;\n\tprotected final EventManager eventManager;\n\tprotected DiGraphViz digraphviz;\n\tprotected AeminiumProfiler profiler;\n\tprotected ErrorManager errorManager;\n\tprotected State state = State.UNINITIALIZED;\n\tprotected ImplicitWorkStealingRuntimeDataGroupFactory dataGroupFactory;\n\t\n\tprotected final boolean nestedAtomicTasks = Configuration.getProperty(getClass(), \"nestedAtomicTasks\", false);\n\t\n\tpublic final boolean enableProfiler \t= Configuration.getProperty(getClass(), \"enableProfiler\", false);\n\tpublic final boolean offlineProfiling\t= Configuration.getProperty(getClass(), \"offlineProfiling\", false);\n\tpublic final String outputOffline \t\t= Configuration.getProperty(getClass(), \"outputOffline\", \"snapshot.jsp\");\n\t\n\tpublic final boolean profileCPU\t \t\t\t= Configuration.getProperty(getClass(), \"profileCPU\", false);\n\tpublic final boolean profileTelemetry\t\t= Configuration.getProperty(getClass(), \"profileTelemetry\", true);\n\tpublic final boolean profileThreads\t\t\t= Configuration.getProperty(getClass(), \"profileThreads\", true);\n\tpublic final boolean profileAeCounters\t\t= Configuration.getProperty(getClass(), \"profileAeCounters\", true);\n\tpublic final boolean profileAeTaskDetails\t= Configuration.getProperty(getClass(), \"profileAeTaskDetails\", true);\n\t\n\tprotected final boolean enableGraphViz = Configuration.getProperty(getClass(), \"enableGraphViz\", false);\n\tprotected final String graphVizName = Configuration.getProperty(getClass(), \"graphVizName\", \"GraphVizOutput\");\n\tprotected final int ranksep = Configuration.getProperty(getClass(), \"ranksep\", 1);\n\tprotected final RankDir rankdir = GraphViz.getDefaultValue(Configuration.getProperty(getClass(), \"rankdir\", \"TB\"), RankDir.TB, RankDir.values());\n\tprotected final int parallelizeCacheSize = Configuration.getProperty(getClass(), \"parallelizeCacheSize\", 1);\n\tprotected final boolean parallelizeUseTimer = Configuration.getProperty(getClass(), \"parallelizeUseTimer\", false);\n\tprotected final int parallelizeUpdateTimer = Configuration.getProperty(getClass(), \"parallelizeUpdateTimer\", 100);\n\t\n\tprivate AtomicInteger idCounter = new AtomicInteger(0); // Required for Profiling\n\t\n\tpublic enum State {\n\t\tUNINITIALIZED,\n\t\tINITIALIZED\n\t}\n\t\n\tpublic ImplicitWorkStealingRuntime() {\n\t\tgraph = new ImplicitGraph(this);\n\t\tscheduler = new BlockingWorkStealingScheduler(this);\n\t\teventManager = new EventManager();\n\t\terrorManager = new ErrorManagerAdapter();\n\t\tdecider \t = DeciderFactory.getDecider();\n\t\tdecider.setRuntime(this);\n\t}\n\t\n\t\n\t/* Initializes all components of the runtime. */\n\t@Override\n\tpublic final void init() {\n\t\tif ( state != State.UNINITIALIZED ) {\n\t\t\tthrow new Error(\"Cannot initialize runtime multiple times.\");\n\t\t}\n\t\t\n\t\tif (offlineProfiling) {\n\t\t\t/* Activation of profiling options according to the parameters given. */\n\t\t\tif (profileCPU) Controller.startCPURecording(true);\n\t\t\tif (profileTelemetry) Controller.startVMTelemetryRecording();\n\t if (profileThreads) Controller.startThreadProfiling();\n\t if (profileAeCounters) Controller.startProbeRecording(\"aeminium.runtime.profiler.CountersProbe\", true);\n\t if (profileAeTaskDetails) Controller.startProbeRecording(\"aeminium.runtime.profiler.TaskDetailsProbe\", true);\n\t \n\t try \n\t {\n\t \tFile file = new File(outputOffline);\n\t\t\t\tfile.createNewFile();\n\t\t\t\tController.saveSnapshotOnExit(file);\n\t\t\t\t\n\t\t\t} catch (IOException e)\n\t\t\t{\n\t\t\t\tSystem.out.println(\"File error: \" + e.getMessage());\n\t\t\t}\n\t\t}\n\n\t\teventManager.init();\n\t\tgraph.init(eventManager);\n\t\tscheduler.init(eventManager);\n\t\t\n\t\tif (enableProfiler) {\n\t\t\tprofiler = new AeminiumProfiler(scheduler, graph);\n\t\t\t\n\t\t\tthis.graph.setProfiler(profiler);\n\t\t\tthis.scheduler.setProfiler(profiler);\n\t\t}\n\t\t\n\t\tif ( enableGraphViz ) {\n\t\t\tdigraphviz = new DiGraphViz(graphVizName, ranksep, rankdir);\n\t\t}\n\t\tdataGroupFactory = new ImplicitWorkStealingRuntimeDataGroupFactory() {\t\n\t\t\t@Override\n\t\t\tpublic ImplicitWorkStealingRuntimeDataGroup create() {\n\t\t\t\treturn new FifoDataGroup();\n\t\t\t}\n\t\t};\n\t\tif ( nestedAtomicTasks ) {\n\t\t\tfinal ImplicitWorkStealingRuntimeDataGroupFactory innerFactory = dataGroupFactory;\n\t\t\tdataGroupFactory = new ImplicitWorkStealingRuntimeDataGroupFactory() {\n\t\t\t\t@Override\n\t\t\t\tpublic ImplicitWorkStealingRuntimeDataGroup create() {\n\t\t\t\t\treturn new NestedAtomicTasksDataGroup(innerFactory);\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t\terrorManager.addErrorHandler(new ErrorHandler() {\n\t\t\tprivate final String PREFIX = \"[AEMINIUM] \";\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void handleTaskException(Task task, Throwable t) {\n\t\t\t\tSystem.err.println(PREFIX + \"Task \" + task + \" threw exception: \" + t);\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void handleTaskDuplicatedSchedule(Task task) {\n\t\t\t\tSystem.err.println(PREFIX + \"Duplicated task : \" + task);\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void handleLockingDeadlock() {\n\t\t\t\tSystem.err.println(PREFIX + \"Locking Deadlock.\");\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void handleInternalError(Error error) {\n\t\t\t\tSystem.err.println(PREFIX + \"INTERNAL ERROR : \" + error);\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void handleDependencyCycle(Task task) {\n\t\t\t\tSystem.err.println(PREFIX + \"Task \" + task + \" causes a dependency cycle.\");\n\t\t\t}\n\t\t});\n\t\tif (parallelizeUseTimer) {\n\t\t\tdeciderTimer = new Timer();\n\t\t\tdeciderTimer.schedule(new TimerTask() {\n\t\t\t\t@Override\n\t\t\t\tpublic void run() {\n\t\t\t\t\tshouldParallelizeCached = decider.parallelize(null);\n\t\t\t\t}\n\t\t\t}, parallelizeUpdateTimer, parallelizeUpdateTimer);\n\t\t}\n\t\tstate = State.INITIALIZED;\n\t}\n\t\n\t@Override\n\tpublic final void shutdown() {\n\t\tif ( state != State.UNINITIALIZED ) {\n\t\t\tgraph.waitToEmpty();\n\t\t\tscheduler.shutdown();\n\t\t\teventManager.shutdown();\n\t\t\tgraph.shutdown();\n\t\t\tif ( enableGraphViz ) {\n\t\t\t\tdigraphviz.dump(new File(digraphviz.getName()+\".dot\"));\n\t\t\t\tdigraphviz = null;\n\t\t\t}\n\t\t\texecutorService = null;\n\t\t\tdataGroupFactory = null;\n\t\t\tif (parallelizeUseTimer) {\n\t\t\t\tdeciderTimer.cancel();\n\t\t\t\tdeciderTimer.purge();\n\t\t\t\tdeciderTimer = null;\n\t\t\t}\n\t\t\tstate = State.UNINITIALIZED;\n\t\t}\n\t}\n\t\n\tpublic final void waitToEmpty() {\n\t\tgraph.waitToEmpty();\n\t}\n\t\n\t@Override\n\tpublic final AtomicTask createAtomicTask(Body body, DataGroup datagroup, short hints) {\n\t\t\n\t\tImplicitAtomicTask task = new ImplicitAtomicTask(body, (ImplicitWorkStealingRuntimeDataGroup)datagroup, hints, this.enableProfiler);\n\t\ttask.id = idCounter.getAndIncrement();\n\t\t\n\t\treturn task;\n\t}\n\n\t@Override\n\tpublic final BlockingTask createBlockingTask(Body body, short hints)\n\t\t\t {\n\n\t\tImplicitBlockingTask task = new ImplicitBlockingTask(body, hints, this.enableProfiler);\n\t\ttask.id = idCounter.getAndIncrement();\n\t\t\n\t\treturn task;\n\t}\n\t\n\t@Override\n\tpublic final NonBlockingTask createNonBlockingTask(Body body, short hints)\n\t\t\t {\n\t\t\n\t\tImplicitNonBlockingTask task = new ImplicitNonBlockingTask(body, hints, this.enableProfiler);\n\t\ttask.id = idCounter.getAndIncrement();\n\t\t\n\t\treturn task;\n\t}\n\n\t@Override\n\tpublic final DataGroup createDataGroup() {\n\t\treturn dataGroupFactory.create();\n\t}\n\n\t@Override\n\tpublic final void schedule(Task task, Task parent, Collection<Task> deps)\n\t\t\t {\n\t\tif ( enableGraphViz ) {\n\t\t\tImplicitTask itask = (ImplicitTask)task;\n\t\t\tdigraphviz.addNode(itask.hashCode(), itask.body.toString());\n\t\t\tif ( parent != NO_PARENT ) {\n\t\t\t\tdigraphviz.addConnection(itask.hashCode(), parent.hashCode(), LineStyle.DASHED, Color.RED, \"\");\n\t\t\t}\n\t\t\tif ( deps != NO_DEPS ) {\n\t\t\t\tfor ( Task dep : deps) {\n\t\t\t\t\tdigraphviz.addConnection(itask.hashCode(), dep.hashCode(), LineStyle.SOLID, Color.BLUE, \"\");\n\t\t\t\t}\n \t\t\t}\n\t\t}\n\t\t\n\t\tgraph.addTask((ImplicitTask)task, parent, deps);\n\t}\n\n\t@Override\n\tpublic boolean parallelize(Task task) {\n\t\tif (parallelizeUseTimer) {\n\t\t\treturn this.shouldParallelizeCached;\n\t\t}\n\t\tif (parallelizeCacheSize > 1) {\n\t\t\tif (this.shouldParallelizeCacheCounter++ % parallelizeCacheSize == 0) this.shouldParallelizeCached = this.decider.parallelize((ImplicitTask) task);\n\t\t\treturn this.shouldParallelizeCached;\n\t\t}\n\t\treturn this.decider.parallelize((ImplicitTask) task);\n\t}\n\t\n\t@Override\n\tpublic int getTaskCount() {\n\t\treturn idCounter.get();\n\t}\n\t\n\tpublic final ExecutorService getExecutorService() {\n\t\tsynchronized (this) {\n\t\t\tif ( executorService == null ) {\n\t\t\t\texecutorService = new ImplicitWorkStealingExecutorService(this);\n\t\t\t}\n\t\t\treturn executorService;\n\t\t}\n\t}\n\t\n\tpublic DiGraphViz getGraphViz() {\n\t\treturn this.digraphviz;\n\t}\n\n\t@Override\n\tpublic final void addErrorHandler(final ErrorHandler eh) {\n\t\terrorManager.addErrorHandler(eh);\t\t\n\t}\n\n\t@Override\n\tpublic final void removeErrorHandler(final ErrorHandler eh) {\n\t\terrorManager.removeErrorHandler(eh);\n\t}\n\t\n\tpublic final ErrorManager getErrorManager() {\n\t\treturn errorManager;\n\t}\n\t\n\t/* External representation of the Runtime as the ExecutorService interface. */\n\tprotected final static class ImplicitWorkStealingExecutorService implements ExecutorService {\n\t\tprivate ImplicitWorkStealingRuntime rt;\t\t\n\t\t\n\t\tpublic ImplicitWorkStealingExecutorService(ImplicitWorkStealingRuntime rt) {\n\t\t\tsuper();\n\t\t\tthis.rt = rt;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {\n\t\t\tthrow new InterruptedException();\n\t\t}\n\n\t\t@Override\n\t\tpublic <T> List<Future<T>> invokeAll(\n\t\t\t\tCollection<? extends Callable<T>> tasks)\n\t\t\t\tthrows InterruptedException {\n\t\t\tList<Future<T>> futures = new ArrayList<Future<T>>(tasks.size());\n\t\t\tfor ( Callable<T> c : tasks) {\n\t\t\t\tfutures.add(submit(c));\n\t\t\t}\n\t\t\treturn futures;\n\t\t}\n\n\t\t@Override\n\t\tpublic <T> List<Future<T>> invokeAll(\n\t\t\t\tCollection<? extends Callable<T>> tasks, long timeout,\n\t\t\t\tTimeUnit unit) throws InterruptedException {\n\t\t\tList<Future<T>> futures = new ArrayList<Future<T>>(tasks.size());\n\t\t\tfor ( Callable<T> c : tasks) {\n\t\t\t\tfutures.add(submit(c, timeout, unit));\n\t\t\t}\n\t\t\treturn futures;\n\t\t}\n\n\t\t@Override\n\t\tpublic <T> T invokeAny(Collection<? extends Callable<T>> tasks)\n\t\t\t\tthrows InterruptedException, ExecutionException {\n\t\t\tException ex = null;\n\t\t\tfor ( Callable<T> c : tasks) {\n\t\t\t\tFuture<T> f = submit(c);\n\t\t\t\tif ( f.get() == null || (f.get() != null && !(f.get() instanceof Exception ))) {\n\t\t\t\t\treturn f.get();\n\t\t\t\t} else if ( f.get() != null && f.get() instanceof Exception ) {\n\t\t\t\t\tex = (Exception)f.get();\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow new ExecutionException(ex);\n\t\t}\n\n\t\t@Override\n\t\tpublic <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)\n\t\t throws InterruptedException, ExecutionException, TimeoutException {\n\t\t\tfinal long start = System.nanoTime();\n\t\t\tfinal Iterator<?> it = tasks.iterator();\n\t\t\tCallable<T> current = null;\n\t\t\twhile ( System.nanoTime() < start + unit.toNanos(timeout) ) {\n\t\t\t\tif ( current == null && it.hasNext() ) {\n\t\t\t\t\t@SuppressWarnings(\"unchecked\")\n\t\t\t\t\tCallable<T> tmp = (Callable<T>)it.next();\n\t\t\t\t\tcurrent = tmp;\n\t\t\t\t} else if ( !it.hasNext() ) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tFuture<T> f = submit(current);\n\t\t\t\tT result = f.get();\n\t\t\t\tif ( result != null && !(result instanceof Exception)) {\n\t\t\t\t\treturn result;\n\t\t\t\t} else {\n\t\t\t\t\tcurrent = null;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn invokeAny(tasks);\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean isShutdown() {\n\t\t\treturn rt.state == State.UNINITIALIZED;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean isTerminated() {\n\t\t\treturn rt.state == State.UNINITIALIZED;\n\t\t}\n\n\t\t@Override\n\t\tpublic void shutdown() {\n\t\t\trt.shutdown();\t\t\t\n\t\t}\n\n\t\t@Override\n\t\tpublic List<Runnable> shutdownNow() {\n\t\t\tshutdown();\n\t\t\t@SuppressWarnings(\"unchecked\")\n\t\t\tList<Runnable> result = (List<Runnable>)Collections.EMPTY_LIST;\n\t\t\treturn result;\n\t\t}\n\n\t\tpublic <T> Future<T> submit(Callable<T> task, long timeout, TimeUnit unit) {\n\t\t\t@SuppressWarnings(\"unchecked\")\n\t\t\tfinal RunnableFutureTask rft = new RunnableFutureTask((Callable<Object>)task);\n\t\t\tImplicitTask aetask = (ImplicitTask) rt.createBlockingTask(rft, NO_HINTS);\n\t\t\trft.setTask(aetask);\n\t\t\trft.setTimeOut(System.nanoTime()+unit.toNanos(timeout));\n\t\t\trt.schedule(aetask, NO_PARENT, NO_DEPS);\n\t\t\t@SuppressWarnings(\"unchecked\")\n\t\t\tFuture<T> result = (Future<T>) rft;\n\t\t\treturn result;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic <T> Future<T> submit(Callable<T> task) {\n\t\t\t@SuppressWarnings(\"unchecked\")\n\t\t\tfinal RunnableFutureTask rft = new RunnableFutureTask((Callable<Object>)task);\n\t\t\tImplicitTask aetask = (ImplicitTask) rt.createBlockingTask(rft, NO_HINTS);\n\t\t\trft.setTask(aetask);\n\t\t\trt.schedule(aetask, NO_PARENT, NO_DEPS);\n\t\t\t@SuppressWarnings(\"unchecked\")\n\t\t\tFuture<T> result = (Future<T>)rft;\n\t\t\treturn result;\n\t\t}\n\n\t\t@Override\n\t\tpublic Future<?> submit(final Runnable task) {\n\t\t\treturn submit(new Callable<Object>() {\n\n\t\t\t\t@Override\n\t\t\t\tpublic Object call() throws Exception {\n\t\t\t\t\ttask.run();\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t});\n\t\t}\n\n\t\t@Override\n\t\tpublic <T> Future<T> submit(Runnable task, T result) {\n\t\t\t@SuppressWarnings(\"unchecked\")\n\t\t\tFuture<T> tmp = (Future<T>) submit(task);\n\t\t\treturn tmp;\n\t\t}\n\n\t\t@Override\n\t\tpublic void execute(Runnable command) {\n\t\t\tsubmit(command);\t\t\t\n\t\t}\n\t\n\t\tprotected class RunnableFutureTask implements RunnableFuture<Object>, Body{\n\t\t\tprivate final Callable<Object> body;\n\t\t\tprivate ImplicitTask task;\n\t\t\tprivate boolean cancelled = false;\n\t\t\tprivate long timeout = 0;\n\t\t\t\n\t\t\tRunnableFutureTask(final Callable<Object> body) {\n\t\t\t\tsuper();\n\t\t\t\tthis.body = body;\n\t\t\t}\n\t\t\t\n\t\t\tpublic void setTask(ImplicitTask task) {\n\t\t\t\tthis.task = task;\n\t\t\t}\n\t\t\t\n\t\t\tpublic void setTimeOut(long timeout) {\n\t\t\t\tthis.timeout = timeout;\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void run() {\n\t\t\t\tthrow new Error(\"Cannot execute the run method.\");\t\t\t\t\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic boolean cancel(boolean mayInterruptIfRunning) {\n\t\t\t\tcancelled = ImplicitWorkStealingExecutorService.this.rt.scheduler.cancelTask(task);\n\t\t\t\treturn cancelled;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Object get() throws InterruptedException, ExecutionException {\n\t\t\t\tObject result = task.getResult();\n\t\t\t\tif ( result instanceof Exception ) {\n\t\t\t\t\tthrow new ExecutionException((Exception)result);\n\t\t\t\t} else {\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Object get(long timeout, TimeUnit unit) \tthrows InterruptedException, ExecutionException, TimeoutException {\n\t\t\t\tfinal long start = System.nanoTime();\n\t\t\t\twhile ( System.nanoTime() < start + unit.toNanos(timeout) ) {\n\t\t\t\t\tif ( !task.isCompleted() ) {\n\t\t\t\t\t\t// TODO: make step depending\n\t\t\t\t\t\tThread.sleep(1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif ( task.isCompleted() ) {\n\t\t\t\t\tObject result = task.getResult();\n\t\t\t\t\tif ( result instanceof Exception ) {\n\t\t\t\t\t\tthrow new ExecutionException((Exception)result);\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tthrow new TimeoutException();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic boolean isCancelled() {\n\t\t\t\treturn cancelled;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic boolean isDone() {\n\t\t\t\treturn task.isCompleted();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void execute(Runtime rt, Task current) throws Exception {\n\t\t\t\tif ( timeout < System.nanoTime() ) {\n\t\t\t\t\tcurrent.setResult(body.call());\n\t\t\t\t} else {\n\t\t\t\t\tcancelled = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t}\n\t}\n\n}", "public interface ErrorManager {\n\t/* manage subscritpions */\n\tpublic void addErrorHandler(final ErrorHandler eh);\n\tpublic void removeErrorHandler(final ErrorHandler eh);\n\t\n\t/* singal errors */\n\tpublic void signalTaskException(final Task task, final Throwable e);\n\tpublic void signalDependencyCycle(final Task task);\n\tpublic void signalTaskDuplicatedSchedule(final Task task);\n\tpublic void signalInternalError(final Error err);\n\tpublic void signalLockingDeadlock();\n}", "public final class ImplicitAtomicTask extends ImplicitTask implements AtomicTask {\n\tprotected ImplicitWorkStealingRuntimeDataGroup datagroup;\n\tprotected ImplicitAtomicTask atomicParent = null;\n\tprotected volatile Set<DataGroup> requiredGroups;\n\n\tpublic ImplicitAtomicTask(Body body, ImplicitWorkStealingRuntimeDataGroup datagroup, short hints, boolean enableProfiler) {\n\t\tsuper(body, hints, enableProfiler);\n\t\tthis.datagroup = datagroup;\n\t}\n\n\t/* Associates another datagroup with the current Task. */\n\tpublic void addDataGroupDependecy(DataGroup required) {\n\t\tif ( requiredGroups == null ) {\n\t\t\tsynchronized (this) {\n\t\t\t\tif (requiredGroups == null ) {\n\t\t\t\t\trequiredGroups = Collections.synchronizedSet(new HashSet<DataGroup>());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\trequiredGroups.add(required);\n\t}\n\t\n\t/* Detaches another datagroup with the current Task. */\n\tpublic void removeDataGroupDependecy(DataGroup required) {\n\t\tif ( requiredGroups == null ) {\n\t\t\tsynchronized (this) {\n\t\t\t\tif (requiredGroups == null ) {\n\t\t\t\t\trequiredGroups = Collections.synchronizedSet(new HashSet<DataGroup>());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\trequiredGroups.remove(required);\n\t}\n\t\n\t/* Retrives all datagroups associated with the current task. */\n\tpublic Set<DataGroup> getDataGroupDependencies() {\n\t\tif ( requiredGroups == null ) {\n\t\t\treturn Collections.emptySet();\n\t\t} else {\t\t\t\n\t\t\treturn Collections.unmodifiableSet(requiredGroups);\n\t\t}\n\t}\n\t\n\t/* In case of nested synchronization, returns the task that held the lock\n\t * before executing this task.\n\t * */\n\tpublic ImplicitAtomicTask getAtomicParent() {\n\t\tImplicitAtomicTask result = atomicParent;\n\t\tif ( result == null ) {\n\t\t\tsynchronized (this) {\n\t\t\t\tatomicParent = this;\n\t\t\t\t// search upwards \n\t\t\t\tImplicitTask parent = this.parent;\n\t\t\t\twhile ( parent != null ) {\n\t\t\t\t\tif ( parent instanceof ImplicitAtomicTask) {\n\t\t\t\t\t\tatomicParent = (ImplicitAtomicTask)parent;\n\t\t\t\t\t}\n\t\t\t\t\tparent = parent.parent;\n\t\t\t\t}\t\t\t\t\n\t\t\t\tresult = atomicParent;\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\t\n\t@Override\n\tpublic final void invoke(ImplicitWorkStealingRuntime rt) {\n\t\tif ( datagroup.trylock(rt, this) ) {\n\t\t\tsuper.invoke(rt);\n\t\t}\t\n\t}\n\n\t@Override \n\tpublic final void taskCompleted(ImplicitWorkStealingRuntime rt) {\n\t\tdatagroup.unlock(rt, this);\n\t\tsuper.taskCompleted(rt);\n\t}\n\n\tpublic final DataGroup getDataGroup() {\n\t\tsynchronized (this) {\n\t\t\treturn datagroup;\n\t\t}\n\t}\n\n}", "public abstract class ImplicitTask implements Task\n{\n\tprotected static final Object UNSET = new Object()\n\t{\n\t\t@Override\n\t\tpublic String toString()\n\t\t{\n\t\t\treturn \"UNSET\";\n\t\t}\n\t};\n\n\tprotected volatile Object result = UNSET; // could merge result with body\n\tpublic Body body;\n\tprivate ImplicitTaskState state = ImplicitTaskState.UNSCHEDULED; // could be a byte instead of a reference\n\tpublic volatile int depCount;\n\tpublic int childCount;\n\tpublic List<ImplicitTask> dependents;\n\tpublic List<ImplicitTask> children; // children are only used for debugging purposes => could be removed\n\tpublic ImplicitTask parent;\n\tpublic static final boolean debug = Configuration.getProperty(ImplicitTask.class, \"debug\", false);\n\tpublic final boolean enableProfiler;\n\tpublic final short hints;\n\tpublic short level;\n\tpublic Thread waiter; // we could same this and just mention that there is someone waiting\n\tpublic Runnable finishedCallback;\n\n\t/* Added for profiler. */\n\tpublic int id;\n\t\n\tpublic ImplicitTask(Body body, short hints, boolean enableProfiler) {\n\t\tthis.body = body;\n\t\tthis.hints = hints;\n\t\tthis.enableProfiler = enableProfiler;\n\t}\n\t\t\n\tpublic void invoke(ImplicitWorkStealingRuntime rt) {\n\t\t\n\t\tif (enableProfiler)\n\t\t\tthis.setState(ImplicitTaskState.RUNNING, rt.graph);\n\t\telse\n\t\t\tthis.setState(ImplicitTaskState.RUNNING);\n\t\t\n\t\ttry {\n\t\t\tbody.execute(rt, this);\n\t\t} catch (Throwable e)\n\t\t{\n\t\t\trt.getErrorManager().signalTaskException(this, e);\n\t\t\tsetResult(e);\n\t\t} finally\n\t\t{\n\t\t\ttaskFinished(rt);\n\t\t}\n\t}\n\n\t@Override\n\tpublic final void setResult(Object result)\n\t{\n\t\tthis.result = result;\n\t}\n\n\t@Override\n\tpublic final Object getResult()\n\t{\n\t\tif (this.isCompleted())\n\t\t{\n\t\t\treturn result;\n\t\t} else\n\t\t{\n\t\t\tThread thread = Thread.currentThread();\n\t\t\tif ( thread instanceof WorkStealingThread )\n\t\t\t{\n\t\t\t\t((WorkStealingThread)thread).progressToCompletion(this);\n\t\t\t} else\n\t\t\t{\n\t\t\t\tsynchronized (this)\n\t\t\t\t{\n\t\t\t\t\twhile (!isCompleted())\n\t\t\t\t\t{\n\t\t\t\t\t\twaiter = thread;\n\n\t\t\t\t\t\ttry\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tthis.wait();\n\t\t\t\t\t\t} catch (InterruptedException e)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn result;\n\t\t}\n\t}\n\n\tpublic final void attachChild(ImplicitWorkStealingRuntime rt, ImplicitTask child)\n\t{\n\t\tsynchronized (this)\n\t\t{\n\t\t\tchildCount += 1;\n\n\t\t\tif (debug)\n\t\t\t{\n\t\t\t\tif (children == null )\n\t\t\t\t\tchildren = new ArrayList<ImplicitTask>(10);\n\n\t\t\t\tchildren.add(child);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic final int addDependent(ImplicitTask task)\n\t{\n\t\tsynchronized (this)\n\t\t{\n\t\t\tif ( state == ImplicitTaskState.COMPLETED)\n\t\t\t\treturn 0;\n\n\t\t\tif (this.dependents == null)\n\t\t\t\tthis.dependents = new ArrayList<ImplicitTask>();\n\n\t\t\tthis.dependents.add(task);\n\t\t\t//System.err.println(\"Added \" + task.id + \" to dependents of \" + this.id);\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\tpublic final void decDependencyCount(ImplicitWorkStealingRuntime rt)\n\t{\n\t\tboolean schedule = false;\n\t\tsynchronized (this)\n\t\t{\n\t\t\tdepCount -= 1;\n\t\t\t//System.err.println(\"Decrementing \" + this.id + \" - \" + depCount);\n\n\t\t\tif ( depCount == 0 ) {\n\t\t\t\tif (enableProfiler) {\n\t\t\t\t\tthis.setState(ImplicitTaskState.WAITING_IN_QUEUE, rt.graph);\n\t\t\t\t} else {\n\t\t\t\t\tthis.setState(ImplicitTaskState.WAITING_IN_QUEUE);\n\t\t\t\t}\n\t\t\t\tschedule = true;\n\t\t\t}\n\t\t}\n\t\tif ( schedule ) {\n\t\t\t//System.err.println(\"Scheduling \" + this.id);\n\t\t\trt.scheduler.scheduleTask(this);\n\t\t}\n\t}\n\n\tpublic final void taskFinished(ImplicitWorkStealingRuntime rt)\n\t{\n\t\t\n\t\tboolean completed = false;\n\t\tsynchronized (this) {\n\t\t\tif (childCount == 0) {\n\t\t\t\tcompleted = true;\n\t\t\t} else {\n\t\t\t\tif (enableProfiler) {\n\t\t\t\t\tthis.setState(ImplicitTaskState.WAITING_FOR_CHILDREN, rt.graph);\n\t\t\t\t} else {\n\t\t\t\t\tthis.setState(ImplicitTaskState.WAITING_FOR_CHILDREN);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (completed)\n\t\t\ttaskCompleted(rt);\n\t}\n\n\tpublic boolean detachChild(ImplicitWorkStealingRuntime rt)\n\t{\n\t\t\n\t\tsynchronized(this)\n\t\t{\n\t\t\tthis.childCount--;\n\t\t\t\n\t\t\tif (this.childCount <= 0 && state == ImplicitTaskState.WAITING_FOR_CHILDREN)\n\t\t\t\treturn true;\n\t\t}\n\t\t\n\t\treturn false;\n\t}\n\t\n\tpublic void taskCompleted(ImplicitWorkStealingRuntime rt)\n\t{\n\t\tImplicitTask task = this;\n\t\tImplicitTask next;\n\t\t\n\t\tdo\n\t\t{\n\t\t\tsynchronized(task)\n\t\t\t{\n\t\t\t\tif (enableProfiler) {\n\t\t\t\t\tthis.setState(ImplicitTaskState.COMPLETED, rt.graph);\n\t\t\t\t} else {\n\t\t\t\t\tthis.setState(ImplicitTaskState.COMPLETED);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (task.parent != null && task.parent.detachChild(rt))\n\t\t\t\tnext = task.parent;\n\t\t\telse\n\t\t\t\tnext = null;\n\t\t\t\t\n\t\t\tif (task.dependents != null)\n\t\t\t{\n\t\t\t\tfor (ImplicitTask t : task.dependents)\n\t\t\t\t\tt.decDependencyCount(rt);\n\n\t\t\t\ttask.dependents = null;\n\t\t\t}\n\t\t\t\n\t\t\t// callback\n\t\t\tif (finishedCallback != null) {\n\t\t\t\tfinishedCallback.run();\n\t\t\t\tfinishedCallback = null;\n\t\t\t}\n\n\t\t\t// cleanup references\n\t\t\ttask.body = null;\n\t\t\ttask.children = null;\n\n\t\t\trt.graph.taskCompleted(task);\n\n\t\t\tif (task.waiter != null) {\n\t\t\t\tsynchronized(this) {\n\t\t\t\t\tnotifyAll();\n\t\t\t\t}\t\n\t\t\t}\n\t\t\t\n\t\t\ttask = next;\n\t\t} while (task != null);\n\t}\n\n\tpublic final boolean isCompleted()\n\t{\n\t\treturn state == ImplicitTaskState.COMPLETED;\n\t}\n\n\tpublic void checkForCycles(final ErrorManager em)\n\t{\n\t\tsynchronized (this)\n\t\t{\n\t\t\tcheckForCycles(this, dependents, em);\n\t\t}\n\t}\n\n\tprotected void checkForCycles(final ImplicitTask task, final Collection<ImplicitTask> deps, final ErrorManager em)\n\t{\n\t\tif (deps == null)\n\t\t\treturn;\n\n\t\tfor (ImplicitTask t : deps)\n\t\t\tcheckPath(task, t, em);\n\t}\n\n\tprotected void checkPath(final ImplicitTask task, ImplicitTask dep, final ErrorManager em)\n\t{\n\t\tif (task == dep)\n\t\t{\n\t\t\tem.signalDependencyCycle(task);\n\t\t} else\n\t\t{\n\t\t\tCollection<ImplicitTask> nextDependents;\n\t\t\tsynchronized (dep)\n\t\t\t{\n\t\t\t\tnextDependents = Collections.unmodifiableList(dep.dependents);\n\t\t\t}\n\n\t\t\tcheckForCycles(task, nextDependents, em);\n\t\t}\n\t}\n\t\n\t/* This method simply changes the state of the task. */\n\tpublic void setState(ImplicitTaskState newState) {\n\t\tthis.state = newState;\n\t}\n\t\n\t/* If we are using the profiler, we need to call these methods, because we need to update\n\t * the value of the graph variables concerning the actual state, namely, for example, the \n\t * number of running tasks or the number of tasks waiting for dependencies.\n\t */\n\tpublic void setState(ImplicitTaskState newState, ImplicitGraph graph) {\n\t\t\n\t\t/* First, we have to test the previous state, decreasing the corresponding\n\t\t * number of tasks in the graph for that category.\n\t\t */\n\t\tif (this.state == ImplicitTaskState.UNSCHEDULED) {\n\t\t\tgraph.noUnscheduledTasks.decrementAndGet();\n\t\t} else if (this.state == ImplicitTaskState.WAITING_IN_QUEUE) {\n\t\t\t\tgraph.noTasksWaitingInQueue.decrementAndGet();\t\n\t\t} else if (this.state == ImplicitTaskState.RUNNING) {\n\t\t\tgraph.noRunningTasks.decrementAndGet();\n\t\t} else if (this.state == ImplicitTaskState.WAITING_FOR_DEPENDENCIES) {\n\t\t\tgraph.noWaitingForDependenciesTasks.decrementAndGet();\n\t\t} else if (this.state == ImplicitTaskState.WAITING_FOR_CHILDREN) {\n\t\t\tgraph.noWaitingForChildrenTasks.decrementAndGet();\n\t\t} else if (this.state == ImplicitTaskState.COMPLETED) {\n\t\t\tgraph.noCompletedTasks.decrementAndGet();\n\t\t}\n\t\t\n\t\t/* Update the task state. */\n\t\tthis.state = newState;\n\t\t\n\t\t/* Having the new state, we also need to update the graph counters. */\n\t\tif (this.state == ImplicitTaskState.UNSCHEDULED) {\n\t\t\tgraph.noUnscheduledTasks.incrementAndGet();\n\t\t} else if (this.state == ImplicitTaskState.WAITING_IN_QUEUE) {\n\t\t\t\tgraph.noTasksWaitingInQueue.incrementAndGet();\t\n\t\t} else if (this.state == ImplicitTaskState.RUNNING) {\n\t\t\tgraph.noRunningTasks.incrementAndGet();\n\t\t} else if (this.state == ImplicitTaskState.WAITING_FOR_DEPENDENCIES) {\n\t\t\tgraph.noWaitingForDependenciesTasks.incrementAndGet();\n\t\t} else if (this.state == ImplicitTaskState.WAITING_FOR_CHILDREN) {\n\t\t\tgraph.noWaitingForChildrenTasks.incrementAndGet();\n\t\t} else if (this.state == ImplicitTaskState.COMPLETED) {\n\t\t\tgraph.noCompletedTasks.incrementAndGet();\n\t\t}\n\t}\n\t\n\tpublic ImplicitTaskState getState() {\n\t\treturn this.state;\n\t}\n\t\n\tpublic void setFinishedCallback(Runnable r) {\n\t\tfinishedCallback = r;\n\t}\n\t\n\n\t@Override\n\tpublic String toString()\n\t{\n\t\treturn \"Task<\"+body+\">[children:\"+childCount+\", deps:\"+depCount+\", state:\"+state+\"]\";\n\t}\n}", "public class DiGraphViz extends GraphViz {\n\tprotected final String name;\n\tprotected final StringBuffer nodes;\n\tprotected final StringBuffer connections;\n\tprotected final String EOL = System.getProperty(\"line.separator\");\n\tprotected final int ranksep;\n\tprotected final RankDir rankdir;\n\t\n\tpublic DiGraphViz(String name, int ranksep, RankDir rankdir) {\n\t\tthis.name = name;\n\t\tthis.ranksep = ranksep;\n\t\tthis.rankdir = rankdir;\n\t\tnodes = new StringBuffer();\n\t\tconnections = new StringBuffer();\n\t}\n\t\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\t\n\tpublic void addNode(int id, String label) {\n\t\taddNode(id, label, DEFAULT_SHAPE, DEFAULT_COLOR);\n\t}\n\t\n\tpublic void addNode(int id,\n\t\t\t\t\t String label,\n\t\t\t\t\t Shape shape,\n\t\t\t\t\t Color color) {\n\t\tnodes.append(String.format(\" %12d [label=\\\"%s\\\", shape=\\\"%s\\\", color=\\\"%s\\\"]\"+EOL, id, label, shape.name().toLowerCase(), color.name().toLowerCase()));\n\t}\n\t\n\tpublic void addConnection(int from, int to) {\n\t\taddConnection(from, to, DEFAULT_LINE_STYLE, DEFAULT_COLOR, \"\");\t\n\t}\n\t\n\tpublic void addConnection(int from,\n\t\t\t\t\t\t\t int to,\n\t\t\t\t\t\t\t LineStyle lineStyle,\n\t\t\t\t\t\t\t Color color,\n\t\t\t\t\t\t\t String label) {\n\t\tconnections.append(String.format(\" %12d -> %12d [style=\\\"%s\\\", color=\\\"%s\\\", fontcolor=\\\"%s\\\", label=\\\"%s\\\"]\"+EOL, from, to, lineStyle.name().toLowerCase(), color.name().toLowerCase(), color.name().toLowerCase(), label));\n\t}\n\t\n\tpublic boolean dump(File file) {\n\t\ttry {\n\t\t\tFileOutputStream fos = new FileOutputStream(file);\n\t\t\tdump(fos);\n\t\t\tfos.close();\n\t\t\treturn true;\n\t\t} catch (IOException e) {\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic boolean dump(OutputStream os ) {\n\t\ttry {\n\t\t\tdumpOutputStream(os);\n\t\t\treturn true;\n\t\t} catch (IOException e) {\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprotected void dumpOutputStream(OutputStream os) throws IOException {\n\t\tos.write(String.format(\"digraph %s {\" + EOL, name).getBytes());\n\t\tos.write(String.format(\" rankdir=%s\" + EOL, rankdir.name()).getBytes());\n\t\tos.write(String.format(\" ranksep=%d\" + EOL, ranksep).getBytes());\n\t\tos.write(nodes.toString().getBytes());\n\t\tos.write(connections.toString().getBytes());\n\t\tos.write(\"}\".getBytes());\n\t}\n}", "public static enum Color {\n\tRED,\n\tGREEN,\n\tBLUE,\n\tBLACK,\n\tYELLOW\n}", "public static enum LineStyle {\n\tSOLID,\n\tDASHED,\n\tDOTTED\n}" ]
import aeminium.runtime.utils.graphviz.GraphViz.Color; import aeminium.runtime.utils.graphviz.GraphViz.LineStyle; import java.util.LinkedList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import aeminium.runtime.DataGroup; import aeminium.runtime.implementations.Configuration; import aeminium.runtime.implementations.implicitworkstealing.ImplicitWorkStealingRuntime; import aeminium.runtime.implementations.implicitworkstealing.error.ErrorManager; import aeminium.runtime.implementations.implicitworkstealing.task.ImplicitAtomicTask; import aeminium.runtime.implementations.implicitworkstealing.task.ImplicitTask; import aeminium.runtime.utils.graphviz.DiGraphViz;
/** * Copyright (c) 2010-11 The AEminium Project (see AUTHORS file) * * This file is part of Plaid Programming Language. * * Plaid Programming Language is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Plaid Programming Language is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Plaid Programming Language. If not, see <http://www.gnu.org/licenses/>. */ package aeminium.runtime.implementations.implicitworkstealing.datagroup; /* * A DataGroup (DG) implementation that works similar to a lock. */ public final class FifoDataGroup implements ImplicitWorkStealingRuntimeDataGroup { protected static final boolean checkForDeadlocks = Configuration.getProperty(FifoDataGroup.class, "checkForDeadlocks", false); protected static final boolean graphVizEnabled = Configuration.getProperty(ImplicitWorkStealingRuntime.class, "enableGraphViz", false); protected static final boolean graphVizShowLockingOrder = Configuration.getProperty(FifoDataGroup.class, "graphVizShowLockingOrder", false); protected static AtomicInteger idGen = new AtomicInteger(); private boolean locked = false; private List<ImplicitTask> waitQueue = new LinkedList<ImplicitTask>(); protected ImplicitTask owner = null; protected ImplicitTask previousOwner; protected final int id = idGen.incrementAndGet(); // Tries to hold the lock on the DG. public final boolean trylock(ImplicitWorkStealingRuntime rt, ImplicitTask task) { synchronized (this) { if ( locked ) { waitQueue.add(task); if ( checkForDeadlocks ) { ImplicitAtomicTask atomicParent = ((ImplicitAtomicTask)task).getAtomicParent(); atomicParent.addDataGroupDependecy(this); checkForDeadlock(atomicParent, rt.getErrorManager()); } return false; } else { locked = true; owner = task; if ( graphVizEnabled && graphVizShowLockingOrder && previousOwner != null ) { DiGraphViz graphViz = rt.getGraphViz(); graphViz.addConnection(owner.hashCode(), previousOwner.hashCode(), LineStyle.DOTTED, Color.GREEN, ""+id); } return true; } } } // Releases the lock on the DG public final void unlock(ImplicitWorkStealingRuntime rt, ImplicitTask task) { ImplicitTask head = null; synchronized (this) { locked = false; previousOwner = owner; owner = null; if (!waitQueue.isEmpty()) { head = waitQueue.remove(0); if ( checkForDeadlocks ) { ImplicitAtomicTask atomicParent = ((ImplicitAtomicTask)head).getAtomicParent(); atomicParent.addDataGroupDependecy(this); } } } if ( head != null ) { rt.scheduler.scheduleTask(head); } } public final boolean checkForDeadlock(final ImplicitAtomicTask atomicParent, final ErrorManager em) {
for ( DataGroup dg : atomicParent.getDataGroupDependencies() ) {
0
OpherV/gitflow4idea
src/main/java/gitflow/ui/GitflowOpenTaskPanel.java
[ "public class GitflowBranchUtil {\n\n Project myProject;\n GitRepository myRepo;\n\n private String currentBranchName;\n private String branchnameMaster;\n private String branchnameDevelop;\n private String prefixFeature;\n private String prefixRelease;\n private String prefixHotfix;\n private String prefixBugfix;\n private ArrayList<GitRemoteBranch> remoteBranches;\n private ArrayList<String> remoteBranchNames;\n private ArrayList<GitLocalBranch> localBranches;\n private ArrayList<String> localBranchNames;\n\n public GitflowBranchUtil(Project project, GitRepository repo){\n myProject=project;\n myRepo = repo;\n\n if (repo != null) {\n update();\n }\n }\n\n public void update(){\n currentBranchName = GitBranchUtil.getBranchNameOrRev(myRepo);\n\n GitflowConfigUtil gitflowConfigUtil = GitflowConfigUtil.getInstance(myProject, myRepo);\n gitflowConfigUtil.update();\n branchnameMaster = gitflowConfigUtil.masterBranch;\n branchnameDevelop = gitflowConfigUtil.developBranch;\n prefixFeature = gitflowConfigUtil.featurePrefix;\n prefixRelease = gitflowConfigUtil.releasePrefix;\n prefixHotfix = gitflowConfigUtil.hotfixPrefix;\n prefixBugfix = gitflowConfigUtil.bugfixPrefix;\n\n initRemoteBranches();\n initLocalBranchNames();\n }\n\n public String getCurrentBranchName() {\n return currentBranchName;\n }\n\n public boolean hasGitflow(){\n boolean hasGitflow = myRepo != null\n && getBranchnameMaster() != null\n && getBranchnameDevelop() != null\n && getPrefixFeature() != null\n && getPrefixRelease() != null\n && getPrefixHotfix() != null\n && getPrefixBugfix() != null;\n\n return hasGitflow;\n }\n\n public String getBranchnameMaster() {\n return branchnameMaster;\n }\n\n public String getBranchnameDevelop() {\n return branchnameDevelop;\n }\n\n public String getPrefixFeature() {\n return prefixFeature;\n }\n\n public String getPrefixRelease() {\n return prefixRelease;\n }\n\n public String getPrefixHotfix() {\n return prefixHotfix;\n }\n\n public String getPrefixBugfix() {\n return prefixBugfix;\n }\n\n public boolean isCurrentBranchMaster(){\n return currentBranchName.startsWith(branchnameMaster);\n }\n\n public boolean isCurrentBranchFeature(){\n return isBranchFeature(currentBranchName);\n }\n\n\n public boolean isCurrentBranchRelease(){\n return currentBranchName.startsWith(prefixRelease);\n }\n\n public boolean isCurrentBranchHotfix(){\n return isBranchHotfix(currentBranchName);\n }\n\n public boolean isCurrentBranchBugfix(){\n return isBranchBugfix(currentBranchName);\n }\n\n //checks whether the current branch also exists on the remote\n public boolean isCurrentBranchPublished(){\n return getRemoteBranchesWithPrefix(currentBranchName).isEmpty()==false;\n }\n\n public boolean isBranchFeature(String branchName){\n return branchName.startsWith(prefixFeature);\n }\n\n public boolean isBranchHotfix(String branchName){\n return branchName.startsWith(prefixHotfix);\n }\n\n public boolean isBranchBugfix(String branchName){\n return branchName.startsWith(prefixBugfix);\n }\n\n private void initRemoteBranches() {\n remoteBranches =\n new ArrayList<GitRemoteBranch>(myRepo.getBranches().getRemoteBranches());\n remoteBranchNames = new ArrayList<String>();\n\n for(Iterator<GitRemoteBranch> i = remoteBranches.iterator(); i.hasNext(); ) {\n GitRemoteBranch branch = i.next();\n remoteBranchNames.add(branch.getName());\n }\n }\n\n private void initLocalBranchNames(){\n localBranches =\n new ArrayList<GitLocalBranch>(myRepo.getBranches().getLocalBranches());\n localBranchNames = new ArrayList<String>();\n\n for(Iterator<GitLocalBranch> i = localBranches.iterator(); i.hasNext(); ) {\n GitLocalBranch branch = i.next();\n localBranchNames.add(branch.getName());\n }\n }\n\n //if no prefix specified, returns all remote branches\n public ArrayList<String> getRemoteBranchesWithPrefix(String prefix){\n ArrayList<String> remoteBranches = remoteBranchNames;\n ArrayList<String> selectedBranches = new ArrayList<String>();\n\n for(Iterator<String> i = remoteBranches.iterator(); i.hasNext(); ) {\n String branch = i.next();\n if (branch.contains(prefix)){\n selectedBranches.add(branch);\n }\n }\n\n return selectedBranches;\n }\n\n\n public ArrayList<String> filterBranchListByPrefix(Collection<String> inputBranches,String prefix){\n ArrayList<String> outputBranches= new ArrayList<String>();\n\n for(Iterator<String> i = inputBranches.iterator(); i.hasNext(); ) {\n String branch = i.next();\n if (branch.contains(prefix)){\n outputBranches.add(branch);\n }\n }\n\n return outputBranches;\n }\n\n public ArrayList<String> getRemoteBranchNames(){\n return remoteBranchNames;\n }\n\n public ArrayList<String> getLocalBranchNames() {\n return localBranchNames;\n }\n\n public GitRemote getRemoteByBranch(String branchName){\n GitRemote remote=null;\n\n for(Iterator<GitRemoteBranch> i = remoteBranches.iterator(); i.hasNext(); ) {\n GitRemoteBranch branch = i.next();\n if (branch.getName().equals(branchName)){\n remote=branch.getRemote();\n break;\n }\n }\n\n return remote;\n }\n\n public boolean areAllBranchesTracked(String prefix){\n\n\n ArrayList<String> localBranches = filterBranchListByPrefix(getLocalBranchNames() , prefix) ;\n\n //to avoid a vacuous truth value. That is, when no branches at all exist, they shouldn't be\n //considered as \"all pulled\"\n if (localBranches.isEmpty()){\n return false;\n }\n\n ArrayList<String> remoteBranches = getRemoteBranchNames();\n\n //check that every local branch has a matching remote branch\n for(Iterator<String> i = localBranches.iterator(); i.hasNext(); ) {\n String localBranch = i.next();\n boolean hasMatchingRemoteBranch = false;\n\n for(Iterator<String> j = remoteBranches.iterator(); j.hasNext(); ) {\n String remoteBranch = j.next();\n\n if (remoteBranch.contains(localBranch)){\n hasMatchingRemoteBranch=true;\n break;\n }\n }\n\n //at least one matching branch wasn't found\n if (hasMatchingRemoteBranch==false){\n return false;\n }\n }\n\n return true;\n }\n\n public ComboBoxModel createBranchComboModel(String defaultBranch) {\n final List<String> branchList = this.getLocalBranchNames();\n branchList.remove(defaultBranch);\n\n ComboEntry[] entries = new ComboEntry[branchList.size() + 1];\n entries[0] = new ComboEntry(defaultBranch, defaultBranch + \" (default)\");\n for (int i = 1; i <= branchList.size(); i++) {\n String branchName = branchList.get(i - 1);\n entries[i] = new ComboEntry(branchName, branchName);\n }\n\n return new DefaultComboBoxModel(entries);\n }\n\n /**\n * Strip a full branch name from its gitflow prefix\n * @param fullBranchName full name of the branch (e.g. 'feature/hello');\n * @return the branch name, prefix free (e.g. 'hello')\n */\n public String stripFullBranchName(String fullBranchName) {\n if (fullBranchName.startsWith(prefixFeature)){\n return fullBranchName.substring(prefixFeature.length(), fullBranchName.length());\n }\n else if (fullBranchName.startsWith(prefixHotfix)){\n return fullBranchName.substring(prefixHotfix.length(), fullBranchName.length());\n } else if (fullBranchName.startsWith(prefixBugfix)){\n return fullBranchName.substring(prefixBugfix.length(), fullBranchName.length());\n } else{\n return null;\n }\n };\n\n /**\n * An entry for the branch selection dropdown/combo.\n */\n public static class ComboEntry {\n private String branchName, label;\n\n public ComboEntry(String branchName, String label) {\n this.branchName = branchName;\n this.label = label;\n }\n\n public String getBranchName() {\n return branchName;\n }\n\n @Override\n public String toString() {\n return label;\n }\n }\n}", "public class GitflowBranchUtilManager {\n private static HashMap<String, GitflowBranchUtil> repoBranchUtilMap;\n\n static public GitflowBranchUtil getBranchUtil(GitRepository repo){\n if (repo != null && repoBranchUtilMap != null) {\n return repoBranchUtilMap.get(repo.getPresentableUrl());\n } else {\n return null;\n }\n }\n\n static public void setupBranchUtil(Project project, GitRepository repo){\n GitflowBranchUtil gitflowBranchUtil = new GitflowBranchUtil(project, repo);\n repoBranchUtilMap.put(repo.getPresentableUrl(), gitflowBranchUtil);\n // clean up\n Disposer.register(repo, () -> repoBranchUtilMap.remove(repo));\n }\n\n /**\n * Repopulates the branchUtils for each repo\n * @param proj\n */\n static public void update(Project proj){\n if (repoBranchUtilMap == null){\n repoBranchUtilMap = new HashMap<String, gitflow.GitflowBranchUtil>();\n }\n\n List<GitRepository> gitRepositories = GitUtil.getRepositoryManager(proj).getRepositories();\n\n Iterator gitRepositoriesIterator = gitRepositories.iterator();\n while(gitRepositoriesIterator.hasNext()){\n GitRepository repo = (GitRepository) gitRepositoriesIterator.next();\n GitflowBranchUtilManager.setupBranchUtil(proj, repo);\n }\n }\n}", "public class GitflowConfigUtil {\n\n public static final String BRANCH_MASTER = \"gitflow.branch.master\";\n public static final String BRANCH_DEVELOP = \"gitflow.branch.develop\";\n public static final String PREFIX_FEATURE = \"gitflow.prefix.feature\";\n public static final String PREFIX_RELEASE = \"gitflow.prefix.release\";\n public static final String PREFIX_HOTFIX = \"gitflow.prefix.hotfix\";\n public static final String PREFIX_BUGFIX = \"gitflow.prefix.bugfix\";\n public static final String PREFIX_SUPPORT = \"gitflow.prefix.support\";\n public static final String PREFIX_VERSIONTAG = \"gitflow.prefix.versiontag\";\n\n private static Map<Project, Map<String, GitflowConfigUtil>> gitflowConfigUtilMap = new HashMap<Project, Map<String, GitflowConfigUtil>>();\n\n Project project;\n GitRepository repo;\n public String masterBranch;\n public String developBranch;\n public String featurePrefix;\n public String releasePrefix;\n public String hotfixPrefix;\n public String bugfixPrefix;\n public String supportPrefix;\n public String versiontagPrefix;\n\n public static GitflowConfigUtil getInstance(@NotNull Project project_, @NotNull GitRepository repo_)\n {\n GitflowConfigUtil instance;\n if (gitflowConfigUtilMap.containsKey(project_) && gitflowConfigUtilMap.get(project_).containsKey(repo_.getPresentableUrl())) {\n instance = gitflowConfigUtilMap.get(project_).get(repo_.getPresentableUrl());\n } else {\n Map<String, GitflowConfigUtil> innerMap = new HashMap<String, GitflowConfigUtil>();\n instance = new GitflowConfigUtil(project_, repo_);\n\n gitflowConfigUtilMap.put(project_, innerMap);\n innerMap.put(repo_.getPresentableUrl(), instance);\n\n //cleanup\n Disposer.register(repo_, () -> innerMap.remove(repo_));\n Disposer.register(project_, () -> gitflowConfigUtilMap.remove(project_));\n }\n\n return instance;\n }\n\n GitflowConfigUtil(Project project_, GitRepository repo_){\n project = project_;\n repo = repo_;\n\n update();\n }\n\n public void update(){\n VirtualFile root = repo.getRoot();\n\n try{\n Future<Void> f = (Future<Void>) ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {\n @Override\n public void run() {\n try{\n masterBranch = GitConfigUtil.getValue(project, root, BRANCH_MASTER);\n developBranch = GitConfigUtil.getValue(project, root, BRANCH_DEVELOP);\n featurePrefix = GitConfigUtil.getValue(project,root,PREFIX_FEATURE);\n releasePrefix = GitConfigUtil.getValue(project,root,PREFIX_RELEASE);\n hotfixPrefix = GitConfigUtil.getValue(project,root,PREFIX_HOTFIX);\n bugfixPrefix = GitConfigUtil.getValue(project,root,PREFIX_BUGFIX);\n supportPrefix = GitConfigUtil.getValue(project,root,PREFIX_SUPPORT);\n versiontagPrefix = GitConfigUtil.getValue(project,root,PREFIX_VERSIONTAG);\n } catch (VcsException e) {\n NotifyUtil.notifyError(project, \"Config error\", e);\n }\n }});\n f.get();\n\n } catch (InterruptedException e) {\n e.printStackTrace();\n } catch (ExecutionException e) {\n e.printStackTrace();\n }\n }\n\n\n public String getFeatureNameFromBranch(String branchName){\n return branchName.substring(branchName.indexOf(featurePrefix)+featurePrefix.length(),branchName.length());\n }\n\n public String getReleaseNameFromBranch(String branchName){\n return branchName.substring(branchName.indexOf(releasePrefix) + releasePrefix.length(), branchName.length());\n }\n\n public String getHotfixNameFromBranch(String branchName){\n return branchName.substring(branchName.indexOf(hotfixPrefix) + hotfixPrefix.length(), branchName.length());\n }\n\n public String getBugfixNameFromBranch(String branchName){\n return branchName.substring(branchName.indexOf(bugfixPrefix)+bugfixPrefix.length(),branchName.length());\n }\n\n public String getRemoteNameFromBranch(String branchName){\n return branchName.substring(0,branchName.indexOf(\"/\"));\n }\n\n public void setMasterBranch(String branchName)\n {\n masterBranch = branchName;\n VirtualFile root = repo.getRoot();\n try {\n GitConfigUtil.setValue(project, root, BRANCH_MASTER, branchName);\n } catch (VcsException e) {\n NotifyUtil.notifyError(project, \"Config error\", e);\n }\n }\n\n public void setDevelopBranch(String branchName) {\n developBranch = branchName;\n VirtualFile root = repo.getRoot();\n try {\n GitConfigUtil.setValue(project, root, BRANCH_DEVELOP, branchName);\n } catch (VcsException e) {\n NotifyUtil.notifyError(project, \"Config error\", e);\n }\n }\n\n public void setReleasePrefix(String prefix) {\n releasePrefix = prefix;\n VirtualFile root = repo.getRoot();\n\n try {\n GitConfigUtil.setValue(project, root, PREFIX_RELEASE, prefix);\n } catch (VcsException e) {\n NotifyUtil.notifyError(project, \"Config error\", e);\n }\n }\n\n public void setFeaturePrefix(String prefix) {\n featurePrefix = prefix;\n VirtualFile root = repo.getRoot();\n\n try {\n GitConfigUtil.setValue(project, root, PREFIX_FEATURE, prefix);\n } catch (VcsException e) {\n NotifyUtil.notifyError(project, \"Config error\", e);\n }\n }\n\n public void setHotfixPrefix(String prefix) {\n hotfixPrefix = prefix;\n VirtualFile root = repo.getRoot();\n\n try {\n GitConfigUtil.setValue(project, root, PREFIX_HOTFIX, prefix);\n } catch (VcsException e) {\n NotifyUtil.notifyError(project, \"Config error\", e);\n }\n }\n\n public void setBugfixPrefix(String prefix) {\n bugfixPrefix = prefix;\n VirtualFile root = repo.getRoot();\n\n try {\n GitConfigUtil.setValue(project, root, PREFIX_BUGFIX, prefix);\n } catch (VcsException e) {\n NotifyUtil.notifyError(project, \"Config error\", e);\n }\n }\n\n public void setSupportPrefix(String prefix) {\n supportPrefix = prefix;\n VirtualFile root = repo.getRoot();\n\n try {\n GitConfigUtil.setValue(project, root, PREFIX_SUPPORT, prefix);\n } catch (VcsException e) {\n NotifyUtil.notifyError(project, \"Config error\", e);\n }\n }\n\n public void setVersionPrefix(String prefix) {\n versiontagPrefix = prefix;\n VirtualFile root = repo.getRoot();\n\n try {\n GitConfigUtil.setValue(project, root, PREFIX_VERSIONTAG, prefix);\n } catch (VcsException e) {\n NotifyUtil.notifyError(project, \"Config error\", e);\n }\n }\n\n // this still reads from config because it always runs from an action and never from the EDT\n public String getBaseBranch(String branchName){\n\n VirtualFile root = repo.getRoot();\n\n String baseBranch=null;\n try{\n baseBranch = GitConfigUtil.getValue(project, root, \"gitflow.branch.\"+branchName+\".base\");\n }\n catch (VcsException e) {\n NotifyUtil.notifyError(project, \"Config error\", e);\n }\n\n return baseBranch;\n }\n}", "@State(\n name = \"GitflowState\", storages = {\n @Storage(\n file = \"$APP_CONFIG$/GitflowState.xml\")\n})\npublic class GitflowState implements PersistentStateComponent<GitflowState> {\n\n private HashMap<String, String> taskBranches;\n\n\n public GitflowState() {\n taskBranches = new HashMap<String, String>();\n }\n\n\n public HashMap<String, String> getTaskBranches() {\n return taskBranches;\n }\n\n public void setTaskBranches(HashMap<String, String> taskBranches) {\n this.taskBranches = taskBranches;\n }\n\n @Nullable\n @Override\n public GitflowState getState() {\n return this;\n }\n\n @Override\n public void loadState(GitflowState state) {\n XmlSerializerUtil.copyBean(state, this);\n\n }\n\n public String getTaskBranch(Task task){\n return taskBranches.get(task.getId());\n }\n\n\n public void setTaskBranch(Task task, String branchName){\n taskBranches.put(task.getId(), branchName);\n }\n}", "public abstract class GitflowAction extends DumbAwareAction {\n\n private static final long VFM_REFRESH_DELAY = 750L;\n\n Project myProject;\n Gitflow myGitflow = ServiceManager.getService(Gitflow.class);\n ArrayList<GitRepository> repos = new ArrayList<GitRepository>();\n GitRepository myRepo;\n GitflowBranchUtil branchUtil;\n\n VirtualFileManager virtualFileMananger;\n\n GitflowAction( String actionName){ super(actionName); }\n\n GitflowAction(GitRepository repo, String actionName){\n super(actionName);\n myRepo = repo;\n\n branchUtil = GitflowBranchUtilManager.getBranchUtil(myRepo);\n }\n\n @Override\n public void actionPerformed(AnActionEvent e) {\n Project project = IDEAUtils.getActiveProject();\n\n // if repo isn't set explicitly, such as in the case of starting from keyboard shortcut, infer it\n if (myRepo == null){\n myRepo = GitBranchUtil.getCurrentRepository(project);\n }\n setup(project);\n }\n\n private void setup(Project project){\n myProject = project;\n virtualFileMananger = VirtualFileManager.getInstance();\n repos.add(myRepo);\n\n branchUtil= GitflowBranchUtilManager.getBranchUtil(myRepo);\n }\n\n public void runAction(final Project project, final String baseBranchName, final String branchName, @Nullable final Runnable callInAwtLater){\n setup(project);\n }\n\n //returns true if merge successful, false otherwise\n public boolean handleMerge(final Project project) {\n // FIXME As of 201.0 the async version of this method still doesn't make use of the callback, else we'd\n // simply use a FutureTask (which is a Runnable) and its get() method prior to launching the merge tool.\n virtualFileMananger.syncRefresh();\n\n try {\n long start, end = System.currentTimeMillis();\n do {\n start = end;\n // Hence this ugly hack, to let the time to intellij to catch up with the external changes made by the\n // CLI before being able to run the merge tool. Else the tool won't have the right state, won't display,\n // and the merge success Y/N dialog will appear directly! Anyway, in v193 500ms was sufficient,\n // but in v201 the right value seems to be in the [700-750]ms range (on the committer's machine).\n Thread.sleep(VFM_REFRESH_DELAY);\n\n GitflowActions.runMergeTool(project); // The window is modal, so we can measure how long it's opened.\n end = System.currentTimeMillis();\n } while(end - start < 1000L); // Additional hack: a window open <1s obviously didn't open, let's try again.\n\n myRepo.update();\n\n // And refreshing again so an onscreen file doesn't show in a conflicted state when the Y/N dialog show up.\n virtualFileMananger.syncRefresh();\n Thread.sleep(VFM_REFRESH_DELAY);\n\n return askUserForMergeSuccess(project);\n }\n catch (InterruptedException ignored) {\n return false;\n }\n }\n\n private static boolean askUserForMergeSuccess(Project myProject) {\n //if merge was completed successfully, finish the action\n //note that if it wasn't intellij is left in the \"merging state\", and git4idea provides no UI way to resolve it\n //merging can be done via intellij itself or any other util\n int answer = Messages.showYesNoDialog(myProject, \"Was the merge completed succesfully?\", \"Merge\", Messages.getQuestionIcon());\n if (answer==0){\n GitMerger gitMerger=new GitMerger(myProject);\n\n try {\n gitMerger.mergeCommit(gitMerger.getMergingRoots());\n } catch (VcsException e1) {\n NotifyUtil.notifyError(myProject, \"Error\", \"Error committing merge result\");\n e1.printStackTrace();\n }\n\n return true;\n }\n else{\n\n\t NotifyUtil.notifyInfo(myProject,\"Merge incomplete\",\"To manually complete the merge choose VCS > Git > Resolve Conflicts.\\n\" +\n\t\t\t \"Once done, commit the merged files.\\n\");\n return false;\n }\n\n\n }\n}", "public class StartBugfixAction extends AbstractStartAction {\n\n public StartBugfixAction() {\n super(\"Start Bugfix\");\n }\n public StartBugfixAction(GitRepository repo) {\n super(repo, \"Start Bugfix\");\n }\n\n @Override\n public void actionPerformed(AnActionEvent e) {\n super.actionPerformed(e);\n\n GitflowStartBugfixDialog dialog = new GitflowStartBugfixDialog(myProject, myRepo);\n dialog.show();\n\n if (dialog.getExitCode() != DialogWrapper.OK_EXIT_CODE) return;\n\n final String bugfixName = dialog.getNewBranchName();\n final String baseBranchName = dialog.getBaseBranchName();\n\n this.runAction(e.getProject(), baseBranchName, bugfixName, null);\n }\n\n @Override\n public void runAction(final Project project, final String baseBranchName, final String bugfixName, @Nullable final Runnable callInAwtLater){\n super.runAction(project, baseBranchName, bugfixName, callInAwtLater);\n\n new Task.Backgroundable(myProject, \"Starting bugfix \" + bugfixName, false) {\n @Override\n public void run(@NotNull ProgressIndicator indicator) {\n final GitCommandResult commandResult = createBugfixBranch(baseBranchName, bugfixName);\n if (callInAwtLater != null && commandResult.success()) {\n callInAwtLater.run();\n }\n }\n }.queue();\n }\n\n private GitCommandResult createBugfixBranch(String baseBranchName, String bugfixName) {\n GitflowErrorsListener errorListener = new GitflowErrorsListener(myProject);\n GitCommandResult result = myGitflow.startBugfix(myRepo, bugfixName, baseBranchName, errorListener);\n\n if (result.success()) {\n String startedBugfixMessage = String.format(\"A new branch '%s%s' was created, based on '%s'\", branchUtil.getPrefixBugfix(), bugfixName, baseBranchName);\n NotifyUtil.notifySuccess(myProject, bugfixName, startedBugfixMessage);\n } else {\n NotifyUtil.notifyError(myProject, \"Error\", \"Please have a look at the Version Control console for more details\");\n }\n\n myRepo.update();\n virtualFileMananger.asyncRefresh(null); //update editors\n return result;\n }\n}", "public class StartFeatureAction extends AbstractStartAction {\n\n public StartFeatureAction() {\n super(\"Start Feature\");\n }\n public StartFeatureAction(GitRepository repo) {\n super(repo, \"Start Feature\");\n }\n\n @Override\n public void actionPerformed(AnActionEvent e) {\n super.actionPerformed(e);\n\n GitflowStartFeatureDialog dialog = new GitflowStartFeatureDialog(myProject, myRepo);\n dialog.show();\n\n if (dialog.getExitCode() != DialogWrapper.OK_EXIT_CODE) return;\n\n final String featureName = dialog.getNewBranchName();\n final String baseBranchName = dialog.getBaseBranchName();\n\n this.runAction(e.getProject(), baseBranchName, featureName, null);\n }\n\n public void runAction(final Project project, final String baseBranchName, final String featureName, @Nullable final Runnable callInAwtLater){\n super.runAction(project, baseBranchName, featureName, callInAwtLater);\n\n new Task.Backgroundable(myProject, \"Starting feature \" + featureName, false) {\n @Override\n public void run(@NotNull ProgressIndicator indicator) {\n final GitCommandResult commandResult = createFeatureBranch(baseBranchName, featureName);\n if (callInAwtLater != null && commandResult.success()) {\n callInAwtLater.run();\n }\n }\n }.queue();\n }\n\n private GitCommandResult createFeatureBranch(String baseBranchName, String featureName) {\n GitflowErrorsListener errorListener = new GitflowErrorsListener(myProject);\n GitCommandResult result = myGitflow.startFeature(myRepo, featureName, baseBranchName, errorListener);\n\n if (result.success()) {\n String startedFeatureMessage = String.format(\"A new branch '%s%s' was created, based on '%s'\", branchUtil.getPrefixFeature(), featureName, baseBranchName);\n NotifyUtil.notifySuccess(myProject, featureName, startedFeatureMessage);\n } else {\n NotifyUtil.notifyError(myProject, \"Error\", \"Please have a look at the Version Control console for more details\");\n }\n\n myRepo.update();\n virtualFileMananger.asyncRefresh(null); //update editors\n return result;\n }\n}", "public class StartHotfixAction extends AbstractStartAction {\n\n public StartHotfixAction(GitRepository repo) {\n super(repo, \"Start Hotfix\");\n }\n\n public StartHotfixAction() {\n super(\"Start Hotfix\");\n }\n\n @Override\n public void actionPerformed(AnActionEvent e) {\n super.actionPerformed(e);\n\n GitflowStartHotfixDialog dialog = new GitflowStartHotfixDialog(myProject, myRepo);\n dialog.show();\n\n if (dialog.getExitCode() != DialogWrapper.OK_EXIT_CODE) return;\n\n final String hotfixName = dialog.getNewBranchName();\n final String baseBranchName = dialog.getBaseBranchName();\n\n this.runAction(e.getProject(), baseBranchName, hotfixName, null);\n }\n\n public void runAction(final Project project, final String baseBranchName, final String hotfixName, @Nullable final Runnable callInAwtLater){\n super.runAction(project, baseBranchName, hotfixName, callInAwtLater);\n\n new Task.Backgroundable(myProject, \"Starting hotfix \" + hotfixName, false) {\n @Override\n public void run(@NotNull ProgressIndicator indicator) {\n final GitCommandResult commandResult = createHotfixBranch(baseBranchName, hotfixName);\n if (callInAwtLater != null && commandResult.success()) {\n callInAwtLater.run();\n }\n }\n }.queue();\n }\n\n private GitCommandResult createHotfixBranch(String baseBranchName, String hotfixBranchName) {\n GitflowErrorsListener errorListener = new GitflowErrorsListener(myProject);\n GitCommandResult result = myGitflow.startHotfix(myRepo, hotfixBranchName, baseBranchName, errorListener);\n\n if (result.success()) {\n String startedHotfixMessage = String.format(\"A new hotfix '%s%s' was created, based on '%s'\",\n branchUtil.getPrefixHotfix(), hotfixBranchName, baseBranchName);\n NotifyUtil.notifySuccess(myProject, hotfixBranchName, startedHotfixMessage);\n } else {\n NotifyUtil.notifyError(myProject, \"Error\", \"Please have a look at the Version Control console for more details\");\n }\n\n myRepo.update();\n\n return result;\n }\n}" ]
import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.vcs.VcsTaskHandler; import com.intellij.tasks.LocalTask; import com.intellij.tasks.Task; import com.intellij.tasks.TaskManager; import com.intellij.tasks.impl.TaskManagerImpl; import com.intellij.tasks.ui.TaskDialogPanel; import git4idea.branch.GitBranchUtil; import git4idea.repo.GitRepository; import gitflow.GitflowBranchUtil; import gitflow.GitflowBranchUtilManager; import gitflow.GitflowConfigUtil; import gitflow.GitflowState; import gitflow.actions.GitflowAction; import gitflow.actions.StartBugfixAction; import gitflow.actions.StartFeatureAction; import gitflow.actions.StartHotfixAction; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.util.Collections; import static com.intellij.openapi.vcs.VcsTaskHandler.TaskInfo;
package gitflow.ui; public class GitflowOpenTaskPanel extends TaskDialogPanel implements ItemListener { private JRadioButton noActionRadioButton; private JRadioButton startFeatureRadioButton; private JRadioButton startHotfixRadioButton; private JTextField featureName; private JComboBox featureBaseBranch; private JTextField hotfixName; private JPanel myPanel; private JComboBox hotfixBaseBranch; private JRadioButton startBugfixRadioButton; private JTextField bugfixName; private JComboBox bugfixBaseBranch; private Project myProject; private GitRepository myRepo; private GitflowBranchUtil gitflowBranchUtil; private TaskManagerImpl myTaskManager; private VcsTaskHandler myVcsTaskHandler; private LocalTask myPreviousTask; private Task currentTask; private GitflowState gitflowState; public GitflowOpenTaskPanel(Project project, Task task, GitRepository repo){ myProject = project; currentTask = task; myRepo = repo; myTaskManager = (TaskManagerImpl) TaskManager.getManager(project); myPreviousTask = myTaskManager.getActiveTask(); VcsTaskHandler[] vcsTaskHAndlers = VcsTaskHandler.getAllHandlers(project); if (vcsTaskHAndlers.length > 0){ //todo handle case of multiple vcs handlers myVcsTaskHandler = vcsTaskHAndlers[0]; } gitflowState = ServiceManager.getService(GitflowState.class); gitflowBranchUtil = GitflowBranchUtilManager.getBranchUtil(myRepo); GitflowConfigUtil gitflowConfigUtil = GitflowConfigUtil.getInstance(project, myRepo); String defaultFeatureBranch = gitflowConfigUtil.developBranch; featureBaseBranch.setModel(gitflowBranchUtil.createBranchComboModel(defaultFeatureBranch)); String defaultHotfixBranch = gitflowConfigUtil.masterBranch; hotfixBaseBranch.setModel(gitflowBranchUtil.createBranchComboModel(defaultHotfixBranch)); String defaultBugfixBranch = gitflowConfigUtil.developBranch; bugfixBaseBranch.setModel(gitflowBranchUtil.createBranchComboModel(defaultBugfixBranch)); myRepo = GitBranchUtil.getCurrentRepository(project); String branchName = myVcsTaskHandler != null ? myVcsTaskHandler.cleanUpBranchName(myTaskManager.constructDefaultBranchName(task)) : myTaskManager.suggestBranchName(task); featureName.setText(branchName); featureName.setEditable(false); featureName.setEnabled(false); hotfixName.setText(branchName); hotfixName.setEditable(false); hotfixName.setEnabled(false); bugfixName.setText(branchName); bugfixName.setEditable(false); bugfixName.setEnabled(false); featureBaseBranch.setEnabled(false); hotfixBaseBranch.setEnabled(false); bugfixBaseBranch.setEnabled(false); //add listeners noActionRadioButton.addItemListener(this); startFeatureRadioButton.addItemListener(this); startHotfixRadioButton.addItemListener(this); startBugfixRadioButton.addItemListener(this); } @NotNull @Override public JComponent getPanel() { return myPanel; } @Override public void commit() { final GitflowBranchUtil.ComboEntry selectedFeatureBaseBranch = (GitflowBranchUtil.ComboEntry) featureBaseBranch.getModel().getSelectedItem(); final GitflowBranchUtil.ComboEntry selectedHotfixBaseBranch = (GitflowBranchUtil.ComboEntry) hotfixBaseBranch.getModel().getSelectedItem(); final GitflowBranchUtil.ComboEntry selectedBugfixBaseBranch = (GitflowBranchUtil.ComboEntry) bugfixBaseBranch.getModel().getSelectedItem(); GitflowConfigUtil gitflowConfigUtil = GitflowConfigUtil.getInstance(myProject, myRepo); if (startFeatureRadioButton.isSelected()) { final String branchName = gitflowConfigUtil.featurePrefix + featureName.getText(); attachTaskAndRunAction(new StartFeatureAction(myRepo), selectedFeatureBaseBranch.getBranchName(), branchName); } else if (startHotfixRadioButton.isSelected()) { final String branchName = gitflowConfigUtil.hotfixPrefix + hotfixName.getText(); attachTaskAndRunAction(new StartHotfixAction(myRepo), selectedHotfixBaseBranch.getBranchName(), branchName); } else if (startBugfixRadioButton.isSelected()) { final String branchName = gitflowConfigUtil.bugfixPrefix + bugfixName.getText(); attachTaskAndRunAction(new StartBugfixAction(myRepo), selectedBugfixBaseBranch.getBranchName(), branchName); } } /** * @param action instance of GitflowAction * @param baseBranchName Branch name of the branch the new one is based on * @param fullBranchName Branch name with feature/hotfix/bugfix prefix for saving to task */
private void attachTaskAndRunAction(GitflowAction action, String baseBranchName, final String fullBranchName) {
4
kontalk/desktopclient-java
src/main/java/org/kontalk/view/ContactDetails.java
[ "public final class JID {\n private static final Logger LOGGER = Logger.getLogger(JID.class.getName());\n\n static {\n // good to know. For working JID validation\n SimpleXmppStringprep.setup();\n }\n\n private final String mLocal; // escaped!\n private final String mDomain;\n private final String mResource;\n private final boolean mValid;\n\n private JID(String local, String domain, String resource) {\n mLocal = local;\n mDomain = domain;\n mResource = resource;\n\n mValid = !mLocal.isEmpty() && !mDomain.isEmpty()\n // NOTE: domain check could be stronger - compliant with RFC 6122, but\n // server does not accept most special characters\n // NOTE: resource not checked\n && JidUtil.isTypicalValidEntityBareJid(\n XmppStringUtils.completeJidFrom(mLocal, mDomain));\n }\n\n /** Return unescaped local part. */\n public String local() {\n return XmppStringUtils.unescapeLocalpart(mLocal);\n }\n\n public String domain() {\n return mDomain;\n }\n\n /** Return JID as escaped string. */\n public String string() {\n return XmppStringUtils.completeJidFrom(mLocal, mDomain, mResource);\n }\n\n public String asUnescapedString() {\n return XmppStringUtils.completeJidFrom(this.local(), mDomain, mResource);\n }\n\n public boolean isValid() {\n return mValid;\n }\n\n public boolean isHash() {\n return mLocal.matches(\"[0-9a-f]{40}\");\n }\n\n public boolean isFull() {\n return !mResource.isEmpty();\n }\n\n public JID toBare() {\n return new JID(mLocal, mDomain, \"\");\n }\n\n /** To invalid(!) domain JID. */\n public JID toDomain() {\n return new JID(\"\", mDomain, \"\");\n }\n\n public BareJid toBareSmack() {\n try {\n return JidCreate.bareFrom(this.string());\n } catch (XmppStringprepException ex) {\n LOGGER.log(Level.WARNING, \"could not convert to smack\", ex);\n throw new RuntimeException(\"You didn't check isValid(), idiot!\");\n }\n }\n\n public Jid toSmack() {\n try {\n return JidCreate.from(this.string());\n } catch (XmppStringprepException ex) {\n LOGGER.log(Level.WARNING, \"could not convert to smack\", ex);\n throw new RuntimeException(\"Not even a simple Jid?\");\n }\n }\n\n /**\n * Comparing only bare JIDs.\n * Case-insensitive.\n */\n @Override\n public final boolean equals(Object o) {\n if (o == this)\n return true;\n\n if (!(o instanceof JID))\n return false;\n\n JID oJID = (JID) o;\n return mLocal.equalsIgnoreCase(oJID.mLocal) &&\n mDomain.equalsIgnoreCase(oJID.mDomain);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(mLocal, mDomain);\n }\n\n /** Use this only for debugging and otherwise string() instead! */\n @Override\n public String toString() {\n return \"'\"+this.string()+\"'\";\n }\n\n public static JID full(String jid) {\n jid = StringUtils.defaultString(jid);\n return escape(XmppStringUtils.parseLocalpart(jid),\n XmppStringUtils.parseDomain(jid),\n XmppStringUtils.parseResource(jid));\n }\n\n public static JID bare(String jid) {\n jid = StringUtils.defaultString(jid);\n return escape(XmppStringUtils.parseLocalpart(jid), XmppStringUtils.parseDomain(jid), \"\");\n }\n\n public static JID fromSmack(Jid jid) {\n Localpart localpart = jid.getLocalpartOrNull();\n return new JID(localpart != null ? localpart.toString() : \"\",\n jid.getDomain().toString(),\n jid.getResourceOrEmpty().toString());\n }\n\n public static JID bare(String local, String domain) {\n return escape(local, domain, \"\");\n }\n\n private static JID escape(String local, String domain, String resource) {\n return new JID(XmppStringUtils.escapeLocalpart(local), domain, resource);\n }\n\n public static JID deleted(int id) {\n return new JID(\"\", Integer.toString(id), \"\");\n }\n}", "public final class Contact extends Observable implements Searchable {\n private static final Logger LOGGER = Logger.getLogger(Contact.class.getName());\n\n /**\n * Online status of one contact.\n */\n public enum Online {UNKNOWN, YES, NO, ERROR}\n\n /**\n * XMPP subscription status in roster.\n */\n public enum Subscription {\n UNKNOWN, PENDING, SUBSCRIBED, UNSUBSCRIBED\n }\n\n public enum ViewChange {\n JID, NAME, LAST_SEEN, ONLINE_STATUS, KEY, BLOCKING, SUBSCRIPTION, AVATAR, DELETED\n }\n\n public static final String TABLE = \"user\";\n public static final String COL_JID = \"jid\";\n public static final String COL_NAME = \"name\";\n public static final String COL_STAT = \"status\";\n public static final String COL_LAST_SEEN = \"last_seen\";\n public static final String COL_ENCR = \"encrypted\";\n public static final String COL_PUB_KEY = \"public_key\";\n public static final String COL_KEY_FP = \"key_fingerprint\";\n public static final String COL_AVATAR_ID = \"avatar_id\";\n public static final String SCHEMA = \"(\" +\n Database.SQL_ID +\n COL_JID + \" TEXT NOT NULL UNIQUE, \" +\n COL_NAME + \" TEXT, \" +\n COL_STAT + \" TEXT, \" +\n COL_LAST_SEEN + \" INTEGER, \" +\n // boolean, send messages encrypted?\n COL_ENCR + \" INTEGER NOT NULL, \" +\n COL_PUB_KEY + \" TEXT, \" +\n COL_KEY_FP + \" TEXT,\" +\n COL_AVATAR_ID + \" TEXT\" +\n \")\";\n\n private final int mID;\n private JID mJID;\n private String mName;\n private String mStatus = \"\";\n private Date mLastSeen = null;\n private Online mOnline = Online.UNKNOWN; // not in database\n private boolean mEncrypted = true;\n private String mKey = \"\";\n private String mFingerprint = \"\";\n private boolean mBlocked = false;\n private Subscription mSubStatus = Subscription.UNKNOWN; // not in database\n //private ItemType mType;\n private Avatar.DefaultAvatar mAvatar = null;\n private Avatar.CustomAvatar mCustomAvatar = null;\n private boolean mSaveOnShutdown = false;\n\n // new contact (eg from roster)\n Contact(JID jid, String name) {\n mJID = jid;\n mName = name;\n\n // insert\n List<Object> values = Arrays.asList(\n mJID,\n mName,\n mStatus,\n mLastSeen,\n mEncrypted,\n null, // key\n null, // fingerprint\n null); // avatar id\n mID = Model.database().execInsert(TABLE, values);\n if (mID < 1)\n LOGGER.log(Level.WARNING, \"could not insert contact\");\n }\n\n // loading from database\n private Contact(\n int id,\n JID jid,\n String name,\n String status,\n Optional<Date> lastSeen,\n boolean encrypted,\n String publicKey,\n String fingerprint,\n String avatarID) {\n mID = id;\n mJID = jid;\n mName = name;\n mStatus = status;\n mLastSeen = lastSeen.orElse(null);\n mEncrypted = encrypted;\n mKey = publicKey;\n mFingerprint = fingerprint.toLowerCase();\n mAvatar = avatarID.isEmpty() ?\n null :\n Avatar.DefaultAvatar.load(avatarID).orElse(null);\n mCustomAvatar = Avatar.CustomAvatar.load(mID).orElse(null);\n }\n\n public JID getJID() {\n return mJID;\n }\n\n void setJID(JID jid) {\n if (jid.equals(mJID))\n return;\n\n if (!jid.isValid()) {\n LOGGER.warning(\"jid is not valid: \"+jid);\n return;\n }\n\n mJID = jid;\n this.save();\n this.changed(ViewChange.JID);\n }\n\n public int getID() {\n return mID;\n }\n\n public String getName() {\n return mName;\n }\n\n public void setName(String name) {\n if (name.equals(mName))\n return;\n\n mName = name;\n this.save();\n\n this.changed(ViewChange.NAME);\n }\n\n public String getStatus() {\n return mStatus;\n }\n\n public Optional<Date> getLastSeen() {\n return Optional.ofNullable(mLastSeen);\n }\n\n public void setLastSeen(Date lastSeen, String status) {\n if (!lastSeen.equals(mLastSeen)) {\n mLastSeen = lastSeen;\n mSaveOnShutdown = true;\n this.changed(ViewChange.LAST_SEEN);\n }\n if (!status.isEmpty() && !status.equals(mStatus)) {\n mStatus = status;\n mSaveOnShutdown = true;\n // notify on status change not required\n }\n }\n\n public boolean getEncrypted() {\n return mEncrypted;\n }\n\n public void setEncrypted(boolean encrypted) {\n if (encrypted == mEncrypted)\n return;\n\n mEncrypted = encrypted;\n this.save();\n }\n\n public Online getOnline() {\n return this.mOnline;\n }\n\n public void setStatusText(String status) {\n if (mStatus.equals(status))\n return;\n\n mStatus = status;\n mSaveOnShutdown = true;\n // notify on status change not required\n }\n\n public void setOnlineStatus(Online onlineStatus) {\n if (onlineStatus == mOnline)\n return;\n\n if (onlineStatus == Online.YES ||\n (onlineStatus == Online.NO && mOnline == Online.YES)) {\n mLastSeen = new Date();\n mSaveOnShutdown = true;\n // notify on last_seen change not required here\n }\n\n mOnline = onlineStatus;\n this.changed(ViewChange.ONLINE_STATUS);\n }\n\n public byte[] getKey() {\n return EncodingUtils.base64ToBytes(mKey);\n }\n\n public boolean hasKey() {\n return !mKey.isEmpty();\n }\n\n public String getFingerprint() {\n return mFingerprint;\n }\n\n public void setKey(byte[] rawKey, String fingerprint) {\n if (!mKey.isEmpty())\n LOGGER.info(\"overwriting public key of contact: \"+this);\n\n mKey = EncodingUtils.bytesToBase64(rawKey);\n mFingerprint = fingerprint.toLowerCase();\n this.save();\n this.changed(ViewChange.KEY);\n }\n\n public boolean isBlocked() {\n return mBlocked;\n }\n\n public void setBlocked(boolean blocked) {\n mBlocked = blocked;\n this.changed(ViewChange.BLOCKING);\n }\n\n public Subscription getSubScription() {\n return mSubStatus;\n }\n\n public void setSubscriptionStatus(Subscription status) {\n if (status == mSubStatus)\n return;\n\n mSubStatus = status;\n this.changed(ViewChange.SUBSCRIPTION);\n }\n\n public Optional<Avatar> getAvatar() {\n return Optional.ofNullable(mAvatar);\n }\n\n /** Get custom or downloaded avatar. */\n public Optional<Avatar> getDisplayAvatar() {\n return mCustomAvatar != null ?\n Optional.of(mCustomAvatar) :\n Optional.ofNullable(mAvatar);\n }\n\n public void setAvatar(Avatar.DefaultAvatar avatar) {\n // delete old\n if (mAvatar != null)\n mAvatar.delete();\n\n // set new\n mAvatar = avatar;\n this.save();\n\n if (mCustomAvatar == null)\n this.changed(ViewChange.AVATAR);\n }\n\n public void deleteAvatar() {\n if (mAvatar == null)\n return;\n\n mAvatar.delete();\n mAvatar = null;\n this.save();\n\n this.changed(ViewChange.AVATAR);\n }\n\n public void setCustomAvatar(Avatar.CustomAvatar avatar) {\n // overwrite file!\n mCustomAvatar = avatar;\n\n this.changed(ViewChange.AVATAR);\n }\n\n public boolean hasCustomAvatarSet() {\n return mCustomAvatar != null;\n }\n\n public void deleteCustomAvatar() {\n if (mCustomAvatar == null)\n return;\n\n mCustomAvatar.delete();\n mCustomAvatar = null;\n\n this.changed(ViewChange.AVATAR);\n }\n\n public boolean isMe() {\n return mJID.isValid() && mJID.equals(Model.getUserJID());\n }\n\n public boolean isKontalkUser(){\n return XMPPUtils.isKontalkJID(mJID);\n }\n\n /**\n * 'Delete' this contact: faked by resetting all values.\n */\n void setDeleted() {\n LOGGER.config(\"contact: \"+this);\n mJID = JID.deleted(mID);\n mName = \"\";\n mStatus = \"\";\n mLastSeen = null;\n mEncrypted = false;\n mKey = \"\";\n mFingerprint = \"\";\n if (mAvatar != null)\n mAvatar.delete();\n mAvatar = null;\n\n this.save();\n this.changed(ViewChange.DELETED);\n }\n\n public boolean isDeleted() {\n return mJID.string().equals(Integer.toString(mID));\n }\n\n void onShutDown() {\n if (!this.isDeleted() && mSaveOnShutdown)\n this.save();\n }\n\n private void save() {\n Map<String, Object> set = new HashMap<>();\n set.put(COL_JID, mJID);\n set.put(COL_NAME, mName);\n set.put(COL_STAT, mStatus);\n set.put(COL_LAST_SEEN, mLastSeen);\n set.put(COL_ENCR, mEncrypted);\n set.put(COL_PUB_KEY, Database.setString(mKey));\n set.put(COL_KEY_FP, Database.setString(mFingerprint));\n set.put(COL_AVATAR_ID, Database.setString(mAvatar != null ? mAvatar.getID() : \"\"));\n Model.database().execUpdate(TABLE, set, mID);\n\n mSaveOnShutdown = false;\n }\n\n private void changed(ViewChange change) {\n this.setChanged();\n this.notifyObservers(change);\n }\n\n @Override\n public boolean contains(String search) {\n return this.getName().toLowerCase().contains(search) ||\n this.getJID().string().toLowerCase().contains(search);\n }\n\n @Override\n public final boolean equals(Object o) {\n if (o == this)\n return true;\n\n if (!(o instanceof Contact))\n return false;\n\n return mID == ((Contact) o).mID;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(mID);\n }\n\n @Override\n public String toString() {\n return \"C:id=\"+mID+\",jid=\"+mJID+\",name=\"+mName+\",fp=\"+mFingerprint\n +\",subsc=\"+mSubStatus;\n }\n\n static Contact load(ResultSet rs) throws SQLException {\n int id = rs.getInt(\"_id\");\n JID jid = JID.bare(rs.getString(Contact.COL_JID));\n\n String name = rs.getString(Contact.COL_NAME);\n String status = rs.getString(Contact.COL_STAT);\n long l = rs.getLong(Contact.COL_LAST_SEEN);\n Date lastSeen = l == 0 ? null : new Date(l);\n boolean encr = rs.getBoolean(Contact.COL_ENCR);\n String key = Database.getString(rs, Contact.COL_PUB_KEY);\n String fp = Database.getString(rs, Contact.COL_KEY_FP);\n String avatarID = Database.getString(rs, Contact.COL_AVATAR_ID);\n\n return new Contact(id, jid, name, status,\n Optional.ofNullable(lastSeen), encr, key, fp, avatarID);\n }\n}", "public class Tr {\n private static final Logger LOGGER = Logger.getLogger(Tr.class.getName());\n\n private static final String DEFAULT_LANG = \"en\";\n private static final String I18N_DIR = \"i18n/\";\n private static final String STRING_FILE = \"strings\";\n private static final String PROP_EXT = \".properties\";\n\n private static final String WIKI_BASE = \"https://github.com/kontalk/desktopclient-java/wiki\";\n private static final String WIKI_HOME = \"Home\";\n private static final List<String> WIKI_LANGS = Arrays.asList(\"de\");\n\n /** Map default (English) strings to translated strings. **/\n private static Map<String, String> TR_MAP = null;\n\n /**\n * Translate string used in user interface.\n * Spaces at beginning or end of string not supported!\n * @param s string that wants to be translated (in English)\n * @return translation of input string (depending on platform language)\n */\n public static String tr(String s) {\n if (TR_MAP == null || !TR_MAP.containsKey(s))\n return s;\n return TR_MAP.get(s);\n }\n\n public static void init() {\n // get language\n String lang = Locale.getDefault().getLanguage();\n // for testing\n //String lang = new Locale(\"zh\").getLanguage();\n if (lang.equals(DEFAULT_LANG)) {\n return;\n }\n\n LOGGER.info(\"Setting language: \"+lang);\n\n // load string keys file\n String path = I18N_DIR + STRING_FILE + PROP_EXT;\n PropertiesConfiguration stringKeys;\n try {\n stringKeys = new PropertiesConfiguration(ClassLoader.getSystemResource(path));\n } catch (ConfigurationException ex) {\n LOGGER.log(Level.WARNING, \"can't load string key file\", ex);\n return;\n }\n\n // load translation file\n path = I18N_DIR + STRING_FILE + \"_\" + lang + PROP_EXT;\n URL url = ClassLoader.getSystemResource(path);\n if (url == null) {\n LOGGER.info(\"can't find translation file: \"+path);\n return;\n }\n PropertiesConfiguration tr = new PropertiesConfiguration();\n tr.setEncoding(\"UTF-8\");\n try {\n tr.load(url);\n } catch (ConfigurationException ex) {\n LOGGER.log(Level.WARNING, \"can't load translation file\", ex);\n return;\n }\n\n TR_MAP = new HashMap<>();\n Iterator<String> it = tr.getKeys();\n while (it.hasNext()) {\n String k = it.next();\n if (!stringKeys.containsKey(k)) {\n LOGGER.warning(\"key in translation but not in key file: \"+k);\n continue;\n }\n TR_MAP.put(stringKeys.getString(k), tr.getString(k));\n }\n }\n\n public static String getLocalizedWikiLink() {\n String lang = Locale.getDefault().getLanguage();\n if (WIKI_LANGS.contains(lang)) {\n // damn URI decoding\n return WIKI_BASE + \"/%5B\" + lang + \"%5D-\" + WIKI_HOME;\n }\n return WIKI_BASE;\n }\n}", "static class AvatarImg {\n\n final BufferedImage image;\n final boolean isFallback;\n\n AvatarImg(BufferedImage img, boolean fallback) {\n this.image = img;\n this.isFallback = fallback;\n }\n}", "static class LabelTextField extends WebTextField {\n\n LabelTextField(int columns, Component focusGainer) {\n this(\"\", null, false, columns, focusGainer);\n }\n\n LabelTextField(int maxTextLength, int columns, final Component focusGainer) {\n this(\"\", maxTextLength, true, columns, focusGainer);\n }\n\n LabelTextField(String text, int maxTextLength, boolean editable,\n int columns, final Component focusGainer) {\n this(text, new TextLimitDocument(maxTextLength), editable, columns, focusGainer);\n }\n\n LabelTextField(String text, Document doc, boolean editable,\n int columns, final Component focusGainer) {\n super(doc, text, columns);\n\n this.setEditable(editable);\n this.setFocusable(true);\n if (editable)\n this.setTrailingComponent(new WebImage(Utils.getIcon(\"ic_ui_edit.png\")));\n else\n this.setBackground(null);\n\n // edit mode needs more height than label mode\n this.setMinimumHeight(30);\n\n this.setHideInputPromptOnFocus(false);\n this.addFocusListener(new FocusListener() {\n @Override\n public void focusGained(FocusEvent e) {\n LabelTextField.this.switchToEditMode();\n }\n @Override\n public void focusLost(FocusEvent e) {\n LabelTextField.this.onFocusLost();\n LabelTextField.this.switchToLabelMode();\n }\n });\n this.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n focusGainer.requestFocus();\n }\n });\n\n this.switchToLabelMode();\n }\n\n private void switchToEditMode() {\n String text = this.editText();\n this.setInputPrompt(text);\n this.setText(text);\n this.setCaretPosition(0); // \"scroll\" back\n this.setDrawBorder(true);\n Optional.ofNullable(this.getTrailingComponent()).ifPresent(c -> c.setVisible(false));\n }\n\n private void switchToLabelMode() {\n this.setText(this.labelText());\n this.setCaretPosition(0); // \"scroll\" back\n // layout problem here\n this.setDrawBorder(false);\n Optional.ofNullable(this.getTrailingComponent()).ifPresent(c -> c.setVisible(true));\n }\n\n String labelText() {\n return this.getText();\n }\n\n String editText() {\n return this.getText();\n }\n\n void onFocusLost() {}\n}" ]
import javax.swing.Box; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.util.HashMap; import java.util.Map; import java.util.Observable; import java.util.Optional; import com.alee.extended.layout.FormLayout; import com.alee.extended.panel.GroupPanel; import com.alee.extended.panel.GroupingType; import com.alee.laf.button.WebButton; import com.alee.laf.checkbox.WebCheckBox; import com.alee.laf.label.WebLabel; import com.alee.laf.optionpane.WebOptionPane; import com.alee.laf.panel.WebPanel; import com.alee.laf.separator.WebSeparator; import com.alee.laf.text.WebTextArea; import com.alee.laf.text.WebTextField; import com.alee.managers.tooltip.TooltipManager; import org.kontalk.misc.JID; import org.kontalk.model.Contact; import org.kontalk.util.Tr; import org.kontalk.view.AvatarLoader.AvatarImg; import org.kontalk.view.ComponentUtils.LabelTextField;
/* * Kontalk Java client * Copyright (C) 2016 Kontalk Devteam <devteam@kontalk.org> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kontalk.view; /** * Show and edit contact details. * * @author Alexander Bikadorov {@literal <bikaejkb@mail.tu-berlin.de>} */ final class ContactDetails extends WebPanel implements ObserverTrait { private static final Map<Contact, ContactDetails> CACHE = new HashMap<>(); private final View mView; private final Contact mContact; private final ComponentUtils.EditableAvatarImage mAvatarImage; private final WebTextField mNameField; private final WebLabel mSubscrStatus; private final WebButton mSubscrButton; private final WebLabel mKeyStatus; private final WebLabel mFPLabel; private final WebButton mUpdateButton; private final WebTextArea mFPArea; private final WebCheckBox mEncryptionBox; private ContactDetails(View view, Contact contact) { mView = view; mContact = contact; GroupPanel groupPanel = new GroupPanel(View.GAP_BIG, false); groupPanel.setMargin(View.MARGIN_BIG);
groupPanel.add(new WebLabel(Tr.tr("Contact details")).setBoldFont());
2
larusba/doc2graph
neo4j-json/src/main/java/org/neo4j/helpers/json/document/impl/DocumentGrapherRecursive.java
[ "public interface DocumentGrapher {\n\n\t/**\n\t * Create and re-use node and relations\n\t * @param key\n\t * @param document\n\t * @return id of root node\n\t */\n\t@SuppressWarnings(\"rawtypes\")\n\tNode upsertDocument(String key, Map document);\n\t\n\t/**\n\t * Remove non shared node and relationships regarding input document key\n\t * @param key\n\t * @return\n\t */\n\tlong deleteDocument(String key);\n}", "public interface DocumentId {\n\n\t/**\n\t * Key is the attribute's name\n\t * Value is the attribute's value\n\t * that compose the identify\n\t * @return\n\t */\n\tMap<String, String> getFields();\n\t\n\t/**\n\t * Buil a cypher filter condition\n\t * ES: filed1: 'aaa', field2: 'bbb'\n\t * @return\n\t */\n\tString toCypherFilter();\n\t\n\t/**\n\t * Equals and hashCode must be implemented\n\t */\n}", "public interface DocumentIdBuilder {\n\n\t/**\n\t * Build documentId from map (extract from json)\n\t * documentId refers to root document (first level)\n\t * @param obj\n\t * @return\n\t */\n\tDocumentId buildId(Map<String,Object> obj);\n\t\n\t/**\n\t * Configure the builder with parameters\n\t * @param configuration\n\t */\n\tvoid init(Map<String, String> configuration);\n}", "public interface DocumentLabelBuilder {\n\n\t/**\n\t * Choose label for the root object in map\n\t * @param obj\n\t * @return\n\t */\n\tLabel buildLabel(Map<String, Object> obj);\n\n\t/**\n\t * Set default label if cannot be assigned at runtime\n\t * @param defaultLabel\n\t */\n\tvoid setDefaultLabel(String defaultLabel);\n}", "public interface DocumentRelationBuilder {\n\n\t/**\n\t * Create or update relationship between parent and child node\n\t * @param parent\n\t * @param child\n\t * @param context\n\t * @return\n\t */\n\tRelationship buildRelation(Node parent, Node child, DocumentRelationContext context);\n\t\n\t/**\n\t * Remove all relationships regarding document context\n\t * @param context\n\t * @return the 'orphan' nodes\n\t */\n\tSet<Node> deleteRelations(DocumentRelationContext context);\n\n\tvoid setDb(GraphDatabaseService db);\n\n\tvoid setLog(Log log);\n}", "public class DocumentGrapherExecutionContext {\n\n\tprivate GraphDatabaseService db;\n\tprivate Log log;\n\tprivate DocumentIdBuilder documentIdBuilder;\n\tprivate DocumentRelationBuilder documentRelationBuilder;\n\tprivate DocumentLabelBuilder documentLabelBuilder;\n\tprivate String rootNodeKeyProperty;\n\t/**\n\t * True if the system log the discard event\n\t */\n\tprivate boolean logDiscard;\n\n\t/**\n\t * @return the rootNodeKeyProperty\n\t */\n\tpublic String getRootNodeKeyProperty() {\n\t\treturn rootNodeKeyProperty;\n\t}\n\n\t/**\n\t * @param rootNodeKeyProperty\n\t * the rootNodeKeyProperty to set\n\t */\n\tpublic void setRootNodeKeyProperty(String rootNodeKeyProperty) {\n\t\tthis.rootNodeKeyProperty = rootNodeKeyProperty;\n\t}\n\n\t/**\n\t * @return the documentLabelBuilder\n\t */\n\tpublic DocumentLabelBuilder getDocumentLabelBuilder() {\n\t\treturn documentLabelBuilder;\n\t}\n\n\t/**\n\t * @param documentLabelBuilder\n\t * the documentLabelBuilder to set\n\t */\n\tpublic void setDocumentLabelBuilder(DocumentLabelBuilder documentLabelBuilder) {\n\t\tthis.documentLabelBuilder = documentLabelBuilder;\n\t}\n\n\t/**\n\t * @return the db\n\t */\n\tpublic GraphDatabaseService getDb() {\n\t\treturn db;\n\t}\n\n\t/**\n\t * @param db\n\t * the db to set\n\t */\n\tpublic void setDb(GraphDatabaseService db) {\n\t\tthis.db = db;\n\t}\n\n\t/**\n\t * @return the log\n\t */\n\tpublic Log getLog() {\n\t\treturn log;\n\t}\n\n\t/**\n\t * @param log\n\t * the log to set\n\t */\n\tpublic void setLog(Log log) {\n\t\tthis.log = log;\n\t}\n\n\t/**\n\t * @return the documentIdBuilder\n\t */\n\tpublic DocumentIdBuilder getDocumentIdBuilder() {\n\t\treturn documentIdBuilder;\n\t}\n\n\t/**\n\t * @param documentIdBuilder\n\t * the documentIdBuilder to set\n\t */\n\tpublic void setDocumentIdBuilder(DocumentIdBuilder documentIdBuilder) {\n\t\tthis.documentIdBuilder = documentIdBuilder;\n\t}\n\n\t/**\n\t * @return the documentRelationBuilder\n\t */\n\tpublic DocumentRelationBuilder getDocumentRelationBuilder() {\n\t\treturn documentRelationBuilder;\n\t}\n\n\t/**\n\t * @param documentRelationBuilder\n\t * the documentRelationBuilder to set\n\t */\n\tpublic void setDocumentRelationBuilder(DocumentRelationBuilder documentRelationBuilder) {\n\t\tthis.documentRelationBuilder = documentRelationBuilder;\n\t}\n\n\tpublic boolean isLogDiscard() {\n\t\treturn logDiscard;\n\t}\n\n\tpublic void setLogDiscard(boolean logDiscard) {\n\t\tthis.logDiscard = logDiscard;\n\t}\n\t\n}", "public class DocumentRelationContext {\n\n\tprivate String documentKey;\n\n\t/**\n\t * @return the documentKey\n\t */\n\tpublic String getDocumentKey() {\n\t\treturn documentKey;\n\t}\n\n\t/**\n\t * @param documentKey\n\t * the documentKey to set\n\t */\n\tpublic void setDocumentKey(String documentKey) {\n\t\tthis.documentKey = documentKey;\n\t}\n\n}" ]
import org.neo4j.helpers.json.document.DocumentId; import org.neo4j.helpers.json.document.DocumentIdBuilder; import org.neo4j.helpers.json.document.DocumentLabelBuilder; import org.neo4j.helpers.json.document.DocumentRelationBuilder; import org.neo4j.helpers.json.document.context.DocumentGrapherExecutionContext; import org.neo4j.helpers.json.document.context.DocumentRelationContext; import org.neo4j.logging.Log; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Label; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Result; import org.neo4j.helpers.json.document.DocumentGrapher;
/** * Copyright (c) 2017 LARUS Business Automation [http://www.larus-ba.it] * <p> * This file is part of the "LARUS Integration Framework for Neo4j". * <p> * The "LARUS Integration Framework for Neo4j" is licensed * under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.neo4j.helpers.json.document.impl; /** * Recursive implementation of logic to transform document into graph (tree) * @author Omar Rampado * */ public class DocumentGrapherRecursive implements DocumentGrapher { private GraphDatabaseService db; private Log log; private DocumentIdBuilder documentIdBuilder; private DocumentRelationBuilder documentRelationBuilder;
private DocumentLabelBuilder documentLabelBuilder;
3
lesstif/jira-rest-client
src/test/java/com/lesstif/jira/services/IssueTest.java
[ "public class JsonPrettyString {\n\t\n\tfinal public String toPrettyJsonString() {\n\t\tObjectMapper mapper = new ObjectMapper();\n\n\t\tmapper.configure(SerializationFeature.INDENT_OUTPUT, true);\n\t\t\n\t\tStringWriter sw = new StringWriter();\n\t\ttry {\n\t\t\tmapper.writeValue(sw, this);\n\t\t} catch (IOException e) {\n\t\t\treturn toString();\n\t\t}\n\t\t\n\t\treturn sw.toString();\n\t}\n\t\n\t/**\n\t * Map to Pretty Json String\n\t * \n\t * @param map map data\n\t * @return Json String \n\t */\n\tpublic static String mapToPrettyJsonString(Map<String, Object> map) {\n\t ObjectMapper mapper = new ObjectMapper();\n \n mapper.configure(SerializationFeature.INDENT_OUTPUT, true);\n \n String jsonStr = \"\";\n try {\n jsonStr = mapper.writeValueAsString(map);\n } catch (IOException e) { \n e.printStackTrace();\n } \n \n return jsonStr;\n\t}\n\t\n}", "@EqualsAndHashCode(callSuper=false)\n@Data\n@JsonIgnoreProperties({\"properties\"})\npublic class Attachment extends JsonPrettyString{\t\n\tprivate String id;\n\tprivate String self;\n\tprivate String filename;\n\tprivate Reporter author;\n\n\t@JsonSerialize(using = ZonedDateTimeSerializer.class)\n\t@JsonDeserialize(using = MyZonedDateTimeDeserializer.class)\n\tprivate ZonedDateTime created;\n\t\n\tprivate Integer size;\n\tprivate String mimeType;\t\n\tprivate String content;\n\tprivate String thumbnail;\n}", "@Data\n@EqualsAndHashCode(callSuper = false)\npublic class Issue extends JsonPrettyString{\n\tprivate String expand;\n\tprivate String id;\n\tprivate String self;\n\tprivate String key;\n\t\n\tprivate IssueFields fields = new IssueFields();\n\n\tpublic Issue addAttachment(String filePath) throws IOException {\t\t\n\t\taddAttachment(new File(filePath));\n\t\t\n\t\treturn this;\n\t}\n\t\n\tpublic Issue addAttachment(File file) throws IOException {\t\n\t\tfields.addAttachment(file);\t\n\t\t\n\t\treturn this;\n\t}\n\n\t/**\n\t * check attachment exist \n\t * \n\t * @return boolean true: issue have attachment, false: no attachment\n\t */\n\tpublic boolean hasAttachments() {\n\t\tif (fields.getFileList() != null && fields.getFileList().size() > 0)\n\t\t\treturn true;\n\t\t\n\t\treturn false;\n\t}\n \n \n}", "@Data\n@JsonIgnoreProperties({\"lastViewed\", \"aggregateprogress\"\n,\"timeoriginalestimate\", \"aggregatetimespent\",\n\"fileList\"\n})\n@JsonInclude(value= JsonInclude.Include.NON_EMPTY, content= JsonInclude.Include.NON_NULL)\n@Accessors(chain=true)\npublic class IssueFields {\n\tprivate Project project;\n\tprivate String summary;\n\t\n\tprivate Map<String, String> progress;\n\t\n\tprivate TimeTracking timetracking;\n\tprivate IssueType issuetype;\n\t\n\tprivate String timespent;\n\t\n\tprivate Reporter reporter;\n\n\t@JsonSerialize(using = LocalDateSerializer.class)\n\t@JsonDeserialize(using = LocalDateDeserializer.class)\n\tprivate LocalDateTime created;\n\n\t@JsonSerialize(using = LocalDateSerializer.class)\n\t@JsonDeserialize(using = LocalDateDeserializer.class)\n\tprivate LocalDateTime updated;\n\t\n\tprivate String description;\n\t\n\tprivate Priority priority;\n\t\n\tprivate String[] issuelinks;\n\t\n\t// for custom field\t\n\tprivate Map<String,Object> customfield = new HashMap<String, Object>();\n\t\n\t@JsonAnyGetter\n\tpublic Map<String,Object> getCustomfield(){\n\t\treturn this.customfield; \n\t}\n\t\n\t@JsonAnySetter\n\tpublic IssueFields setCustomfield(String key,Object value){ \n\t\tif (this.customfield == null)\n\t\t\tthis.customfield = new HashMap<String, Object>();\n\t\t\n\t\tthis.customfield.put(key, value);\n\t\t\n\t\treturn this;\n\t}\n\t\t\n\tprivate String[] subtasks;\n\tprivate Status status;\n\t\n\tprivate String[] labels;\n\n\tprivate Double workratio;\n\n\tprivate String environment;\n\t\n\tprivate List<Component> components;\n\t\n\tprivate Comment comment;\n\t\n\tprivate Vote votes;\n\t\n\tprivate Resolution resolution;\n\t\n\tprivate String[] fixVersions;\n\n\t@JsonSerialize(using = LocalDateSerializer.class)\n\t@JsonDeserialize(using = LocalDateDeserializer.class)\n\tprivate LocalDateTime resolutiondate;\n\t\n\tprivate Reporter creator;\n\n\t@JsonSerialize(using = LocalDateSerializer.class)\n\t@JsonDeserialize(using = LocalDateDeserializer.class)\n\tprivate LocalDateTime aggregatetimeoriginalestimate;\n\n\t@JsonSerialize(using = LocalDateSerializer.class)\n\t@JsonDeserialize(using = LocalDateDeserializer.class)\n\tprivate LocalDateTime duedate;\n\t\n\tprivate Map<String, String> watches;\n\n\tprivate Worklog worklog;\n\t\n\tprivate Reporter assignee;\n\t\n\tprivate List<Attachment> attachment;\n\t\n\tprivate\tList<File>\tfileList;\n\n\t@JsonSerialize(using = LocalDateSerializer.class)\n\t@JsonDeserialize(using = LocalDateDeserializer.class)\n\tprivate LocalDateTime aggregatetimeestimate;\n\t\n\tprivate List<Version> versions;\n\t\n\tprivate Integer timeestimate;\n\t\n\t// Helper method\n\tpublic IssueFields setProjectId(String id) {\n\t\tif (project == null)\n\t\t\tproject = new Project();\n\t\t\n\t\tproject.setId(id);\n\t\t\n\t\treturn this;\n\t}\n\t\n\tpublic IssueFields setProjectKey(String key) {\n\t\tif (project == null)\n\t\t\tproject = new Project();\n\t\t\n\t\tproject.setKey(key);\n\t\t\n\t\treturn this;\n\t}\n\t\n\tpublic IssueFields setIssueTypeId(String id) {\n\t\tif (issuetype == null)\n\t\t\tissuetype = new IssueType();\n\t\tissuetype.setId(id);\n\t\t\n\t\treturn this;\n\t}\n\t\n\tpublic IssueFields setIssueTypeName(String name) {\n\t\tif (issuetype == null)\n\t\t\tissuetype = new IssueType();\n\t\tissuetype.setName(name);\n\t\t\n\t\treturn this;\n\t}\n\t\n\tpublic IssueFields setAssigneeName(String name) {\n\t\tif (assignee == null)\n\t\t\tassignee = new Reporter();\n\n\t\tassignee.setName(name);\n\t\t\n\t\treturn this;\n\t}\n\t\n\tpublic IssueFields setReporterName(String name) {\n\t\tif (reporter == null)\n\t\t\treporter = new Reporter();\n\n\t\treporter.setName(name);\n\t\t\n\t\treturn this;\n\t}\n\n\tpublic IssueFields setPriorityId(String id) {\n\t\tif (priority == null)\n\t\t\tpriority = new Priority();\n\n\t\tpriority.setId(id);\n\t\t\n\t\treturn this;\t\t\n\t}\n\t\n\tpublic IssueFields setPriorityName(String name) {\n\t\tif (priority == null)\n\t\t\tpriority = new Priority();\n\n\t\tpriority.setName(name);\n\t\t\n\t\treturn this;\n\t}\n\n\tpublic IssueFields addAttachment(String filePath) {\n\t\taddAttachment(new File(filePath));\n\n\t\treturn this;\n\t}\n\n\tpublic IssueFields addAttachment(File file) {\t\t\t\n\t\tif (this.fileList == null)\n\t\t\tthis.fileList = new ArrayList<File>();\n\t\t\t\n\t\tfileList.add(file);\n\t\t\n\t\treturn this;\n\t}\n\t\n\tpublic IssueFields setComponentsByStringArray(String[] componenArray) {\n\t \n\t if (componenArray == null || componenArray.length == 0)\n\t return this;\n\t \n\t Component[] c = new Component[componenArray.length];\n\t \n\t for(int i = 0; i < componenArray.length; i++) {\n\t c[i] = new Component(componenArray[i]);\n\t }\n\t \n\t this.components = Arrays.asList(c);\n\t \n\t return this;\n\t}\n\t\n}", "@Data\n@EqualsAndHashCode(callSuper = false)\npublic class IssueSearchResult extends JsonPrettyString{\n \n private String expand;\n private Integer startAt;\n private Integer maxResults;\n private Integer total;\n private List<Issue> issues;\n}", "@Data\n@EqualsAndHashCode(callSuper = false)\npublic class IssueType extends JsonPrettyString {\n\t// Default issue type\n\tpublic static final String ISSUE_TYPE_BUG = \"Bug\";\n\tpublic static final String ISSUE_TYPE_TASK = \"Task\";\n\tpublic static final String ISSUE_TYPE_IMPROVEMENT = \"Improvement\";\n\tpublic static final String ISSUE_TYPE_SUBTASK = \"SubTask\";\n\tpublic static final String ISSUE_TYPE_NEW_FEATURE = \"New Feature\";\n\t\n\tprivate String self;\n\tprivate String id;\n\tprivate String description;\n\tprivate String iconUrl;\n\tprivate String name;\n\tprivate Boolean subtask;\n\tprivate Integer avatarId;\n}", "@Data\n@EqualsAndHashCode(callSuper=false)\npublic class Priority extends JsonPrettyString {\n\tpublic static final String PRIORITY_BLOCKER = \"Blocker\";\n\tpublic static final String PRIORITY_CRITICAL = \"Critical\";\n\tpublic static final String PRIORITY_MAJOR = \"Major\";\n\tpublic static final String PRIORITY_MINOR = \"Minor\";\n\tpublic static final String PRIORITY_TRIVIAL = \"Trivial\";\n\t\n\tprivate String self;\n\tprivate String iconUrl;\n\tprivate String name;\n\tprivate String id;\n\tprivate String statusColor;\n\tprivate String description;\n}", "public class HttpConnectionUtil {\n \n public static void disableSslVerification() {\n try {\n // Create a trust manager that does not validate certificate chains\n TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {\n public java.security.cert.X509Certificate[] getAcceptedIssuers() {\n return null;\n }\n\n public void checkClientTrusted(X509Certificate[] certs, String authType) {\n }\n\n public void checkServerTrusted(X509Certificate[] certs, String authType) {\n }\n }\n };\n\n // Install the all-trusting trust manager\n SSLContext sc = SSLContext.getInstance(\"SSL\");\n sc.init(null, trustAllCerts, new java.security.SecureRandom());\n HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());\n\n // Create all-trusting host name verifier\n HostnameVerifier allHostsValid = new HostnameVerifier() {\n public boolean verify(String hostname, SSLSession session) {\n return true;\n }\n };\n\n // Install the all-trusting host verifier\n HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);\n } catch (NoSuchAlgorithmException e) {\n e.printStackTrace();\n } catch (KeyManagementException e) {\n e.printStackTrace();\n }\n }\n \n}" ]
import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; import org.apache.commons.configuration.ConfigurationException; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.lesstif.jira.JsonPrettyString; import com.lesstif.jira.issue.Attachment; import com.lesstif.jira.issue.Issue; import com.lesstif.jira.issue.IssueFields; import com.lesstif.jira.issue.IssueSearchResult; import com.lesstif.jira.issue.IssueType; import com.lesstif.jira.issue.Priority; import com.lesstif.jira.util.HttpConnectionUtil; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*;
package com.lesstif.jira.services; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class IssueTest { private Logger logger = LoggerFactory.getLogger(getClass()); static String PROJECT_KEY = null; static String ISSUE_KEY = null; static String REPORTER = null; static String ASSIGNEE = null; @BeforeClass public static void beforeClass() { HttpConnectionUtil.disableSslVerification(); PROJECT_KEY = System.getProperty("jira.test.project", "TEST"); ISSUE_KEY = System.getProperty("jira.test.issue", "TEST-108"); ASSIGNEE = System.getProperty("jira.test.assignee", "lesstif"); REPORTER = System.getProperty("jira.test.reporter", "gitlab"); } @Test public void aCreateIssue() throws IOException, ConfigurationException {
Issue issue = new Issue();
2
agilie/dribbble-android-sdk
dribbble-sdk-library/src/main/java/com/agilie/dribbblesdk/service/retrofit/DribbbleWebServiceHelper.java
[ "public interface DribbbleBucketsService {\n\n /**\n * Get a bucket\n *\n * @param bucketId Bucket ID\n *\n * @return Network operation result\n */\n @GET(\"buckets/{id}\")\n Call<Bucket> getBucket(@Path(\"id\") long bucketId);\n\n /**\n * Create a bucket.\n * Creating a bucket requires the user to be authenticated with the <u>write</u> scope\n *\n * @param bucket The bucket to create. Field <code>Bucket.name</code> is required\n *\n * @return Network operation result\n */\n @POST(\"buckets\")\n Call<Bucket> createBucket(@Body Bucket bucket);\n\n /**\n * Update a bucket.\n * Updating a bucket requires the user to be authenticated with the <u>write</u> scope.\n *\n * @param bucketId Bucket ID to update\n * @param bucket The bucket to update\n *\n * @return Network operation result\n */\n @PUT(\"buckets/{id}\")\n Call<Bucket> updateBucket(@Path(\"id\") long bucketId, @Body Bucket bucket);\n\n /**\n * Delete a bucket.\n * Deleting a bucket requires the user to be authenticated with the <u>write</u> scope. The authenticated user must also own the bucket\n *\n * @param bucketId Bucket ID to delete\n *\n * @return Network operation result\n */\n @DELETE(\"buckets/{id}\")\n Call<Void> deleteBucket(@Path(\"id\") long bucketId);\n\n /************************************** BUCKET SHOTS ************************************************/\n\n /**\n * List shots for a bucket\n *\n * @param bucketId Bucket ID\n *\n * @return Network operation result\n */\n @GET(\"buckets/{id}/shots\")\n Call<List<Shot>> getShotsForBucket(@Path(\"id\") long bucketId);\n\n /**\n * Add a shot to a bucket.\n * Adding a shot to a bucket requires the user to be authenticated with the <u>write</u> scope.\n * The authenticated user must also own the bucket.S\n *\n * @param shotId Shot ID to add\n * @param bucketId Bucket ID\n *\n * @return Network operation result\n */\n @PUT(\"buckets/{id}/shots\")\n Call<Void> addShotToBucket(@Path(\"id\") long bucketId, @Query(\"shot_id\") long shotId);\n\n /**\n * Remove a shot from a bucket\n * Removing a shot from a bucket requires the user to be authenticated with the <u>write</u> scope.\n * The authenticated user must also own the bucket.\n *\n * @param shotId Shot ID to remove\n * @param bucketId Bucket ID\n *\n * @return Network operation result\n */\n @DELETE(\"buckets/{id}/shots\")\n Call<Void> removeShotFromBucket(@Path(\"id\") long bucketId, @Query(\"shot_id\") long shotId);\n}", "public interface DribbbleProjectsService {\n\n /**\n * Get a project\n *\n * @param projectId Project ID to receive\n *\n * @return Network operation result\n */\n @GET(\"projects/{id}\")\n Call<Project> getProject(@Path(\"id\") long projectId);\n\n /************************************** PROJECT SHOTS ************************************************/\n\n /**\n * List of shots for a project\n *\n * @param projectId Project ID to be received list for\n *\n * @return Network operation result\n */\n @GET(\"projects/{id}/shots\")\n Call<List<Shot>> getShotsForProject(@Path(\"id\") long projectId);\n}", "public interface DribbbleShotsService {\n\n /**\n * Get shots list (popular shots by default)\n *\n * @param page Page number, used to receive result partially by pages.\n * Increase this value by 1 for each next request\n * @return Network operation result\n */\n @GET(\"shots\")\n Call<List<Shot>> fetchShots(@Query(\"page\") int page);\n\n /**\n * Get shots list (popular shots by default)\n *\n * @param page Page number, used to receive result partially by pages.\n * Increase this value by 1 for each next request\n * @return Network operation result\n */\n @GET(\"shots\")\n Call<List<Shot>> fetchShots(@Query(\"page\") int page, @Query(\"per_page\") int perPage);\n\n /**\n * Get shots list\n *\n * @param page Page number, used to receive result partially by pages.\n * Increase this value by 1 for each next request\n * @param list Allowed values:\n * <br/><code>Shot.LIST_ANIMATED</code>\n * <br/><code>Shot.LIST_ATTACHMENTS</code>\n * <br/><code>Shot.LIST_DEBUTS</code>\n * <br/><code>Shot.LIST_PLAYOFFS</code>\n * <br/><code>Shot.LIST_REBOUNDS</code>\n * <br/><code>Shot.LIST_TEAMS</code>\n * <br/>Default: Results of any type.\n * @param sort Allowed values:\n * <br/><code>Shot.SORT_COMMENTS</code>\n * <br/><code>Shot.SORT_RECENT</code>\n * <br/><code>Shot.SORT_VIEWS</code>\n * <br/>Default: Results are sorted by popularity.\n * @return Network operation result\n */\n @GET(\"shots\")\n Call<List<Shot>> fetchShots(@Query(\"page\") int page, @Query(\"per_page\") int perPage, @Query(\"list\") String list, @Query(\"sort\") String sort);\n\n /**\n * Get shots list\n *\n * @param page Page number, used to receive result partially by pages. Increase this value by 1 for each next request\n * @param list Allowed values:\n * <code>Shot.LIST_ANIMATED</code>\n * <code>Shot.LIST_ATTACHMENTS</code>\n * <code>Shot.LIST_DEBUTS</code>\n * <code>Shot.LIST_PLAYOFFS</code>\n * <code>Shot.LIST_REBOUNDS</code>\n * <code>Shot.LIST_TEAMS</code>\n * Default: Results of any type.\n * @param sort Allowed values:\n * <code>Shot.SORT_COMMENTS</code>\n * <code>Shot.SORT_RECENT</code>\n * <code>Shot.SORT_VIEWS</code>\n * Default: Results are sorted by popularity.\n * @param date Limit the timeframe to a specific date, week, month, or year.\n * Format: of YYYY-MM-DD.\n * @param timeframe A period of time to limit the results.\n * Allowed values:\n * <code>Shot.TIMEFRAME_WEEKS</code>\n * <code>Shot.TIMEFRAME_MONTH</code>\n * <code>Shot.TIMEFRAME_YEAR</code>\n * <code>Shot.TIMEFRAME_EVER</code>\n * <p/>\n * Note that the value is ignored when sorting with recent.\n * Default: Results from now.\n * @return Network operation result\n */\n @GET(\"shots\")\n Call<List<Shot>> fetchShots(@Query(\"page\") int page, @Query(\"per_page\") int perPage, @Query(\"list\") String list, @Query(\"sort\") String sort, @Query(\"date\") String date, @Query(\"timeframe\") String timeframe);\n\n @GET(\"shots\")\n Call<List<Shot>> fetchShots(@Query(\"page\") int page, @Query(\"list\") String list, @Query(\"sort\") String sort, @Query(\"date\") String date, @Query(\"timeframe\") String timeframe);\n\n /**\n * Get shots list\n *\n * @param list Allowed values:\n * <code>Shot.LIST_ANIMATED</code>\n * <code>Shot.LIST_ATTACHMENTS</code>\n * <code>Shot.LIST_DEBUTS</code>\n * <code>Shot.LIST_PLAYOFFS</code>\n * <code>Shot.LIST_REBOUNDS</code>\n * <code>Shot.LIST_TEAMS</code>\n * @return Network operation result\n */\n @GET(\"shots\")\n Call<List<Shot>> fetchShots(@Query(\"list\") String list);\n\n /**\n * Get shots list\n *\n * @param parameters Allowed parameters:\n * <b>list</b>\n * <code>Shot.LIST_ANIMATED</code>\n * <code>Shot.LIST_ATTACHMENTS</code>\n * <code>Shot.LIST_DEBUTS</code>\n * <code>Shot.LIST_PLAYOFFS</code>\n * <code>Shot.LIST_REBOUNDS</code>\n * <code>Shot.LIST_TEAMS</code>\n * Default: Results of any type.\n * <b>sort</b>\n * <code>Shot.SORT_COMMENTS</code>\n * <code>Shot.SORT_RECENT</code>\n * <code>Shot.SORT_VIEWS</code>\n * <b>timeframe</b> A period of time to limit the results.\n * Allowed values:\n * <code>Shot.TIMEFRAME_WEEKS</code>\n * <code>Shot.TIMEFRAME_MONTH</code>\n * <code>Shot.TIMEFRAME_YEAR</code>\n * <code>Shot.TIMEFRAME_EVER</code>\n * <p/>\n * Note that the value is ignored when sorting with recent.\n * Default: Results from now.\n * <b>date</b> Limit the timeframe to a specific date, week, month, or year.\n * Format: YYYY-MM-DD.\n * <b>page</b> to receive result partially by pages.\n * Increase this value by 1 for each next request\n * <b>per_page</b> Number of items per page.\n * <p>\n * Parameters name - the type of keys maintained by this map\n * Parameters value - the type of mapped values\n * @return Network operation result\n */\n @GET(\"shots\")\n Call<List<Shot>> fetchShots(@QueryMap Map<String, Object> parameters);\n\n /**\n * Get shots list\n *\n * @param sort Allowed values:\n * <code>Shot.SORT_COMMENTS</code>\n * <code>Shot.SORT_RECENT</code>\n * <code>Shot.SORT_VIEWS</code>\n * @return Network operation result\n */\n @GET(\"shots\")\n Call<List<Shot>> fetchSortedShots(@Query(\"sort\") String sort);\n\n /**\n * Get a shot\n *\n * @param shotId Shot ID to receive\n * @return Network operation result\n */\n @GET(\"shots/{id}\")\n Call<Shot> getShot(@Path(\"id\") long shotId);\n\n /**\n * Create a shot.\n * <p>\n * Creating a shot happens asynchronously. After creation the returned location will\n * return a 404 Not Found until processing is completed.\n * If this takes longer than five minutes, be sure to contact support.\n *\n * @param title <b>Required.</b> The title of the shot.\n * @param image <b>Required.</b> The image file.\n * It must be exactly 400x300 or 800x600, no larger\n * than eight megabytes, and be a GIF, JPG, or PNG.\n * @param description A description of the shot.\n * @param tags Tags for the shot.\n * Limited to a maximum of 12 tags.\n * @param teamId An ID of a team to associate the shot with.\n * The authenticated user must either be a member\n * of the team or be authenticated as the same team.\n * @param reboundSourceId An ID of a shot that the new shot is a rebound of.\n * The shot must be reboundable and by a user not blocking\n * the authenticated user.\n * @return Network operation result\n */\n @Multipart\n @POST(\"shots\")\n Call<Void> createShot(@Part(\"title\") String title, @Part MultipartBody.Part image, @Part(\"description\") String description,\n @Part(\"tags\") String[] tags, @Part(\"team_id\") int teamId, @Part(\"rebound_source_id\") int reboundSourceId);\n\n @Multipart\n @POST(\"shots\")\n Call<Void> createShot(@Part(\"title\") String title, @Part MultipartBody.Part image, @Part(\"description\") String description,\n @Part(\"tags\") String[] tags);\n\n @Multipart\n @POST(\"shots\")\n Call<Void> createShot(@Part(\"title\") String title, @Part MultipartBody.Part image);\n\n\n /**\n * Create a shot by using PartMap\n * <p>\n * Creating a shot happens asynchronously. After creation the returned location will\n * return a 404 Not Found until processing is completed.\n * If this takes longer than five minutes, be sure to contact support.\n *\n * @param partMap allowable put parameters into Map&ltString, Object&gt such as:\n * <b>title</b> <b>Required.</b> The title of the shot.\n * <b>image</b> <b>Required.</b> The image file.\n * It must be exactly 400x300 or 800x600,\n * no larger than eight megabytes, and be a GIF, JPG, or PNG.\n * <b>description</b> A description of the shot.\n * <b>tags</b> Tags for the shot.\n * Limited to a maximum of 12 tags.\n * <b>team_id</b> An ID of a team to associate the shot with.\n * The authenticated user must either be a member\n * of the team or be authenticated as the same team.\n * <b>rebound_source_id</b> An ID of a shot that the new shot is a rebound of.\n * The shot must be reboundable and by a user\n * not blocking the authenticated user.\n * <p>\n * Parameters name - the type of keys maintained by this map\n * Parameters value - the type of mapped values\n * @return Network operation result\n */\n @Multipart\n @POST(\"shots\")\n Call<Void> createShot(@PartMap Map<String, Object> partMap);\n\n /**\n * Update a shot.\n * <p>\n * Updating a shot requires the user to be authenticated with the upload scope.\n * The authenticated user must also own the shot.\n *\n * @param shotId Shot ID to update\n * @return Network operation result\n */\n @Multipart\n @PUT(\"shots/{id}\")\n Call<Shot> updateShot(@Path(\"id\") long shotId, @Part(\"title\") String title, @Part(\"description\") String description,\n @Part(\"team_id\") int teamId, @Part(\"tags\") String[] tags);\n\n @Multipart\n @PUT(\"shots/{id}\")\n Call<Shot> updateShot(@Path(\"id\") long shotId, @Part(\"title\") String title, @Part(\"description\") String description,\n @Part(\"tags\") String[] tags);\n\n @Multipart\n @PUT(\"shots/{id}\")\n Call<Shot> updateShot(@Path(\"id\") long shotId, @Part(\"description\") String description);\n\n /**\n * Delete a shot.\n * <p>\n * Deleting a shot requires the user to be authenticated with the upload scope.\n * The authenticated user must also own the shot.\n *\n * @param shotId Shot ID to delete.\n * @return Network operation result\n */\n @DELETE(\"shots/{id}\")\n Call<Void> deleteShot(@Path(\"id\") long shotId);\n\n\n /************************************** SHOT ATTACHMENTS ************************************************/\n\n /**\n * List the attachments for a shot\n *\n * @param shotId Shot ID\n * @return Network operation result\n */\n @GET(\"shots/{id}/attachments\")\n Call<List<Attachment>> getShotAttachments(@Path(\"id\") long shotId);\n\n /**\n * Create a shot attachment.\n * <p>\n * Creating an attachment requires the user to be authenticated with the <u>upload</u> scope.\n * The authenticated user must own the shot and be a pro, a team, or a member of a team.\n *\n * @param shotId Shot ID to create attachment for\n * @param file Attachment to be created. <b>Required.</b> The attachment file.\n * It must be no larger than 10 megabytes.\n * @return Network operation result\n */\n @POST(\"shots/{shot}/attachments\")\n Call<Void> createShotAttachment(@Path(\"shot\") long shotId, @Part MultipartBody.Part file);\n\n /**\n * Get a single attachment\n * <p>\n * A <u>thumbnail_url</u> is only present for image attachments.\n *\n * @param shotId Shot ID to get attachment for\n * @param attachmentId Attachment ID to receive\n * @return Network operation result\n */\n @GET(\"shots/{shot}/attachments/{id}\")\n Call<Attachment> getShotAttachment(@Path(\"shot\") long shotId, @Path(\"id\") long attachmentId);\n\n /**\n * Delete an attachment\n * <p>\n * Deleting an attachment requires the user to be authenticated with the <u>upload</u> scope.\n * The authenticated user must also own the attachment.\n *\n * @param shotId Shot ID to delete attachment for\n * @param attachmentId Attachment ID to delete\n * @return Network operation result\n */\n @DELETE(\"shots/{shot}/attachments/{id}\")\n Call<Void> deleteShotAttachment(@Path(\"shot\") long shotId, @Path(\"id\") long attachmentId);\n\n\n /************************************** SHOT BUCKETS ****************************************************/\n\n /**\n * List buckets for a shot\n *\n * @param shotId Shot ID with the list of buckets\n * @return Network operation result\n */\n @GET(\"shots/{id}/buckets\")\n Call<List<Bucket>> getShotBuckets(@Path(\"id\") long shotId);\n\n\n /************************************** SHOT COMMENTS ***************************************************/\n\n /**\n * List of comments for a shot\n *\n * @param shotId Shot ID with the list of comments\n * @return Network operation result\n */\n\n @GET(\"shots/{shot}/comments\")\n Call<List<Comment>> getShotComments(@Path(\"shot\") long shotId);\n\n\n /**\n * List of likes for a comment\n *\n * @param shotId Shot ID with the given comment\n * @param commentId Comment ID with the list of likes\n * @return Network operation result\n */\n\n @GET(\"shots/{shot}/comments/{id}/likes\")\n Call<List<Like>> getCommentLikes(@Path(\"shot\") long shotId, @Path(\"id\") long commentId);\n\n\n /**\n * Create a comment\n * <p>\n * Creating a comment requires the user to be authenticated with the <u>comment</u> scope.\n * The authenticated user must also be a player or team.\n * <p>\n * Any username mentions, such as @simplebits, are automatically parsed and linked.\n *\n * @param shotId Shot ID\n * @param body Content to update\n * @return Network operation result\n */\n\n @POST(\"shots/{shot}/comments\")\n Call<Comment> createComment(@Path(\"shot\") long shotId, @Body Comment body);\n\n /**\n * Get a single comment\n *\n * @param shotId Shot ID\n * @param commentId Comment ID to return\n * @return Network operation result\n */\n\n @GET(\"shots/{shot}/comments/{id}\")\n Call<Comment> getShotComment(@Path(\"shot\") long shotId, @Path(\"id\") long commentId);\n\n /**\n * Update a comment\n * <p>\n * Updating a comment requires the user to be authenticated with the <u>comment</u> scope.\n * The authenticated user must also own the comment.\n *\n * @param shotId Shot ID\n * @param commentId Comment ID to update\n * @param comment Comment content\n * @return Network operation result\n */\n\n @PUT(\"shots/{shot}/comments/{id}\")\n Call<Comment> updateShotComment(@Path(\"shot\") long shotId, @Path(\"id\") long commentId, @Body Comment comment);\n\n /**\n * Delete a comment\n * <p>\n * Deleting a comment requires the user to be authenticated with the <u>comment</u> scope.\n * The authenticated user must also own the comment.\n *\n * @param shotId Shot ID\n * @param commentId Comment ID to remove\n * @return Network operation result\n */\n\n @DELETE(\"shots/{shot}/comments/{id}\")\n Call<Void> deleteShotComment(@Path(\"shot\") long shotId, @Path(\"id\") long commentId);\n\n /**\n * Check if you like a comment\n * <p>\n * Checking for a comment like requires the user to be authenticated.\n * <p>\n * Note that returned result may contain \"404 not found\" error, if the user does not like the comment.\n * It's better use synchronous method which returns Response.class.\n *\n * @param shotId Shot ID to check if the user likes comment\n * @param commentId Comment ID to check if the user likes it\n * @return Network operation result\n */\n\n @GET(\"shots/{shot}/comments/{id}/like\")\n Call<Like> checkIsLikedShotComment(@Path(\"shot\") long shotId, @Path(\"id\") long commentId);\n\n /**\n * Like a comment\n * <p>\n * Liking a comment requires the user to be authenticated with the <u>write</u> scope.\n *\n * @param shotId Shot ID to like comment\n * @param commentId Comment ID to like\n * @return Network operation result\n */\n\n @POST(\"shots/{shot}/comments/{id}/like\")\n Call<Like> likeShotComment(@Path(\"shot\") long shotId, @Path(\"id\") long commentId);\n\n /**\n * Unlike a comment\n * <p>\n * Unliking a comment requires the user to be authenticated with the <u>write</u> scope.\n *\n * @param shotId Shot ID\n * @param commentId Comment ID to unlike\n * @return Network operation result\n */\n\n @DELETE(\"shots/{shot}/comments/{id}/like\")\n Call<Void> unlikeShotComment(@Path(\"shot\") long shotId, @Path(\"id\") long commentId);\n\n\n /************************************** SHOT LIKES ******************************************************/\n /********************************************************************************************************/\n\n /**\n * Get list of likes for a shot\n *\n * @param shotId Shot ID with the list of likes\n * @return Network operation result\n */\n\n @GET(\"shots/{id}/likes\")\n Call<List<Like>> getShotLikes(@Path(\"id\") long shotId);\n\n /**\n * Check if you like a shot.\n * Checking for a shot like requires the user to be authenticated.\n * <p>\n * Note that returned result may contain \"404 not found\" error, if the user does not like the shot.\n * It's better use synchronous method which returns Response.class.\n *\n * @param shotId Shot ID to check\n * @return Network operation result\n */\n @GET(\"shots/{id}/like\")\n Call<Like> checkShotIsLiked(@Path(\"id\") long shotId);\n\n /**\n * Like a shot\n * <p>\n * Liking a shot requires the user to be authenticated with the <u>write</u> scope.\n *\n * @param shotId Shot ID to like\n * @return Network operation result\n */\n\n @POST(\"shots/{id}/like\")\n Call<Like> likeShot(@Path(\"id\") long shotId);\n\n /**\n * Unlike a shot\n * <p>\n * Unliking a shot requires the user to be authenticated with the <u>write</u> scope.\n *\n * @param shotId Shot ID to unlike\n * @return Network operation result\n */\n\n @DELETE(\"shots/{id}/like\")\n Call<Void> unlikeShot(@Path(\"id\") long shotId);\n\n\n /************************************** SHOT PROJECTS ***************************************************/\n\n /**\n * List projects for a shot\n *\n * @param shotId Shot ID with the list of projects\n * @return Network operation result\n */\n\n @GET(\"shots/{id}/projects\")\n Call<List<Project>> getShotProjectsList(@Path(\"id\") long shotId);\n\n\n /************************************** SHOT REBOUNDS ***************************************************/\n\n /**\n * List rebounds for a shot\n *\n * @param shotId Shot ID with the list of rebounds\n * @return Network operation result\n */\n\n @GET(\"shots/{id}/rebounds\")\n Call<List<Rebound>> getShotReboundsList(@Path(\"id\") long shotId);\n}", "public interface DribbbleTeamsService {\n\n /**\n * List a team’s members\n *\n * @param teamId Team ID with the list of the members\n *\n * @return Network operation result\n */\n\n @GET(\"teams/{team}/members\")\n Call<List<User>> getTeamMembersList(@Path(\"team\") long teamId);\n\n /**\n * List shots for a team\n *\n * @param teamId Team ID\n *\n * @return Network operation result\n */\n\n @GET(\"teams/{team}/shots\")\n Call<List<Shot>> getTeamShotsList(@Path(\"team\") long teamId);\n}", "public interface DribbbleUserService {\n\n /**\n * Get a single user\n *\n * @param userId User ID to get\n *\n * @return Network operation result\n */\n @GET(\"users/{user}\")\n Call<User> getSingleUser(@Path(\"user\") long userId);\n\n /**\n * Get the authenticated user\n *\n * @return Network operation result\n */\n @GET(\"user\")\n Call<User> fetchAuthenticatedUser();\n\n\n /************************************** USER BUCKETS ****************************************************/\n\n /**\n * Get user's buckets list\n *\n * @param userId User ID to get buckets list\n *\n * @return Network operation result\n */\n @GET(\"users/{user}/buckets\")\n Call<List<Bucket>> getUsersBuckets(@Path(\"user\") long userId);\n\n /**\n * Get authenticated user's buckets list\n *\n * @return Network operation result\n */\n @GET(\"user/buckets\")\n Call<List<Bucket>> getAuthenticatedUsersBuckets();\n\n\n /************************************** USER FOLLOWERS **************************************************/\n\n /**\n * Get user's followers list\n *\n * @param userId User ID to get followers list\n * @param page Page number, used to receive result partially by pages.\n * Increase this value by 1 for each next request\n * @param perPage Followers count per one page\n *\n * @return Network operation result\n */\n @GET(\"users/{user}/followers\")\n Call<List<Follower>> getUsersFollowers(@Path(\"user\") long userId, @Query(\"page\") int page, @Query(\"per_page\") int perPage);\n\n /**\n * Get authenticated user's followers list\n *\n * @param page Page number, used to receive result partially by pages.\n * Increase this value by 1 for each next request\n * @param perPage Followers count per one page\n *\n * @return Network operation result\n */\n @GET(\"user/followers\")\n Call<List<Follower>> getAuthenticatedUsersFollowers(@Query(\"page\") int page, @Query(\"per_page\") int perPage);\n\n /**\n * List of users followed by a user\n *\n * @param userId User ID\n *\n * @return Network operation result\n */\n @GET(\"users/{user}/following\")\n Call<List<Followee>> getFollowingByUser(@Path(\"user\") long userId);\n\n /**\n * List of users followed by a user\n *\n * @param userId User ID to get followers list\n * @param page Page number, used to receive result partially by pages.\n * Increase this value by 1 for each next request\n * @param perPage Followers count per one page\n *\n * @return Network operation result\n */\n @GET(\"users/{user}/following\")\n Call<List<Followee>> getFollowingByUser(@Path(\"user\") long userId, @Query(\"page\") int page, @Query(\"per_page\") int perPage);\n\n /**\n * List of users followed by an authenticated user\n *\n * @return Network operation result\n */\n @GET(\"user/following\")\n Call<List<Followee>> getFollowingByCurrentUser();\n\n /**\n * List of shots for users followed by an authenticated user\n *\n * Listing shots from followed users requires the user to be authenticated\n * with the <u>public</u> scope. Also note that you can not retrieve more than 600 results,\n * regardless of the number requested per page.\n *\n * @return Network operation result\n */\n @GET(\"user/following/shots\")\n Call<List<Shot>> shotsForUserFollowedByUser();\n\n /**\n * Check if you are following the user.\n * Checking for a shot like requires the user to be authenticated.\n *\n * Note that returned result may contain \"404 not found\" error, if you are not following this user.\n * It's better use synchronous method which returns Response.class.\n *\n * @param userId User ID to check\n *\n * @return Network operation result\n */\n @GET(\"user/following/{user}\")\n Call<Void> checkUserIsFollowed(@Path(\"user\") long userId);\n\n /**\n * Check if one user is following another\n *\n * Note that returned result may contain \"404 not found\" error, if user does not follow target user.\n * It's better use synchronous method which returns Response.class.\n *\n * @param userId User ID to be checked\n * @param targetUserId Target user ID which will draw comparisons\n *\n * @return Network operation result\n */\n @GET(\"users/{user}/following/{target_user}\")\n Call<Void> checkUserIsFollowingAnother(@Path(\"user\") long userId, @Path(\"target_user\") long targetUserId);\n\n /**\n * Follow a user.\n * Following a user requires the user to be authenticated with the <u>write</u> scope.\n *\n * The following errors are possible, and will be on the base attribute:\n * You cannot follow yourself.\n * You have been blocked from following this member at their request.\n * You have reached the maximum number of follows allowed.\n *\n * @param userId User id to follow\n *\n * @return Network operation result\n */\n @PUT(\"users/{id}/follow\")\n Call<Void> followUser(@Path(\"id\") long userId);\n\n /**\n * Unfollow a user.\n * Unfollowing a user requires the user to be authenticated with the <u>write</u> scope.\n *\n * @param userId User id to unfollow\n *\n * @return Network operation result\n */\n @DELETE(\"users/{id}/follow\")\n Call<Void> unfollowUser(@Path(\"id\") long userId);\n\n\n /************************************** USER LIKES ******************************************************/\n\n /**\n * Get a user’s shot likes list\n *\n * @param userId User ID to get list shot likes\n *\n * @return Network operation result\n */\n @GET(\"users/{user}/likes\")\n Call<List<Like>> getUsersLikes(@Path(\"user\") long userId);\n\n /**\n * Get a user’s shot likes list\n *\n * @param userId User ID to get list shot likes\n * @param page Page number, used to receive result partially by pages.\n * Increase this value by 1 for each next request\n * @param perPage Shots count per one page\n *\n * @return Network operation result\n */\n @GET(\"users/{user}/likes\")\n Call<List<Like>> getUsersLikes(@Path(\"user\") long userId, @Query(\"page\") int page, @Query(\"per_page\") int perPage);\n\n /**\n * Get the authenticated user’s shot likes list\n *\n * @return Network operation result\n */\n @GET(\"user/likes\")\n Call<List<Like>> getAuthenticatedUsersLikes();\n\n\n /************************************** USER PROJECTS ***************************************************/\n\n /**\n * Get a user’s projects list\n *\n * @param userId User ID to get project list\n *\n * @return Network operation result\n */\n @GET(\"users/{user}/projects\")\n Call<List<Project>> getUsersProjects(@Path(\"user\") long userId);\n\n /**\n * Get the authenticated user’s projects list\n *\n * @return Network operation result\n */\n @GET(\"user/projects\")\n Call<List<Project>> getAuthenticatedUsersProjects();\n\n\n /************************************** USER SHOTS ******************************************************/\n\n /**\n * Get a user’s shots list\n *\n * @param userId User ID to get shot list\n *\n * @return Network operation result\n */\n @GET(\"users/{user}/shots\")\n Call<List<Shot>> getUsersShots(@Path(\"user\") long userId);\n\n /**\n * Get a user’s shots list by page\n *\n * @param userId User ID to get shot list\n * @param page Page number, used to receive result partially by pages.\n * Increase this value by 1 for each next request\n * @param perPage Number of shot per page\n *\n * @return Network operation result\n */\n @GET(\"users/{user}/shots\")\n Call<List<Shot>> getUsersShots(@Path(\"user\") long userId, @Query(\"page\") int page, @Query(\"per_page\") int perPage);\n\n /**\n * Get authenticated user's shots list\n *\n * @param page Page number, used to receive result partially by pages.\n * Increase this value by 1 for each next request\n * @param perPage Number of shot per page\n *\n * @return Network operation result\n */\n @GET(\"user/shots\")\n Call<List<Shot>> getAuthenticatedUsersShots(@Query(\"page\") int page, @Query(\"per_page\") int perPage);\n\n\n /************************************** USER TEAMS ******************************************************/\n\n /**\n * Get a user’s teams list\n *\n * @param userId User ID to get shot list\n *\n * @return Network operation result\n */\n @GET(\"users/{user}/teams\")\n Call<List<Team>> getUsersTeams(@Path(\"user\") long userId);\n\n /**\n * Get authenticated user's teams list\n *\n * @param page Page number, used to receive result partially by pages.\n * Increase this value by 1 for each next request\n *\n * @return Network operation result\n */\n @GET(\"user/teams\")\n Call<List<Team>> getAuthenticatedUsersTeams(@Query(\"page\") int page);\n}" ]
import com.agilie.dribbblesdk.service.retrofit.services.DribbbleBucketsService; import com.agilie.dribbblesdk.service.retrofit.services.DribbbleProjectsService; import com.agilie.dribbblesdk.service.retrofit.services.DribbbleShotsService; import com.agilie.dribbblesdk.service.retrofit.services.DribbbleTeamsService; import com.agilie.dribbblesdk.service.retrofit.services.DribbbleUserService; import java.io.IOException; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import retrofit2.Retrofit; import android.os.Build; import android.util.Log; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.net.ssl.SSLContext; import okhttp3.ConnectionSpec; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.TlsVersion; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory;
package com.agilie.dribbblesdk.service.retrofit; public class DribbbleWebServiceHelper { public static String DRIBBBLE_URL = "https://api.dribbble.com/v1/"; public static DribbbleBucketsService getDribbbleBucketService(Retrofit retrofit) { DribbbleBucketsService service = retrofit.create(DribbbleBucketsService.class); return service; } public static DribbbleProjectsService getDribbbleProjectService(Retrofit retrofit) { DribbbleProjectsService service = retrofit.create(DribbbleProjectsService.class); return service; } public static DribbbleShotsService getDribbbleShotService(Retrofit retrofit) { DribbbleShotsService service = retrofit.create(DribbbleShotsService.class); return service; }
public static DribbbleTeamsService getDribbbleTeamService(Retrofit retrofit) {
3
MCUpdater/MCUpdater
MCU-API/src/org/mcupdater/util/MCLegacyAuth.java
[ "public class Version {\n\tpublic static final int MAJOR_VERSION;\n\tpublic static final int MINOR_VERSION;\n\tpublic static final int BUILD_VERSION;\n\tpublic static final String BUILD_BRANCH;\n\tpublic static final String BUILD_LABEL;\n\tstatic {\n\t\tProperties prop = new Properties();\n\t\ttry {\n\t\t\tprop.load(Version.class.getResourceAsStream(\"/version.properties\"));\n\t\t} catch (IOException e) {\n\t\t}\n\t\tMAJOR_VERSION = Integer.valueOf(prop.getProperty(\"major\",\"0\"));\n\t\tMINOR_VERSION = Integer.valueOf(prop.getProperty(\"minor\",\"0\"));\n\t\tBUILD_VERSION = Integer.valueOf(prop.getProperty(\"build_version\",\"0\"));\n\t\tBUILD_BRANCH = prop.getProperty(\"git_branch\",\"unknown\");\n\t\tif( BUILD_BRANCH.equals(\"unknown\") || BUILD_BRANCH.equals(\"master\") ) {\n\t\t\tBUILD_LABEL = \"\";\n\t\t} else {\n\t\t\tBUILD_LABEL = \" (\"+BUILD_BRANCH+\")\";\n\t\t}\n\t}\n\t\n\tpublic static final String API_VERSION = MAJOR_VERSION + \".\" + MINOR_VERSION;\n\tpublic static final String VERSION = \"v\"+MAJOR_VERSION+\".\"+MINOR_VERSION+\".\"+BUILD_VERSION;\n\t\n\tpublic static boolean isVersionOld(String packVersion) {\n\t\tif( packVersion == null ) return false;\t// can't check anything if they don't tell us\n\t\tString parts[] = packVersion.split(\"\\\\.\");\n\t\ttry {\n\t\t\tint mcuParts[] = { MAJOR_VERSION, MINOR_VERSION, BUILD_VERSION };\n\t\t\tfor( int q = 0; q < mcuParts.length && q < parts.length; ++q ) {\n\t\t\t\tint packPart = Integer.valueOf(parts[q]);\n\t\t\t\tif( packPart > mcuParts[q] ) return true;\n\t\t\t\tif( packPart < mcuParts[q] ) return false; // Since we check major, then minor, then build, if the required value < current value, we can stop checking.\n\t\t\t}\n\t\t\treturn false;\n\t\t} catch( NumberFormatException e ) {\n\t\t\tlog(\"Got non-numerical pack format version '\"+packVersion+\"'\");\n\t\t} catch( ArrayIndexOutOfBoundsException e ) {\n\t\t\tlog(\"Got malformed pack format version '\"+packVersion+\"'\");\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic static boolean requestedFeatureLevel(String packVersion, String featureLevelVersion) {\n\t\tString packParts[] = packVersion.split(\"\\\\.\");\n\t\tString featureParts[] = featureLevelVersion.split(\"\\\\.\");\n\t\ttry {\n\t\t\tfor (int q = 0; q < featureParts.length; ++q ) {\n\t\t\t\tif (Integer.valueOf(packParts[q]) > Integer.valueOf(featureParts[q])) return true;\n\t\t\t\tif (Integer.valueOf(packParts[q]) < Integer.valueOf(featureParts[q])) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t} catch( NumberFormatException e ) {\n\t\t\tlog(\"Got non-numerical pack format version '\"+packVersion+\"'\");\n\t\t} catch( ArrayIndexOutOfBoundsException e ) {\n\t\t\tlog(\"Got malformed pack format version '\"+packVersion+\"'\");\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic static boolean isMasterBranch() {\n\t\treturn BUILD_BRANCH.equals(\"master\");\n\t}\n\tpublic static boolean isDevBranch() {\n\t\treturn BUILD_BRANCH.equals(\"develop\");\n\t}\n\t\n\t// for error logging support\n\tpublic static void setApp( MCUApp app ) {\n\t\t_app = app;\n\t}\n\tprivate static MCUApp _app;\n\tprivate static void log(String msg) {\n\t\tif( _app != null ) {\n\t\t\t_app.log(msg);\n\t\t} else {\n\t\t\tSystem.out.println(msg);\n\t\t}\n\t}\n}", "public class LoginData {\n\tprivate String userName = \"\";\n\tprivate String latestVersion = \"\";\n\tprivate String sessionId = \"\";\n\tprivate String UUID = \"\";\n\n\tpublic LoginData() {\n\t}\n\t\n\tpublic String getUserName() {\n\t\treturn userName;\n\t}\n\tpublic void setUserName(String userName) {\n\t\tthis.userName = userName;\n\t}\n\tpublic String getLatestVersion() {\n\t\treturn latestVersion;\n\t}\n\tpublic void setLatestVersion(String latestVersion) {\n\t\tthis.latestVersion = latestVersion;\n\t}\n\tpublic String getSessionId() {\n\t\treturn sessionId;\n\t}\n\tpublic void setSessionId(String sessionId) {\n\t\tthis.sessionId = sessionId;\n\t}\n\n\tpublic String getUUID() {\n\t\treturn UUID;\n\t}\n\n\tpublic void setUUID(String uUID) {\n\t\tUUID = uUID;\n\t}\n}", "public class HTTPSUtils {\n\n\tpublic static String buildQuery(Map<String, Object> paramMap) {\n\t\tStringBuilder localStringBuilder = new StringBuilder();\n\n\t\tfor (Map.Entry<String, Object> localEntry : paramMap.entrySet()) {\n\t\t\tif (localStringBuilder.length() > 0) {\n\t\t\t\tlocalStringBuilder.append('&');\n\t\t\t}\n\t\t\ttry\n\t\t\t{\n\t\t\t\tlocalStringBuilder.append(URLEncoder.encode((String)localEntry.getKey(), \"UTF-8\"));\n\t\t\t} catch (UnsupportedEncodingException localUnsupportedEncodingException1) {\n\t\t\t\tlocalUnsupportedEncodingException1.printStackTrace();\n\t\t\t}\n\n\t\t\tif (localEntry.getValue() != null) {\n\t\t\t\tlocalStringBuilder.append('=');\n\t\t\t\ttry {\n\t\t\t\t\tlocalStringBuilder.append(URLEncoder.encode(localEntry.getValue().toString(), \"UTF-8\"));\n\t\t\t\t} catch (UnsupportedEncodingException localUnsupportedEncodingException2) {\n\t\t\t\t\tlocalUnsupportedEncodingException2.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn localStringBuilder.toString();\n\t}\n\n\tpublic static String executePost(String postURL, Map<String, Object> paramMap) {\n\t\treturn executePost(postURL, buildQuery(paramMap));\n\t}\n\n\tpublic static String executePost(String postURL, String postQuery)\n\t{\n\t\tHttpsURLConnection localHttpsURLConnection = null;\n\t\ttry\n\t\t{\n\t\t\tURL localURL = new URL(postURL);\n\t\t\tlocalHttpsURLConnection = (HttpsURLConnection)localURL.openConnection();\n\t\t\tlocalHttpsURLConnection.setRequestMethod(\"POST\");\n\t\t\tlocalHttpsURLConnection.setRequestProperty(\"Content-Type\", \"application/x-www-form-urlencoded\");\n\n\t\t\tlocalHttpsURLConnection.setRequestProperty(\"Content-Length\", \"\" + Integer.toString(postQuery.getBytes().length));\n\t\t\tlocalHttpsURLConnection.setRequestProperty(\"Content-Language\", \"en-US\");\n\n\t\t\tlocalHttpsURLConnection.setUseCaches(false);\n\t\t\tlocalHttpsURLConnection.setDoInput(true);\n\t\t\tlocalHttpsURLConnection.setDoOutput(true);\n\t\t\t\n\t\t\tlocalHttpsURLConnection.setConnectTimeout(MCUpdater.getInstance().getTimeout());\n\t\t\tlocalHttpsURLConnection.setReadTimeout(MCUpdater.getInstance().getTimeout());\n\n\t\t\tlocalHttpsURLConnection.connect();\n\t\t\tCertificate[] arrayOfCertificate = localHttpsURLConnection.getServerCertificates();\n\n\t\t\tbyte[] arrayOfByte1 = new byte[294];\n\t\t\tDataInputStream localDataInputStream = new DataInputStream(HTTPSUtils.class.getResourceAsStream(\"minecraft.key\"));\n\t\t\tlocalDataInputStream.readFully(arrayOfByte1);\n\t\t\tlocalDataInputStream.close();\n\n\t\t\tCertificate localCertificate = arrayOfCertificate[0];\n\t\t\tPublicKey localPublicKey = localCertificate.getPublicKey();\n\t\t\tbyte[] arrayOfByte2 = localPublicKey.getEncoded();\n\n\t\t\tfor (int i = 0; i < arrayOfByte2.length; i++) {\n\t\t\t\tif (arrayOfByte2[i] != arrayOfByte1[i]) throw new RuntimeException(\"Public key mismatch\");\n\n\t\t\t}\n\n\t\t\tDataOutputStream localDataOutputStream = new DataOutputStream(localHttpsURLConnection.getOutputStream());\n\t\t\tlocalDataOutputStream.writeBytes(postQuery);\n\t\t\tlocalDataOutputStream.flush();\n\t\t\tlocalDataOutputStream.close();\n\n\t\t\tInputStream localInputStream = localHttpsURLConnection.getInputStream();\n\t\t\tBufferedReader localBufferedReader = new BufferedReader(new InputStreamReader(localInputStream));\n\n\t\t\tStringBuffer localStringBuffer = new StringBuffer();\n\t\t\tString str1;\n\t\t\twhile ((str1 = localBufferedReader.readLine()) != null) {\n\t\t\t\tlocalStringBuffer.append(str1);\n\t\t\t\tlocalStringBuffer.append('\\r');\n\t\t\t}\n\t\t\tlocalBufferedReader.close();\n\n\t\t\treturn localStringBuffer.toString();\n\t\t}\n\t\tcatch (Exception localException)\n\t\t{\n\t\t\tlocalException.printStackTrace();\n\t\t\treturn null;\n\t\t}\n\t\tfinally\n\t\t{\n\t\t\tif (localHttpsURLConnection != null)\n\t\t\t\tlocalHttpsURLConnection.disconnect();\n\t\t}\n\t}\n}", "public class MCLoginException extends Exception {\n\t\n\tpublic enum ResponseType {\n\t\tNOCONNECTION(\"Unable to connect to minecraft.net\"),\n\t\tBADLOGIN(\"Login Failed\"),\n\t\tOLDVERSION(\"Old Version\"),\n\t\tOLDLAUNCHER(\"Outdated Launcher\"),\n\t\tNOTPREMIUM(\"User not premium\");\n\t\t\n\t\tpublic String message;\n\t\t\n\t\tResponseType (String message) {\n\t\t\tthis.message = message;\n\t\t}\n\t}\n\t\n\tprivate static final long serialVersionUID = -8012092277739360133L;\n\t\n\tpublic MCLoginException(ResponseType response) {\n\t\tsuper(response.message);\n\t}\n\n\tpublic MCLoginException(String message) {\n\t\tsuper(message);\n\t}\n\t\n}", "public enum ResponseType {\n\tNOCONNECTION(\"Unable to connect to minecraft.net\"),\n\tBADLOGIN(\"Login Failed\"),\n\tOLDVERSION(\"Old Version\"),\n\tOLDLAUNCHER(\"Outdated Launcher\"),\n\tNOTPREMIUM(\"User not premium\");\n\t\t\n\tpublic String message;\n\t\t\n\tResponseType (String message) {\n\t\tthis.message = message;\n\t}\n}" ]
import java.util.HashMap; import java.util.logging.Level; import org.mcupdater.Version; import org.mcupdater.model.LoginData; import org.mcupdater.util.HTTPSUtils; import org.mcupdater.util.MCLoginException; import org.mcupdater.util.MCLoginException.ResponseType;
package org.mcupdater.util; public class MCLegacyAuth { public static LoginData login(String username, String password) throws Exception { try { HashMap<String, Object> localHashMap = new HashMap<String, Object>(); localHashMap.put("user", username); localHashMap.put("password", password); localHashMap.put("version", Integer.valueOf(13)); String str = HTTPSUtils.executePost("https://login.minecraft.net/", localHashMap); if (str == null) { //showError("Can't connect to minecraft.net"); throw new MCLoginException(ResponseType.NOCONNECTION); } if (!str.contains(":")) { if (str.trim().equals("Bad login")) { throw new MCLoginException(ResponseType.BADLOGIN); } else if (str.trim().equals("Old version")) { throw new MCLoginException(ResponseType.OLDVERSION); } else if (str.trim().equals("User not premium")) { throw new MCLoginException(ResponseType.OLDLAUNCHER); } else { throw new MCLoginException(str); } }
if (!Version.isMasterBranch()) {
0
jeick/jamod
src/main/java/net/wimpi/modbus/io/ModbusBINTransport.java
[ "public interface Modbus {\n\n\t/**\n\t * JVM flag for debug mode. Can be set passing the system property\n\t * net.wimpi.modbus.debug=false|true (-D flag to the jvm).\n\t */\n\tpublic static final boolean debug = \"true\".equals(System\n\t\t\t.getProperty(\"net.wimpi.modbus.debug\"));\n\n\t/**\n\t * Defines the class 0 function code for <tt>read multiple registers</tt>.\n\t */\n\tpublic static final int READ_MULTIPLE_REGISTERS = 3;\n\n\t/**\n\t * Defines the class 0 function code for <tt>write multiple registers</tt>.\n\t */\n\tpublic static final int WRITE_MULTIPLE_REGISTERS = 16;\n\n\t/**\n\t * Defines the class 1 function code for <tt>read coils</tt>.\n\t */\n\tpublic static final int READ_COILS = 1;\n\n\t/**\n\t * Defines a class 1 function code for <tt>read input discretes</tt>.\n\t */\n\tpublic static final int READ_INPUT_DISCRETES = 2;\n\n\t/**\n\t * Defines a class 1 function code for <tt>read input registers</tt>.\n\t */\n\tpublic static final int READ_INPUT_REGISTERS = 4;\n\n\t/**\n\t * Defines a class 1 function code for <tt>write coil</tt>.\n\t */\n\tpublic static final int WRITE_COIL = 5;\n\n\t/**\n\t * Defines a standard function code for <tt>write multiple coils</tt>.\n\t */\n\tpublic static final int WRITE_MULTIPLE_COILS = 15;\n\n\t/**\n\t * Defines a class 1 function code for <tt>write single register</tt>.\n\t */\n\tpublic static final int WRITE_SINGLE_REGISTER = 6;\n\n\t/**\n\t * Defines the byte representation of the coil state <b>on</b>.\n\t */\n\tpublic static final int COIL_ON = (byte) 255;\n\n\t/**\n\t * Defines the byte representation of the coil state <b>pos</b>.\n\t */\n\tpublic static final int COIL_OFF = 0;\n\n\t/**\n\t * Defines the word representation of the coil state <b>on</b>.\n\t */\n\tpublic static final byte[] COIL_ON_BYTES = { (byte) COIL_ON,\n\t\t\t(byte) COIL_OFF };\n\n\t/**\n\t * Defines the word representation of the coil state <b>pos</b>.\n\t */\n\tpublic static final byte[] COIL_OFF_BYTES = { (byte) COIL_OFF,\n\t\t\t(byte) COIL_OFF };\n\n\t/**\n\t * Defines the maximum number of bits in multiple read/write of input\n\t * discretes or coils (<b>2000</b>).\n\t */\n\tpublic static final int MAX_BITS = 2000;\n\n\t/**\n\t * Defines the Modbus slave exception offset that is added to the function\n\t * code, to flag an exception.\n\t */\n\tpublic static final int EXCEPTION_OFFSET = 128; // the last valid function\n\t\t\t\t\t\t\t\t\t\t\t\t\t// code is 127\n\n\t/**\n\t * Defines the Modbus slave exception type <tt>illegal function</tt>. This\n\t * exception code is returned if the slave:\n\t * <ul>\n\t * <li>does not implement the function code <b>or</b></li>\n\t * <li>is not in a state that allows it to process the function</li>\n\t * </ul>\n\t */\n\tpublic static final int ILLEGAL_FUNCTION_EXCEPTION = 1;\n\n\t/**\n\t * Defines the Modbus slave exception type <tt>illegal data address</tt>.\n\t * This exception code is returned if the reference:\n\t * <ul>\n\t * <li>does not exist on the slave <b>or</b></li>\n\t * <li>the combination of reference and length exceeds the bounds of the\n\t * existing registers.</li>\n\t * </ul>\n\t */\n\tpublic static final int ILLEGAL_ADDRESS_EXCEPTION = 2;\n\n\t/**\n\t * Defines the Modbus slave exception type <tt>illegal data value</tt>. This\n\t * exception code indicates a fault in the structure of the data values of a\n\t * complex request, such as an incorrect implied length.<br>\n\t * <b>This code does not indicate a problem with application specific\n\t * validity of the value.</b>\n\t */\n\tpublic static final int ILLEGAL_VALUE_EXCEPTION = 3;\n\n\t/**\n\t * Defines the default port number of Modbus (=<tt>502</tt>).\n\t */\n\tpublic static final int DEFAULT_PORT = 502;\n\n\t/**\n\t * Defines the maximum message length for serial transport in bytes (=\n\t * <tt>256</tt>). RS232 / RS485 ADU = 253 bytes + Server address (1 byte) +\n\t * CRC (2 bytes) = 256 bytes.\n\t */\n\tpublic static final int MAX_MESSAGE_LENGTH = 256;\n\n\t/**\n\t * Defines the maximum message length for IP transport in bytes (=\n\t * <tt>260</tt>). TCP MODBUS ADU = 253 bytes + MBAP (7 bytes) = 260 bytes.\n\t */\n\tpublic static final int MAX_IP_MESSAGE_LENGTH = 260;\n\n\t/**\n\t * Defines the default transaction identifier (=<tt>0</tt>).\n\t */\n\tpublic static final int DEFAULT_TRANSACTION_ID = 0;\n\n\t/**\n\t * Defines the default protocol identifier (=<tt>0</tt>).\n\t */\n\tpublic static final int DEFAULT_PROTOCOL_ID = 0;\n\n\t/**\n\t * Defines the default unit identifier (=<tt>0</tt>).\n\t */\n\tpublic static final int DEFAULT_UNIT_ID = 0;\n\n\t/**\n\t * Defines the default setting for validity checking in transactions (=\n\t * <tt>true</tt>).\n\t */\n\tpublic static final boolean DEFAULT_VALIDITYCHECK = true;\n\n\t/**\n\t * Defines the default setting for I/O operation timeouts in milliseconds (=\n\t * <tt>3000</tt>).\n\t */\n\tpublic static final int DEFAULT_TIMEOUT = 3000;\n\n\t/**\n\t * Defines the default reconnecting setting for transactions (=\n\t * <tt>false</tt>).\n\t */\n\tpublic static final boolean DEFAULT_RECONNECTING = false;\n\n\t/**\n\t * Defines the default amount of retires for opening a connection (=\n\t * <tt>3</tt>).\n\t */\n\tpublic static final int DEFAULT_RETRIES = 3;\n\n\t/**\n\t * Defines the default number of msec to delay before transmission (=\n\t * <tt>50</tt>).\n\t */\n\tpublic static final int DEFAULT_TRANSMIT_DELAY = 0;\n\n\t/**\n\t * Defines the maximum value of the transaction identifier.\n\t */\n\tpublic static final int MAX_TRANSACTION_ID = (Short.MAX_VALUE * 2) - 1;\n\n\t/**\n\t * Defines the serial encoding \"ASCII\".\n\t */\n\tpublic static final String SERIAL_ENCODING_ASCII = \"ascii\";\n\n\t/**\n\t * Defines the serial encoding \"RTU\".\n\t */\n\tpublic static final String SERIAL_ENCODING_RTU = \"rtu\";\n\n\t/**\n\t * Defines the serial encoding \"BIN\".\n\t */\n\tpublic static final String SERIAL_ENCODING_BIN = \"bin\";\n\n\t/**\n\t * Defines the default serial encoding (ASCII).\n\t */\n\tpublic static final String DEFAULT_SERIAL_ENCODING = SERIAL_ENCODING_ASCII;\n\n}// class Modbus", "public class ModbusCoupler {\n\n\t// class attributes\n\tprivate static ModbusCoupler c_Self; // Singleton reference\n\n\t// instance attributes\n\tprivate ProcessImage m_ProcessImage;\n\tprivate int m_UnitID = Modbus.DEFAULT_UNIT_ID;\n\tprivate boolean m_Master = true;\n\tprivate ProcessImageFactory m_PIFactory;\n\n\tstatic {\n\t\tc_Self = new ModbusCoupler();\n\t}// initializer\n\n\tprivate ModbusCoupler() {\n\t\tm_PIFactory = new DefaultProcessImageFactory();\n\t}// constructor\n\n\t/**\n\t * Private constructor to prevent multiple instantiation.\n\t * <p/>\n\t * \n\t * @param procimg\n\t * a <tt>ProcessImage</tt>.\n\t */\n\tprivate ModbusCoupler(ProcessImage procimg) {\n\t\tsetProcessImage(procimg);\n\t\tc_Self = this;\n\t}// contructor(ProcessImage)\n\n\t/**\n\t * Returns the actual <tt>ProcessImageFactory</tt> instance.\n\t * \n\t * @return a <tt>ProcessImageFactory</tt> instance.\n\t */\n\tpublic ProcessImageFactory getProcessImageFactory() {\n\t\treturn m_PIFactory;\n\t}// getProcessImageFactory\n\n\t/**\n\t * Sets the <tt>ProcessImageFactory</tt> instance.\n\t * \n\t * @param factory\n\t * the instance to be used for creating process image instances.\n\t */\n\tpublic void setProcessImageFactory(ProcessImageFactory factory) {\n\t\tm_PIFactory = factory;\n\t}// setProcessImageFactory\n\n\t/**\n\t * Returns a reference to the <tt>ProcessImage</tt> of this\n\t * <tt>ModbusCoupler</tt>.\n\t * <p/>\n\t * \n\t * @return the <tt>ProcessImage</tt>.\n\t */\n\tpublic synchronized ProcessImage getProcessImage() {\n\t\treturn m_ProcessImage;\n\t}// getProcessImage\n\n\t/**\n\t * Sets the reference to the <tt>ProcessImage</tt> of this\n\t * <tt>ModbusCoupler</tt>.\n\t * <p/>\n\t * \n\t * @param procimg\n\t * the <tt>ProcessImage</tt> to be set.\n\t */\n\tpublic synchronized void setProcessImage(ProcessImage procimg) {\n\t\tm_ProcessImage = procimg;\n\t}// setProcessImage\n\n\t/**\n\t * Returns the identifier of this unit. This identifier is required to be\n\t * set for serial protocol slave implementations.\n\t * \n\t * @return the unit identifier as <tt>int</tt>.\n\t */\n\tpublic int getUnitID() {\n\t\treturn m_UnitID;\n\t}// getUnitID\n\n\t/**\n\t * Sets the identifier of this unit, which is needed to be determined in a\n\t * serial network.\n\t * \n\t * @param id\n\t * the new unit identifier as <tt>int</tt>.\n\t */\n\tpublic void setUnitID(int id) {\n\t\tm_UnitID = id;\n\t}// setUnitID\n\n\t/**\n\t * Tests if this instance is a master device.\n\t * \n\t * @return true if master, false otherwise.\n\t */\n\tpublic boolean isMaster() {\n\t\treturn m_Master;\n\t}// isMaster\n\n\t/**\n\t * Tests if this instance is not a master device.\n\t * \n\t * @return true if slave, false otherwise.\n\t */\n\tpublic boolean isSlave() {\n\t\treturn !m_Master;\n\t}// isSlave\n\n\t/**\n\t * Sets this instance to be or not to be a master device.\n\t * \n\t * @param master\n\t * true if master device, false otherwise.\n\t */\n\tpublic void setMaster(boolean master) {\n\t\tm_Master = master;\n\t}// setMaster\n\n\t/**\n\t * Returns a reference to the singleton instance.\n\t * <p/>\n\t * \n\t * @return the <tt>ModbusCoupler</tt> instance reference.\n\t */\n\tpublic static final ModbusCoupler getReference() {\n\t\treturn c_Self;\n\t}// getReference\n\n}// class ModbusCoupler", "@SuppressWarnings(\"serial\")\npublic class ModbusIOException extends ModbusException {\n\n\tprivate boolean m_EOF = false;\n\n\t/**\n\t * Constructs a new <tt>ModbusIOException</tt> instance.\n\t */\n\tpublic ModbusIOException() {\n\t}// constructor\n\n\t/**\n\t * Constructs a new <tt>ModbusIOException</tt> instance with the given\n\t * message.\n\t * <p>\n\t * \n\t * @param message\n\t * the message describing this <tt>ModbusIOException</tt>.\n\t */\n\tpublic ModbusIOException(String message) {\n\t\tsuper(message);\n\t}// constructor(String)\n\n\t/**\n\t * Constructs a new <tt>ModbusIOException</tt> instance.\n\t * \n\t * @param b\n\t * true if caused by end of stream, false otherwise.\n\t */\n\tpublic ModbusIOException(boolean b) {\n\t\tm_EOF = b;\n\t}// constructor\n\n\t/**\n\t * Constructs a new <tt>ModbusIOException</tt> instance with the given\n\t * message.\n\t * <p>\n\t * \n\t * @param message\n\t * the message describing this <tt>ModbusIOException</tt>.\n\t * @param b\n\t * true if caused by end of stream, false otherwise.\n\t */\n\tpublic ModbusIOException(String message, boolean b) {\n\t\tsuper(message);\n\t\tm_EOF = b;\n\t}// constructor(String)\n\n\t/**\n\t * Tests if this <tt>ModbusIOException</tt> is caused by an end of the\n\t * stream.\n\t * <p>\n\t * \n\t * @return true if stream ended, false otherwise.\n\t */\n\tpublic boolean isEOF() {\n\t\treturn m_EOF;\n\t}// isEOF\n\n\t/**\n\t * Sets the flag that determines whether this <tt>ModbusIOException</tt> was\n\t * caused by an end of the stream.\n\t * <p>\n\t * \n\t * @param b\n\t * true if stream ended, false otherwise.\n\t */\n\tpublic void setEOF(boolean b) {\n\t\tm_EOF = b;\n\t}// setEOF\n\n}// ModbusIOException", "public final class ModbusUtil {\n\n\tprivate static BytesOutputStream m_ByteOut = new BytesOutputStream(\n\t\t\tModbus.MAX_IP_MESSAGE_LENGTH);\n\n\t/**\n\t * Converts a <tt>ModbusMessage</tt> instance into a hex encoded string\n\t * representation.\n\t * \n\t * @param msg\n\t * the message to be converted.\n\t * @return the converted hex encoded string representation of the message.\n\t */\n\tpublic static final String toHex(ModbusMessage msg) {\n\t\tString ret = \"-1\";\n\t\ttry {\n\t\t\tsynchronized (m_ByteOut) {\n\t\t\t\tmsg.writeTo(m_ByteOut);\n\t\t\t\tret = toHex(m_ByteOut.getBuffer(), 0, m_ByteOut.size());\n\t\t\t\tm_ByteOut.reset();\n\t\t\t}\n\t\t} catch (IOException ex) {\n\t\t}\n\t\treturn ret;\n\t}// toHex\n\n\t/**\n\t * Returns the given byte[] as hex encoded string.\n\t * \n\t * @param data\n\t * a byte[] array.\n\t * @return a hex encoded String.\n\t */\n\tpublic static final String toHex(byte[] data) {\n\t\treturn toHex(data, 0, data.length);\n\t}// toHex\n\n\t/**\n\t * Returns a <tt>String</tt> containing unsigned hexadecimal numbers as\n\t * digits. The <tt>String</tt> will coontain two hex digit characters for\n\t * each byte from the passed in <tt>byte[]</tt>.<br>\n\t * The bytes will be separated by a space character.\n\t * <p/>\n\t * \n\t * @param data\n\t * the array of bytes to be converted into a hex-string.\n\t * @param off\n\t * the offset to start converting from.\n\t * @param length\n\t * the number of bytes to be converted.\n\t * \n\t * @return the generated hexadecimal representation as <code>String</code>.\n\t */\n\tpublic static final String toHex(byte[] data, int off, int length) {\n\t\t// double size, two bytes (hex range) for one byte\n\t\tStringBuffer buf = new StringBuffer(data.length * 2);\n\t\tfor (int i = off; i < length; i++) {\n\t\t\t// don't forget the second hex digit\n\t\t\tif (((int) data[i] & 0xff) < 0x10) {\n\t\t\t\tbuf.append(\"0\");\n\t\t\t}\n\t\t\tbuf.append(Long.toString((int) data[i] & 0xff, 16));\n\t\t\tif (i < data.length - 1) {\n\t\t\t\tbuf.append(\" \");\n\t\t\t}\n\t\t}\n\t\treturn buf.toString();\n\t}// toHex\n\n\t/**\n\t * Returns a <tt>byte[]</tt> containing the given byte as unsigned\n\t * hexadecimal number digits.\n\t * <p/>\n\t * \n\t * @param i\n\t * the int to be converted into a hex string.\n\t * @return the generated hexadecimal representation as <code>byte[]</code>.\n\t */\n\tpublic static final byte[] toHex(int i) {\n\t\tStringBuffer buf = new StringBuffer(2);\n\t\t// don't forget the second hex digit\n\t\tif (((int) i & 0xff) < 0x10) {\n\t\t\tbuf.append(\"0\");\n\t\t}\n\t\tbuf.append(Long.toString((int) i & 0xff, 16).toUpperCase());\n\t\treturn buf.toString().getBytes();\n\t}// toHex\n\n\t/**\n\t * Converts the register (a 16 bit value) into an unsigned short. The value\n\t * returned is:\n\t * <p>\n\t * \n\t * <pre>\n\t * <code>(((a &amp; 0xff) &lt;&lt; 8) | (b &amp; 0xff))\n\t * </code>\n\t * </pre>\n\t * <p/>\n\t * This conversion has been taken from the documentation of the\n\t * <tt>DataInput</tt> interface.\n\t * \n\t * @param bytes\n\t * a register as <tt>byte[2]</tt>.\n\t * @return the unsigned short value as <tt>int</tt>.\n\t * @see java.io.DataInput\n\t */\n\tpublic static final int registerToUnsignedShort(byte[] bytes) {\n\t\treturn ((bytes[0] & 0xff) << 8 | (bytes[1] & 0xff));\n\t}// registerToUnsignedShort\n\n\t/**\n\t * Converts the given unsigned short into a register (2 bytes). The byte\n\t * values in the register, in the order shown, are:\n\t * <p/>\n\t * \n\t * <pre>\n\t * <code>\n\t * (byte)(0xff &amp; (v &gt;&gt; 8))\n\t * (byte)(0xff &amp; v)\n\t * </code>\n\t * </pre>\n\t * <p/>\n\t * This conversion has been taken from the documentation of the\n\t * <tt>DataOutput</tt> interface.\n\t * \n\t * @param v\n\t * @return the register as <tt>byte[2]</tt>.\n\t * @see java.io.DataOutput\n\t */\n\tpublic static final byte[] unsignedShortToRegister(int v) {\n\t\tbyte[] register = new byte[2];\n\t\tregister[0] = (byte) (0xff & (v >> 8));\n\t\tregister[1] = (byte) (0xff & v);\n\t\treturn register;\n\t}// unsignedShortToRegister\n\n\t/**\n\t * Converts the given register (16-bit value) into a <tt>short</tt>. The\n\t * value returned is:\n\t * <p/>\n\t * \n\t * <pre>\n\t * <code>\n\t * (short)((a &lt;&lt; 8) | (b &amp; 0xff))\n\t * </code>\n\t * </pre>\n\t * <p/>\n\t * This conversion has been taken from the documentation of the\n\t * <tt>DataInput</tt> interface.\n\t * \n\t * @param bytes\n\t * bytes a register as <tt>byte[2]</tt>.\n\t * @return the signed short as <tt>short</tt>.\n\t */\n\tpublic static final short registerToShort(byte[] bytes) {\n\t\treturn (short) ((bytes[0] << 8) | (bytes[1] & 0xff));\n\t}// registerToShort\n\n\t/**\n\t * Converts the register (16-bit value) at the given index into a\n\t * <tt>short</tt>. The value returned is:\n\t * <p/>\n\t * \n\t * <pre>\n\t * <code>\n\t * (short)((a &lt;&lt; 8) | (b &amp; 0xff))\n\t * </code>\n\t * </pre>\n\t * <p/>\n\t * This conversion has been taken from the documentation of the\n\t * <tt>DataInput</tt> interface.\n\t * \n\t * @param bytes\n\t * a <tt>byte[]</tt> containing a short value.\n\t * @param idx\n\t * an offset into the given byte[].\n\t * @return the signed short as <tt>short</tt>.\n\t */\n\tpublic static final short registerToShort(byte[] bytes, int idx) {\n\t\treturn (short) ((bytes[idx] << 8) | (bytes[idx + 1] & 0xff));\n\t}// registerToShort\n\n\t/**\n\t * Converts the given <tt>short</tt> into a register (2 bytes). The byte\n\t * values in the register, in the order shown, are:\n\t * <p/>\n\t * \n\t * <pre>\n\t * <code>\n\t * (byte)(0xff &amp; (v &gt;&gt; 8))\n\t * (byte)(0xff &amp; v)\n\t * </code>\n\t * </pre>\n\t * \n\t * @param s\n\t * @return a register containing the given short value.\n\t */\n\tpublic static final byte[] shortToRegister(short s) {\n\t\tbyte[] register = new byte[2];\n\t\tregister[0] = (byte) (0xff & (s >> 8));\n\t\tregister[1] = (byte) (0xff & s);\n\t\treturn register;\n\t}// shortToRegister\n\n\t/**\n\t * Converts a byte[4] binary int value to a primitive int.<br>\n\t * The value returned is:\n\t * <p>\n\t * \n\t * <pre>\n\t * <code>\n\t * (((a &amp; 0xff) &lt;&lt; 24) | ((b &amp; 0xff) &lt;&lt; 16) |\n\t * &#32;((c &amp; 0xff) &lt;&lt; 8) | (d &amp; 0xff))\n\t * </code>\n\t * </pre>\n\t * \n\t * @param bytes\n\t * registers as <tt>byte[4]</tt>.\n\t * @return the integer contained in the given register bytes.\n\t */\n\tpublic static final int registersToInt(byte[] bytes) {\n\t\treturn (((bytes[0] & 0xff) << 24) | ((bytes[1] & 0xff) << 16)\n\t\t\t\t| ((bytes[2] & 0xff) << 8) | (bytes[3] & 0xff));\n\t}// registersToInt\n\n\t/**\n\t * Converts an int value to a byte[4] array.\n\t * \n\t * @param v\n\t * the value to be converted.\n\t * @return a byte[4] containing the value.\n\t */\n\tpublic static final byte[] intToRegisters(int v) {\n\t\tbyte[] registers = new byte[4];\n\t\tregisters[0] = (byte) (0xff & (v >> 24));\n\t\tregisters[1] = (byte) (0xff & (v >> 16));\n\t\tregisters[2] = (byte) (0xff & (v >> 8));\n\t\tregisters[3] = (byte) (0xff & v);\n\t\treturn registers;\n\t}// intToRegisters\n\n\t/**\n\t * Converts a byte[8] binary long value into a long primitive.\n\t * \n\t * @param bytes\n\t * a byte[8] containing a long value.\n\t * @return a long value.\n\t */\n\tpublic static final long registersToLong(byte[] bytes) {\n\t\treturn ((((long) (bytes[0] & 0xff) << 56)\n\t\t\t\t| ((long) (bytes[1] & 0xff) << 48)\n\t\t\t\t| ((long) (bytes[2] & 0xff) << 40)\n\t\t\t\t| ((long) (bytes[3] & 0xff) << 32)\n\t\t\t\t| ((long) (bytes[4] & 0xff) << 24)\n\t\t\t\t| ((long) (bytes[5] & 0xff) << 16)\n\t\t\t\t| ((long) (bytes[6] & 0xff) << 8) | ((long) (bytes[7] & 0xff))));\n\t}// registersToLong\n\n\t/**\n\t * Converts a long value to a byte[8].\n\t * \n\t * @param v\n\t * the value to be converted.\n\t * @return a byte[8] containing the long value.\n\t */\n\tpublic static final byte[] longToRegisters(long v) {\n\t\tbyte[] registers = new byte[8];\n\t\tregisters[0] = (byte) (0xff & (v >> 56));\n\t\tregisters[1] = (byte) (0xff & (v >> 48));\n\t\tregisters[2] = (byte) (0xff & (v >> 40));\n\t\tregisters[3] = (byte) (0xff & (v >> 32));\n\t\tregisters[4] = (byte) (0xff & (v >> 24));\n\t\tregisters[5] = (byte) (0xff & (v >> 16));\n\t\tregisters[6] = (byte) (0xff & (v >> 8));\n\t\tregisters[7] = (byte) (0xff & v);\n\t\treturn registers;\n\t}// longToRegisters\n\n\t/**\n\t * Converts a byte[4] binary float value to a float primitive.\n\t * \n\t * @param bytes\n\t * the byte[4] containing the float value.\n\t * @return a float value.\n\t */\n\tpublic static final float registersToFloat(byte[] bytes) {\n\t\treturn Float\n\t\t\t\t.intBitsToFloat((((bytes[0] & 0xff) << 24)\n\t\t\t\t\t\t| ((bytes[1] & 0xff) << 16) | ((bytes[2] & 0xff) << 8) | (bytes[3] & 0xff)));\n\t}// registersToFloat\n\n\t/**\n\t * Converts a float value to a byte[4] binary float value.\n\t * \n\t * @param f\n\t * the float to be converted.\n\t * @return a byte[4] containing the float value.\n\t */\n\tpublic static final byte[] floatToRegisters(float f) {\n\t\treturn intToRegisters(Float.floatToIntBits(f));\n\t}// floatToRegisters\n\n\t/**\n\t * Converts a byte[8] binary double value into a double primitive.\n\t * \n\t * @param bytes\n\t * a byte[8] to be converted.\n\t * @return a double value.\n\t */\n\tpublic static final double registersToDouble(byte[] bytes) {\n\t\treturn Double\n\t\t\t\t.longBitsToDouble(((((long) (bytes[0] & 0xff) << 56)\n\t\t\t\t\t\t| ((long) (bytes[1] & 0xff) << 48)\n\t\t\t\t\t\t| ((long) (bytes[2] & 0xff) << 40)\n\t\t\t\t\t\t| ((long) (bytes[3] & 0xff) << 32)\n\t\t\t\t\t\t| ((long) (bytes[4] & 0xff) << 24)\n\t\t\t\t\t\t| ((long) (bytes[5] & 0xff) << 16)\n\t\t\t\t\t\t| ((long) (bytes[6] & 0xff) << 8) | ((long) (bytes[7] & 0xff)))));\n\t}// registersToDouble\n\n\t/**\n\t * Converts a double value to a byte[8].\n\t * \n\t * @param d\n\t * the double to be converted.\n\t * @return a byte[8].\n\t */\n\tpublic static final byte[] doubleToRegisters(double d) {\n\t\treturn longToRegisters(Double.doubleToLongBits(d));\n\t}// doubleToRegisters\n\n\t/**\n\t * Converts an unsigned byte to an integer.\n\t * \n\t * @param b\n\t * the byte to be converted.\n\t * @return an integer containing the unsigned byte value.\n\t */\n\tpublic static final int unsignedByteToInt(byte b) {\n\t\treturn (int) b & 0xFF;\n\t}// unsignedByteToInt\n\n\t/**\n\t * Returns the broadcast address for the subnet of the host the code is\n\t * executed on.\n\t * \n\t * @return the broadcast address as <tt>InetAddress</tt>.\n\t * <p/>\n\t * public static final InetAddress getBroadcastAddress() { byte[]\n\t * addr = new byte[4]; try { addr =\n\t * InetAddress.getLocalHost().getAddress(); addr[3] = -1; return\n\t * getAddressFromBytes(addr); } catch (Exception ex) {\n\t * ex.printStackTrace(); return null; } }//getBroadcastAddress\n\t */\n\n\t/*\n\t * public static final InetAddress getAddressFromBytes(byte[] addr) throws\n\t * Exception { StringBuffer sbuf = new StringBuffer(); for (int i = 0; i <\n\t * addr.length; i++) { if (addr[i] < 0) { sbuf.append(256 + addr[i]); } else\n\t * { sbuf.append(addr[i]); } if (i < (addr.length - 1)) { sbuf.append('.');\n\t * } } //DEBUG:System.out.println(sbuf.toString()); return\n\t * InetAddress.getByName(sbuf.toString()); }//getAddressFromBytes\n\t */\n\n\t// TODO: John description.\n\t/**\n\t * Returs the low byte of an integer word.\n\t * \n\t * @param wd\n\t * @return the low byte.\n\t */\n\tpublic static final byte lowByte(int wd) {\n\t\treturn (new Integer(0xff & wd).byteValue());\n\t}// lowByte\n\n\t// TODO: John description.\n\t/**\n\t * \n\t * @param wd\n\t * @return the hi byte.\n\t */\n\tpublic static final byte hiByte(int wd) {\n\t\treturn (new Integer(0xff & (wd >> 8)).byteValue());\n\t}// hiByte\n\n\t// TODO: John description.\n\t/**\n\t * \n\t * @param hibyte\n\t * @param lowbyte\n\t * @return a word.\n\t */\n\tpublic static final int makeWord(int hibyte, int lowbyte) {\n\t\tint hi = 0xFF & hibyte;\n\t\tint low = 0xFF & lowbyte;\n\t\treturn ((hi << 8) | low);\n\t}// makeWord\n\n\tpublic static final int[] calculateCRC(byte[] data, int offset, int len) {\n\n\t\tint[] crc = { 0xFF, 0xFF };\n\t\tint nextByte = 0;\n\t\tint uIndex; /* will index into CRC lookup *//* table */\n\t\t/* pass through message buffer */\n\t\tfor (int i = offset; i < len && i < data.length; i++) {\n\t\t\tnextByte = 0xFF & ((int) data[i]);\n\t\t\tuIndex = crc[0] ^ nextByte; // *puchMsg++; /* calculate the CRC */\n\t\t\tcrc[0] = crc[1] ^ auchCRCHi[uIndex];\n\t\t\tcrc[1] = auchCRCLo[uIndex];\n\t\t}\n\n\t\treturn crc;\n\t}// calculateCRC\n\n\tpublic static final int calculateLRC(byte[] data, int off, int len) {\n\t\tint lrc = 0;\n\t\tfor (int i = off; i < len; i++) {\n\t\t\tlrc += (int) data[i] & 0xff; // calculate with unsigned bytes\n\t\t}\n\t\tlrc = (lrc ^ 0xff) + 1; // two's complement\n\t\treturn (int) ((byte) lrc) & 0xff;\n\t}// calculateLRC\n\n\t/* Table of CRC values for high-order byte */\n\tprivate final static short[] auchCRCHi = { 0x00, 0xC1, 0x81, 0x40, 0x01,\n\t\t\t0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,\n\t\t\t0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81,\n\t\t\t0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,\n\t\t\t0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00,\n\t\t\t0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,\n\t\t\t0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81,\n\t\t\t0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,\n\t\t\t0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00,\n\t\t\t0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,\n\t\t\t0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80,\n\t\t\t0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,\n\t\t\t0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00,\n\t\t\t0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,\n\t\t\t0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81,\n\t\t\t0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,\n\t\t\t0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00,\n\t\t\t0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,\n\t\t\t0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80,\n\t\t\t0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,\n\t\t\t0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01,\n\t\t\t0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,\n\t\t\t0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80,\n\t\t\t0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40 };\n\n\t/* Table of CRC values for low-order byte */\n\tprivate final static short[] auchCRCLo = { 0x00, 0xC0, 0xC1, 0x01, 0xC3,\n\t\t\t0x03, 0x02, 0xC2, 0xC6, 0x06, 0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04,\n\t\t\t0xCC, 0x0C, 0x0D, 0xCD, 0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB,\n\t\t\t0x0B, 0xC9, 0x09, 0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB,\n\t\t\t0xDA, 0x1A, 0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, 0x14,\n\t\t\t0xD4, 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,\n\t\t\t0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3, 0xF2,\n\t\t\t0x32, 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4, 0x3C, 0xFC,\n\t\t\t0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A, 0x3B, 0xFB, 0x39,\n\t\t\t0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29, 0xEB, 0x2B, 0x2A, 0xEA,\n\t\t\t0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED, 0xEC, 0x2C, 0xE4, 0x24, 0x25,\n\t\t\t0xE5, 0x27, 0xE7, 0xE6, 0x26, 0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21,\n\t\t\t0x20, 0xE0, 0xA0, 0x60, 0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62, 0x66,\n\t\t\t0xA6, 0xA7, 0x67, 0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D,\n\t\t\t0xAF, 0x6F, 0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8,\n\t\t\t0x68, 0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, 0xBE, 0x7E,\n\t\t\t0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5, 0x77,\n\t\t\t0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71, 0x70, 0xB0,\n\t\t\t0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92, 0x96, 0x56, 0x57,\n\t\t\t0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C, 0x5D, 0x9D, 0x5F, 0x9F,\n\t\t\t0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B, 0x99, 0x59, 0x58, 0x98, 0x88,\n\t\t\t0x48, 0x49, 0x89, 0x4B, 0x8B, 0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F,\n\t\t\t0x8D, 0x4D, 0x4C, 0x8C, 0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46,\n\t\t\t0x86, 0x82, 0x42, 0x43, 0x83, 0x41, 0x81, 0x80, 0x40 };\n\n}// class ModBusUtil", "public interface ModbusMessage extends Transportable {\n\n\t/**\n\t * Sets the flag that marks this <tt>ModbusMessage</tt> as headless (for\n\t * serial transport).\n\t */\n\tpublic void setHeadless();\n\n\t/**\n\t * Returns the transaction identifier of this <tt>ModbusMessage</tt> as\n\t * <tt>int</tt>.<br>\n\t * The identifier is a 2-byte (short) non negative integer value valid in\n\t * the range of 0-65535.\n\t * <p>\n\t * \n\t * @return the transaction identifier as <tt>int</tt>.\n\t */\n\tpublic int getTransactionID();\n\n\t/**\n\t * Returns the protocol identifier of this <tt>ModbusMessage</tt> as\n\t * <tt>int</tt>.<br>\n\t * The identifier is a 2-byte (short) non negative integer value valid in\n\t * the range of 0-65535.\n\t * <p>\n\t * \n\t * @return the protocol identifier as <tt>int</tt>.\n\t */\n\tpublic int getProtocolID();\n\n\t/**\n\t * Returns the length of the data appended after the protocol header.\n\t * <p>\n\t * \n\t * @return the data length as <tt>int</tt>.\n\t */\n\tpublic int getDataLength();\n\n\t/**\n\t * Returns the unit identifier of this <tt>ModbusMessage</tt> as\n\t * <tt>int</tt>.<br>\n\t * The identifier is a 1-byte non negative integer value valid in the range\n\t * of 0-255.\n\t * <p>\n\t * \n\t * @return the unit identifier as <tt>int</tt>.\n\t */\n\tpublic int getUnitID();\n\n\t/**\n\t * Returns the function code of this <tt>ModbusMessage</tt> as <tt>int</tt>.<br>\n\t * The function code is a 1-byte non negative integer value valid in the\n\t * range of 0-127.<br>\n\t * Function codes are ordered in conformance classes their values are\n\t * specified in <tt>net.wimpi.modbus.Modbus</tt>.\n\t * <p>\n\t * \n\t * @return the function code as <tt>int</tt>.\n\t * \n\t * @see net.wimpi.modbus.Modbus\n\t */\n\tpublic int getFunctionCode();\n\n\t/**\n\t * Returns the <i>raw</i> message as <tt>String</tt> containing a\n\t * hexadecimal series of bytes. <br>\n\t * This method is specially for debugging purposes, allowing to log the\n\t * communication in a manner used in the specification document.\n\t * <p>\n\t * \n\t * @return the <i>raw</i> message as <tt>String</tt> containing a\n\t * hexadecimal series of bytes.\n\t * \n\t */\n\tpublic String getHexMessage();\n\n}// interface ModbusMessage", "public abstract class ModbusRequest extends ModbusMessageImpl {\n\n\t/**\n\t * Returns the <tt>ModbusResponse</tt> that correlates with this\n\t * <tt>ModbusRequest</tt>.\n\t * <p>\n\t * \n\t * @return the corresponding <tt>ModbusResponse</tt>.\n\t * \n\t * public abstract ModbusResponse getResponse();\n\t */\n\n\t/**\n\t * Returns the <tt>ModbusResponse</tt> that represents the answer to this\n\t * <tt>ModbusRequest</tt>.\n\t * <p>\n\t * The implementation should take care about assembling the reply to this\n\t * <tt>ModbusRequest</tt>.\n\t * <p>\n\t * \n\t * @return the corresponding <tt>ModbusResponse</tt>.\n\t */\n\tpublic abstract ModbusResponse createResponse();\n\n\t/**\n\t * Factory method for creating exception responses with the given exception\n\t * code.\n\t * \n\t * @param EXCEPTION_CODE\n\t * the code of the exception.\n\t * @return a ModbusResponse instance representing the exception response.\n\t */\n\tpublic ModbusResponse createExceptionResponse(int EXCEPTION_CODE) {\n\t\tExceptionResponse response = new ExceptionResponse(\n\t\t\t\tthis.getFunctionCode(), EXCEPTION_CODE);\n\t\tif (!isHeadless()) {\n\t\t\tresponse.setTransactionID(this.getTransactionID());\n\t\t\tresponse.setProtocolID(this.getProtocolID());\n\t\t\tresponse.setUnitID(this.getUnitID());\n\t\t} else {\n\t\t\tresponse.setHeadless();\n\t\t}\n\t\treturn response;\n\t}// createExceptionResponse\n\n\t/**\n\t * Factory method creating the required specialized <tt>ModbusRequest</tt>\n\t * instance.\n\t * \n\t * @param functionCode\n\t * the function code of the request as <tt>int</tt>.\n\t * @return a ModbusRequest instance specific for the given function type.\n\t */\n\tpublic static ModbusRequest createModbusRequest(int functionCode) {\n\t\tModbusRequest request = null;\n\n\t\tswitch (functionCode) {\n\t\tcase Modbus.READ_MULTIPLE_REGISTERS:\n\t\t\trequest = new ReadMultipleRegistersRequest();\n\t\t\tbreak;\n\t\tcase Modbus.READ_INPUT_DISCRETES:\n\t\t\trequest = new ReadInputDiscretesRequest();\n\t\t\tbreak;\n\t\tcase Modbus.READ_INPUT_REGISTERS:\n\t\t\trequest = new ReadInputRegistersRequest();\n\t\t\tbreak;\n\t\tcase Modbus.READ_COILS:\n\t\t\trequest = new ReadCoilsRequest();\n\t\t\tbreak;\n\t\tcase Modbus.WRITE_MULTIPLE_REGISTERS:\n\t\t\trequest = new WriteMultipleRegistersRequest();\n\t\t\tbreak;\n\t\tcase Modbus.WRITE_SINGLE_REGISTER:\n\t\t\trequest = new WriteSingleRegisterRequest();\n\t\t\tbreak;\n\t\tcase Modbus.WRITE_COIL:\n\t\t\trequest = new WriteCoilRequest();\n\t\t\tbreak;\n\t\tcase Modbus.WRITE_MULTIPLE_COILS:\n\t\t\trequest = new WriteMultipleCoilsRequest();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\trequest = new IllegalFunctionRequest(functionCode);\n\t\t\tbreak;\n\t\t}\n\t\treturn request;\n\t}// createModbusRequest\n\n\tpublic abstract int getReference();\n\n}// class ModbusRequest", "public abstract class ModbusResponse extends ModbusMessageImpl {\n\n\t/**\n\t * Utility method to set the raw data of the message. Should not be used\n\t * except under rare circumstances.\n\t * <p>\n\t * \n\t * @param msg\n\t * the <tt>byte[]</tt> resembling the raw modbus response\n\t * message.\n\t */\n\tprotected void setMessage(byte[] msg) {\n\t\ttry {\n\t\t\treadData(new DataInputStream(new ByteArrayInputStream(msg)));\n\t\t} catch (IOException ex) {\n\n\t\t}\n\t}// setMessage\n\n\t/**\n\t * Factory method creating the required specialized <tt>ModbusResponse</tt>\n\t * instance.\n\t * \n\t * @param functionCode\n\t * the function code of the response as <tt>int</tt>.\n\t * @return a ModbusResponse instance specific for the given function code.\n\t */\n\tpublic static ModbusResponse createModbusResponse(int functionCode) {\n\t\tModbusResponse response = null;\n\n\t\tswitch (functionCode) {\n\t\tcase Modbus.READ_MULTIPLE_REGISTERS:\n\t\t\tresponse = new ReadMultipleRegistersResponse();\n\t\t\tbreak;\n\t\tcase Modbus.READ_INPUT_DISCRETES:\n\t\t\tresponse = new ReadInputDiscretesResponse();\n\t\t\tbreak;\n\t\tcase Modbus.READ_INPUT_REGISTERS:\n\t\t\tresponse = new ReadInputRegistersResponse();\n\t\t\tbreak;\n\t\tcase Modbus.READ_COILS:\n\t\t\tresponse = new ReadCoilsResponse();\n\t\t\tbreak;\n\t\tcase Modbus.WRITE_MULTIPLE_REGISTERS:\n\t\t\tresponse = new WriteMultipleRegistersResponse();\n\t\t\tbreak;\n\t\tcase Modbus.WRITE_SINGLE_REGISTER:\n\t\t\tresponse = new WriteSingleRegisterResponse();\n\t\t\tbreak;\n\t\tcase Modbus.WRITE_COIL:\n\t\t\tresponse = new WriteCoilResponse();\n\t\t\tbreak;\n\t\tcase Modbus.WRITE_MULTIPLE_COILS:\n\t\t\tresponse = new WriteMultipleCoilsResponse();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tresponse = new ExceptionResponse();\n\t\t\tbreak;\n\t\t}\n\t\treturn response;\n\t}// createModbusResponse\n\n}// class ModbusResponse" ]
import net.wimpi.modbus.Modbus; import net.wimpi.modbus.ModbusCoupler; import net.wimpi.modbus.ModbusIOException; import net.wimpi.modbus.util.ModbusUtil; import net.wimpi.modbus.msg.ModbusMessage; import net.wimpi.modbus.msg.ModbusRequest; import net.wimpi.modbus.msg.ModbusResponse; import java.io.DataInputStream; import java.io.IOException; import jssc.SerialInputStream; import jssc.SerialOutputStream;
/*** * Copyright 2002-2010 jamod development team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ***/ package net.wimpi.modbus.io; /** * Class that implements the Modbus/BIN transport flavor. * * @author Dieter Wimberger * @version @version@ (@date@) */ public class ModbusBINTransport extends ModbusSerialTransport { private DataInputStream m_InputStream; // used to read from private ASCIIOutputStream m_OutputStream; // used to write to private byte[] m_InBuffer; private BytesInputStream m_ByteIn; // to read message from private BytesOutputStream m_ByteInOut; // to buffer message to private BytesOutputStream m_ByteOut; // write frames /** * Constructs a new <tt>MobusBINTransport</tt> instance. */ public ModbusBINTransport() { }// constructor public void close() throws IOException { m_InputStream.close(); m_OutputStream.close(); }// close
public void writeMessage(ModbusMessage msg) throws ModbusIOException {
4
occi4java/occi4java
http/src/main/java/occi/http/OcciRestNetworkInterface.java
[ "public class OcciConfig extends XMLConfiguration {\n\tprivate static final long serialVersionUID = 1L;\n\tprivate static final Logger LOGGER = LoggerFactory\n\t\t\t.getLogger(OcciConfig.class);\n\t/**\n\t * Instance of OcciConfig\n\t */\n\tprivate static OcciConfig instance = null;\n\tprivate static ConfigurationFactory factory;\n\t/**\n\t * Configuration for all occi properties\n\t */\n\tpublic Configuration config;\n\n\tprivate OcciConfig() {\n\t\tfactory = new ConfigurationFactory();\n\t\t// load configuration file\n\t\tURL configURL = getClass().getResource(\"/conf/config.xml\");\n\t\tfactory.setConfigurationURL(configURL);\n\t\ttry {\n\t\t\t// pick up configuration\n\t\t\tconfig = factory.getConfiguration();\n\t\t} catch (ConfigurationException e) {\n\t\t\tLOGGER.error(\"Failed to load config file.\");\n\t\t}\n\t}\n\n\tpublic static OcciConfig getInstance() {\n\t\tif (instance == null) {\n\t\t\t// create OcciConfig instance\n\t\t\tinstance = new OcciConfig();\n\t\t}\n\t\treturn instance;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tnew OcciConfig();\n\t}\n}", "public class Kind extends Category {\n\t/**\n\t * Set of Actions defined by the Kind instance.\n\t */\n\tprivate Set<Action> actions;\n\t/**\n\t * Set of related instances.\n\t */\n\tprivate Set<Kind> related;\n\t/**\n\t * Entity type uniquely identified by the Kind instance.\n\t */\n\tprivate static Entity entity_type;\n\t/**\n\t * Set of resource instances, i.e. Entity sub-type instances. Resources\n\t * instantiated from the Entity sub-type which is uniquely identified by\n\t * this Kind instance. [T. Metsch, A. Edmonds, R. Nyren and A.Papaspyrou -\n\t * Open Cloud Computing Interface - Core,\n\t * http://ogf.org/documents/GFD.183.pdf, Apr. 2011]\n\t */\n\tprivate Set<Entity> entities;\n\tprivate Set<String> actionNames = new HashSet<String>();\n\t/*\n\t * set of existing kind instances, for the query interface\n\t */\n\tprivate static Set<Kind> kinds = new HashSet<Kind>();\n\n\tpublic Kind(Set<Action> actions, Set<Kind> related, Set<Entity> entities,\n\t\t\tEntity entity_type, String term, String title, String scheme,\n\t\t\tSet<String> attributes) throws SchemaViolationException,\n\t\t\tURISyntaxException {\n\t\tsuper(term, scheme, title, attributes);\n\n\t\tthis.actions = actions;\n\t\tthis.related = related;\n\t\tthis.entities = entities;\n\t\tKind.entity_type = entity_type;\n\n\t\tkinds.add(this);\n\t}\n\n\tpublic Kind(Set<Entity> entities, Entity entity_type, String term,\n\t\t\tString title, Set<String> attributes)\n\t\t\tthrows SchemaViolationException, URISyntaxException {\n\t\tsuper(term, OcciConfig.getInstance().config.getString(\"occi.scheme\"),\n\t\t\t\ttitle, attributes);\n\n\t\tthis.entities = entities;\n\t\tKind.entity_type = entity_type;\n\n\t\tkinds.add(this);\n\t}\n\n\tpublic Kind(Set<Kind> related, Set<Entity> entities, Entity entity_type,\n\t\t\tString term, String title, Set<String> attributes)\n\t\t\tthrows SchemaViolationException, URISyntaxException {\n\t\tsuper(term, OcciConfig.getInstance().config.getString(\"occi.scheme\"),\n\t\t\t\ttitle, attributes);\n\n\t\tthis.related = related;\n\t\tthis.entities = entities;\n\t\tKind.entity_type = entity_type;\n\n\t\tkinds.add(this);\n\t}\n\n\tpublic Kind(Entity entity_type, String term, String title,\n\t\t\tSet<String> attributes) throws SchemaViolationException,\n\t\t\tURISyntaxException {\n\t\tsuper(term, \"http://schemas.ogf.org/occi/\", title, attributes);\n\n\t\tKind.entity_type = entity_type;\n\n\t\tkinds.add(this);\n\t}\n\n\tpublic Kind(Entity entity_type, Set<String> attributes)\n\t\t\tthrows SchemaViolationException, URISyntaxException {\n\t\tsuper(entity_type.getKind().getTerm(), OcciConfig.getInstance().config\n\t\t\t\t.getString(\"occi.scheme\"), entity_type.getTitle(), attributes);\n\n\t\tKind.entity_type = entity_type;\n\n\t\tkinds.add(this);\n\t}\n\n\t/**\n\t * Returns all action names as set.\n\t * \n\t * @return Action names\n\t */\n\tpublic Set<String> getActionNames() {\n\t\treturn this.actionNames;\n\t}\n\n\t/**\n\t * Sets a set of action names.\n\t * \n\t * @param actionNames\n\t */\n\tpublic void setActionNames(Set<String> actionNames) {\n\t\tthis.actionNames = actionNames;\n\t}\n\n\t/**\n\t * Returns actions.\n\t * \n\t * @return actions\n\t */\n\tpublic Set<Action> getActions() {\n\t\treturn this.actions;\n\t}\n\n\t/**\n\t * Returns related Kind.\n\t * \n\t * @return related Kind\n\t */\n\tpublic Set<Kind> getRelated() {\n\t\treturn this.related;\n\t}\n\n\t/**\n\t * Returns entities.\n\t * \n\t * @return entities\n\t */\n\tpublic Set<Entity> getEntities() {\n\t\treturn this.entities;\n\t}\n\n\t/**\n\t * Returns entity_Type.\n\t * \n\t * @return entity_Type\n\t */\n\tpublic Entity getEntity_type() {\n\t\treturn entity_type;\n\t}\n\n\t/**\n\t * Returns all active Kinds.\n\t * \n\t * @return all active Kinds\n\t */\n\tpublic static Set<Kind> getKinds() {\n\t\treturn kinds;\n\t}\n}", "public class Mixin extends Category {\n\t/**\n\t * Set of Actions defined by the Mixin instance.\n\t */\n\tprivate Set<Action> actions;\n\t/**\n\t * Set of related Mixin instances.\n\t */\n\tprivate Set<Mixin> related;\n\t/**\n\t * Set of resource instances, i.e. Entity sub-type instances, associated\n\t * with the Mixin instance. [T. Metsch, A. Edmonds, R. Nyren and\n\t * A.Papaspyrou - Open Cloud Computing Interface - Core,\n\t * http://ogf.org/documents/GFD.183.pdf, Apr. 2011]\n\t */\n\tprivate Set<Entity> entities;\n\t/**\n\t * set of existing mixin instances, for the query interface\n\t */\n\tprivate static Set<Mixin> mixins = new HashSet<Mixin>();\n\n\t/**\n\t * Mixin Constructor\n\t * \n\t * @param actions\n\t * @param related\n\t * @param entities\n\t * @throws URISyntaxException\n\t */\n\tpublic Mixin(Set<Action> actions, Set<Mixin> related, Set<Entity> entities)\n\t\t\tthrows URISyntaxException, SchemaViolationException {\n\t\tsuper(null, \"http://schemas.ogf.org/occi/core#\", null, null);\n\t\tthis.actions = actions;\n\t\tthis.related = related;\n\t\tthis.entities = entities;\n\n\t\tmixins.add(this);\n\t}\n\n\tpublic Mixin(Set<Mixin> related, Set<Entity> entities)\n\t\t\tthrows URISyntaxException, SchemaViolationException {\n\t\tsuper(null, \"http://schemas.ogf.org/occi/core#\", null, null);\n\t\tthis.related = related;\n\t\tthis.entities = entities;\n\n\t\tmixins.add(this);\n\t}\n\n\tpublic Mixin(Set<Entity> entities) throws URISyntaxException,\n\t\t\tSchemaViolationException {\n\t\tsuper(null, \"http://schemas.ogf.org/occi/core#\", null, null);\n\t\tthis.entities = entities;\n\n\t\tmixins.add(this);\n\t}\n\n\tpublic Mixin(Set<Mixin> related, String term, String title, String scheme,\n\t\t\tSet<String> attributes) throws URISyntaxException,\n\t\t\tSchemaViolationException {\n\t\tsuper(term, scheme, title, attributes);\n\t\tthis.related = related;\n\n\t\tmixins.add(this);\n\t}\n\n\t/**\n\t * Returns actions\n\t * \n\t * @return actions\n\t */\n\tpublic Set<Action> getActions() {\n\t\treturn actions;\n\t}\n\n\t/**\n\t * Returns related mixin\n\t * \n\t * @return related mixin\n\t */\n\tpublic Set<Mixin> getRelated() {\n\t\treturn related;\n\t}\n\n\t/**\n\t * Returns entities\n\t * \n\t * @return entities\n\t */\n\tpublic Set<Entity> getEntities() {\n\t\treturn entities;\n\t}\n\n\t/**\n\t * Sets entities\n\t * \n\t * @param entities\n\t */\n\tpublic void setEntities(Set<Entity> entities) {\n\t\tthis.entities = entities;\n\t}\n\n\t/**\n\t * Returns all active Mixins\n\t * \n\t * @return all active mixins\n\t */\n\tpublic static Set<Mixin> getMixins() {\n\t\treturn mixins;\n\t}\n}", "public class OcciCheck extends ServerResource {\n\tprivate static final Logger LOGGER = LoggerFactory\n\t\t\t.getLogger(OcciCheck.class);\n\n\t/**\n\t * Class checks some statements, if they start with capital or not and gives\n\t * the string back.\n\t * \n\t * @param string\n\t * @return String\n\t */\n\tpublic static Map<String, String> checkCaseSensitivity(String string) {\n\t\tMap<String, String> caseMap = new HashMap<String, String>();\n\t\tif (string.contains(\"x-occi-location\")) {\n\t\t\tcaseMap.put(\"x-occi-location\", \"x-occi-location\");\n\t\t} else if (string.contains(\"X-OCCI-Location\")) {\n\t\t\tcaseMap.put(\"x-occi-location\", \"X-OCCI-Location\");\n\t\t}\n\n\t\tif (string.contains(\"occi.compute.Category\")) {\n\t\t\tcaseMap.put(\"occi.compute.category\", \"occi.compute.Category\");\n\t\t}\n\n\t\tif (string.contains(\"Category\")) {\n\t\t\tcaseMap.put(\"category\", \"Category\");\n\t\t} else if (string.contains(\"category\")) {\n\t\t\tcaseMap.put(\"category\", \"category\");\n\t\t}\n\n\t\tif (string.contains(\"x-occi-attribute\")) {\n\t\t\tcaseMap.put(\"x-occi-attribute\", \"x-occi-attribute\");\n\t\t} else if (string.contains(\"X-OCCI-Attribute\")) {\n\t\t\tcaseMap.put(\"x-occi-attribute\", \"X-OCCI-Attribute\");\n\t\t}\n\n\t\tif (string.contains(\"content-type\")) {\n\t\t\tcaseMap.put(\"accept\", \"content-type\");\n\t\t} else if (string.contains(\"Content-Type\")) {\n\t\t\tcaseMap.put(\"accept\", \"Content-Type\");\n\t\t}\n\n\t\t// Comma-separated because the contains() Method of String matches also\n\t\t// the Accept-* Keys. But the needed key is comma-separated from the\n\t\t// value in the String\n\t\tif (string.contains(\"Accept,\")) {\n\t\t\tcaseMap.put(\"accept\", \"Accept\");\n\t\t} else if (string.contains(\"accept,\")) {\n\t\t\tcaseMap.put(\"accept\", \"accept\");\n\t\t}\n\n\t\treturn caseMap;\n\t}\n\n\tpublic static Representation checkContentType(Form requestHeaders,\n\t\t\tStringBuffer buffer, Response response) {\n\t\tRepresentation representation = null;\n\n\t\tLOGGER.debug(\"Request Headers: \" + requestHeaders);\n\t\tString acceptCase = \"\";\n\t\tif (OcciCheck.checkCaseSensitivity(requestHeaders.toString()).get(\n\t\t\t\t\"accept\") != null) {\n\t\t\tacceptCase = OcciCheck.checkCaseSensitivity(\n\t\t\t\t\trequestHeaders.toString()).get(\"accept\");\n\t\t} else {\n\t\t\tacceptCase = OcciCheck.checkCaseSensitivity(\n\t\t\t\t\trequestHeaders.toString()).get(\"content-type\");\n\t\t}\n\n\t\tLOGGER.debug(\"acceptCase: \" + acceptCase);\n\t\tString acceptHeader = requestHeaders.getFirstValue(acceptCase);\n\t\tLOGGER.debug(\"acceptHeader: \" + acceptHeader);\n\t\tif (acceptHeader == null) {\n\t\t\tacceptHeader = \" \";\n\t\t}\n\n\t\t// if text/occi is requested return text/occi, otherwise text/plain\n\t\tif (acceptHeader.equalsIgnoreCase(\"text/occi\")) {\n\t\t\trepresentation = new StringRepresentation(\" \", new MediaType(\n\t\t\t\t\t\"text/occi\"));\n\t\t\tresponse.setStatus(Status.SUCCESS_OK, buffer.toString());\n\t\t} else if ((acceptHeader.equalsIgnoreCase(\"text/plain\"))\n\t\t\t\t|| (acceptHeader.equalsIgnoreCase(\" \"))\n\t\t\t\t|| (acceptHeader.equalsIgnoreCase(\"*/*\"))) {\n\t\t\trepresentation = new StringRepresentation(buffer.toString(),\n\t\t\t\t\tMediaType.TEXT_PLAIN);\n\t\t\tresponse.setStatus(Status.SUCCESS_OK, buffer.toString());\n\t\t} else {\n\t\t\trepresentation = new StringRepresentation(\"Unsupported Media Type\",\n\t\t\t\t\tMediaType.TEXT_PLAIN);\n\t\t\tresponse.setStatus(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE);\n\t\t}\n\t\t// set character set to null\n\t\trepresentation.setCharacterSet(null);\n\t\treturn representation;\n\t}\n\n\t/**\n\t * Count the colons of the given String\n\t * \n\t * @param attributes\n\t * @throws Exception\n\t */\n\tpublic static void countColons(String attributes, int i) throws Exception {\n\t\tint count = 0;\n\t\tLOGGER.debug(\"Counting colons\");\n\t\t// Iterate over every char\n\t\tfor (char c : attributes.toCharArray()) {\n\t\t\t// Check if the char is a colon and increase count\n\t\t\tif (c == ':') {\n\t\t\t\tLOGGER.debug(\"Colon found\");\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t\t// Throw new Exception, if more than one colon is found in the request\n\t\tif (count > i) {\n\t\t\tLOGGER.error(\"One Colon found in the Request\");\n\t\t\tthrow new Exception(\n\t\t\t\t\t\"One Colon found in the Request. Please use the Request like this: XOCCI-Attribute: occi.compute.cores=2 [...]\");\n\t\t}\n\t}\n\n\t/**\n\t * Adds a whitespace after every semicolon and removes leading and trailing\n\t * whitespaces.\n\t * \n\t * @param string\n\t * @return string\n\t */\n\tpublic static String addWhitespaceAfterSemicolonAndTrim(String string) {\n\t\tif (string.contains(\";\")) {\n\t\t\tstring = string.replace(\";\", \"; \");\n\t\t}\n\t\tstring = string.trim();\n\n\t\treturn string;\n\t}\n\n\t/**\n\t * Specific method for header rendering for the query interface. Generates\n\t * the header rendering with the given params.\n\t * \n\t * @param queryKinds\n\t * @param compute\n\t * @param attributes\n\t */\n\tpublic void setHeaderRendering(LinkedList<Kind> queryKinds) {\n\t\tForm xOcciLocation = new Form();\n\t\tResponse.getCurrent().getAttributes()\n\t\t\t\t.put(\"org.restlet.http.headers\", xOcciLocation);\n\t\tString location = \"\";\n\t\tString category = \"\";\n\t\tif (queryKinds != null) {\n\t\t\tfor (Mixin mixin : Mixin.getMixins()) {\n\t\t\t\tcategory += mixin.getTitle() + \"; scheme=\\\"\"\n\t\t\t\t\t\t+ mixin.getScheme() + \"\\\"\" + \"; class=\\\"mixin\\\"\" + \", \";\n\t\t\t\tlocation += \"/\" + mixin.getTitle() + \"/,\";\n\t\t\t}\n\t\t\tfor (Kind kind : queryKinds) {\n\t\t\t\tif (!kind.equals(queryKinds.getLast())) {\n\t\t\t\t\tcategory += kind.getTerm() + \"; scheme=\\\"\"\n\t\t\t\t\t\t\t+ kind.getScheme() + \"\\\"\" + \"; class=\\\"mixin\\\"\"\n\t\t\t\t\t\t\t+ \", \";\n\t\t\t\t} else {\n\t\t\t\t\tcategory += kind.getTerm();\n\t\t\t\t}\n\t\t\t\tif (kind.equals(queryKinds.getLast())) {\n\t\t\t\t\tlocation += \"/\" + kind.getTerm() + \"/\";\n\t\t\t\t} else if (!kind.equals(queryKinds.getLast())) {\n\t\t\t\t\tlocation += \"/\" + kind.getTerm() + \"/,\";\n\t\t\t\t} else if (kind.equals(queryKinds.getFirst())) {\n\t\t\t\t\tlocation += \"/\" + kind.getTerm() + \"/,\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\txOcciLocation.add(\"Category\", category);\n\t\txOcciLocation.add(\"X-OCCI-Location\", location);\n\t\txOcciLocation.add(\"Link\",\n\t\t\t\t\"setHeaderRendering(LinkedList<Kind> queryKinds)\");\n\t}\n\n\t/**\n\t * Specific method for header rendering for the query interface. Generates\n\t * the header rendering with the given params.\n\t * \n\t * @param queryKinds\n\t * @param compute\n\t * @param attributes\n\t */\n\tpublic void setHeaderRendering(LinkedList<Kind> queryKinds,\n\t\t\tResource resource, String attributes, StringBuffer link) {\n\t\tForm xOcciLocation = new Form();\n\t\tResponse.getCurrent().getAttributes()\n\t\t\t\t.put(\"org.restlet.http.headers\", xOcciLocation);\n\t\tString location = \"\";\n\t\tString category = \"\";\n\t\tStringBuffer linkBuffer = new StringBuffer();\n\t\tif (queryKinds != null) {\n\t\t\tfor (Mixin mixin : Mixin.getMixins()) {\n\t\t\t\t// category += mixin.getTitle() + \",\";\n\t\t\t\tcategory += mixin.getTitle() + \"; scheme=\\\"\"\n\t\t\t\t\t\t+ mixin.getScheme() + \"\\\"\" + \"; class=\\\"mixin\\\"\" + \", \";\n\t\t\t\tlocation += \"/\" + mixin.getTitle() + \"/,\";\n\t\t\t}\n\t\t\tfor (Kind kind : queryKinds) {\n\t\t\t\tif (!kind.equals(queryKinds.getLast())) {\n\t\t\t\t\tcategory += kind.getTerm() + \",\";\n\t\t\t\t} else {\n\t\t\t\t\tcategory += kind.getTerm();\n\t\t\t\t}\n\t\t\t\tif (kind.equals(queryKinds.getLast())) {\n\t\t\t\t\tlocation += \"/\" + kind.getTerm() + \"/\";\n\t\t\t\t} else if (!kind.equals(queryKinds.getLast())) {\n\t\t\t\t\tlocation += \"/\" + kind.getTerm() + \"/,\";\n\t\t\t\t} else if (kind.equals(queryKinds.getFirst())) {\n\t\t\t\t\tlocation += \"/\" + kind.getTerm() + \"/,\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif ((resource != null) && (attributes != null)) {\n\t\t\tcategory = null;\n\t\t\t// xOcciLocation = null;\n\t\t\tResponse.getCurrent().getAttributes()\n\t\t\t\t\t.put(\"org.restlet.http.headers\", xOcciLocation);\n\t\t\tcategory = \"\"; // resource.getKind().getTerm();\n\n\t\t\t// add information about category and location to the header\n\t\t\tif (resource.getKind() != null) {\n\t\t\t\tfor (Category mixin : resource.getKind().getCategories()) {\n\t\t\t\t\tif (!mixin.getTitle().equalsIgnoreCase(\"action\")) {\n\t\t\t\t\t\tcategory += mixin.getTitle() + \"; scheme=\\\"\"\n\t\t\t\t\t\t\t\t+ mixin.getScheme().toString()\n\t\t\t\t\t\t\t\t+ \"\\\"; class=\\\"mixin\\\";\";\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (String actionName : resource.getKind().getActionNames()) {\n\t\t\t\tString actionScheme = resource.getKind().getScheme().toString();\n\t\t\t\tString actionSchemeSubStr = actionScheme.substring(0,\n\t\t\t\t\t\tactionScheme.length() - 1);\n\t\t\t\tlinkBuffer.append(\"</\");\n\t\t\t\tlinkBuffer.append(resource.getKind().getTerm() + \"/\");\n\t\t\t\tlinkBuffer.append(resource.getId());\n\t\t\t\tlinkBuffer.append(\"/?action=\");\n\t\t\t\tlinkBuffer.append(actionName.substring(actionName\n\t\t\t\t\t\t.lastIndexOf(\"#\") + 1));\n\t\t\t\tlinkBuffer.append(\">;rel=\\\"\" + actionSchemeSubStr + \"/\");\n\t\t\t\tlinkBuffer.append(resource.getKind().getTerm() + \"/action#\");\n\t\t\t\tlinkBuffer.append(actionName.substring(actionName\n\t\t\t\t\t\t.lastIndexOf(\"#\") + 1) + \"\\\" \");\n\n\t\t\t}\n\t\t}\n\t\tif (link != null) {\n\t\t\tlinkBuffer.append(link);\n\t\t}\n\n\t\tif (location.isEmpty()) {\n\t\t\txOcciLocation.add(\"X-OCCI-Location\", location);\n\t\t}\n\n\t\txOcciLocation.add(\"Link\", linkBuffer.toString());\n\t\txOcciLocation.add(\"Category\", category);\n\t\txOcciLocation.add(\"X-OCCI-Attribute\", attributes);\n\t}\n\n\t/**\n\t * Specific method for header rendering for the query interface. Generates\n\t * the header rendering with the given params.\n\t * \n\t * @param queryKinds\n\t * @param link\n\t * @param attributes\n\t * @param linked\n\t */\n\tpublic void setHeaderRendering(LinkedList<Kind> queryKinds, Link link,\n\t\t\tString attributes, StringBuffer linked) {\n\t\tForm xOcciLocation = new Form();\n\t\tResponse.getCurrent().getAttributes()\n\t\t\t\t.put(\"org.restlet.http.headers\", xOcciLocation);\n\t\tString location = link.getKind().getTitle() + \"/\" + link.getId();\n\n\t\tString category = \"\";\n\t\tStringBuffer linkBuffer = new StringBuffer();\n\t\tif (queryKinds != null) {\n\n\t\t\tfor (Mixin mixin : Mixin.getMixins()) {\n\t\t\t\t// category += mixin.getTitle() + \",\";\n\t\t\t\tcategory += mixin.getTitle() + \"; scheme=\\\"\" + link.getScheme()\n\t\t\t\t\t\t+ \"\\\"\" + \"; class=\\\"kind\\\"\" + \", \";\n\t\t\t\tlocation += \"/\" + mixin.getTitle() + \"/,\";\n\t\t\t}\n\t\t\tfor (Kind kind : queryKinds) {\n\t\t\t\tif (!kind.equals(queryKinds.getLast())) {\n\t\t\t\t\tcategory += kind.getTerm() + \",\";\n\t\t\t\t} else {\n\t\t\t\t\tcategory += kind.getTerm();\n\t\t\t\t}\n\t\t\t\tif (kind.equals(queryKinds.getLast())) {\n\t\t\t\t\tlocation += \"/\" + kind.getTerm() + \"/\";\n\t\t\t\t} else if (!kind.equals(queryKinds.getLast())) {\n\t\t\t\t\tlocation += \"/\" + kind.getTerm() + \"/,\";\n\t\t\t\t} else if (kind.equals(queryKinds.getFirst())) {\n\t\t\t\t\tlocation += \"/\" + kind.getTerm() + \"/,\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif ((link != null) && (attributes != null)) {\n\t\t\tcategory = \"\";\n\t\t\t// xOcciLocation = null;\n\t\t\tResponse.getCurrent().getAttributes()\n\t\t\t\t\t.put(\"org.restlet.http.headers\", xOcciLocation);\n\n\t\t\t// add information about category and location to the header\n\t\t\tif (link.getKind() != null) {\n\t\t\t\t// for (Category mixin : link.getKind()) {\n\t\t\t\tif (!link.getKind().getTitle().equalsIgnoreCase(\"action\")) {\n\t\t\t\t\tcategory += link.getKind().getTitle() + \"; scheme=\\\"\"\n\t\t\t\t\t\t\t+ link.getScheme() + \"\\\"; class=\\\"kind\\\";\";\n\t\t\t\t}\n\n\t\t\t\t// }\n\t\t\t}\n\n\t\t\tif (link.getKind() != null) {\n\t\t\t\tfor (String actionName : link.getKind().getActionNames()) {\n\t\t\t\t\tString actionScheme = link.getKind().getScheme().toString();\n\t\t\t\t\tString actionSchemeSubStr = actionScheme.substring(0,\n\t\t\t\t\t\t\tactionScheme.length() - 1);\n\t\t\t\t\tlinkBuffer.append(\"</\");\n\t\t\t\t\tlinkBuffer.append(link.getKind().getTerm() + \"/\");\n\t\t\t\t\tlinkBuffer.append(link.getId());\n\t\t\t\t\tlinkBuffer.append(\"/?action=\");\n\t\t\t\t\tlinkBuffer.append(actionName.substring(actionName\n\t\t\t\t\t\t\t.lastIndexOf(\"#\") + 1));\n\t\t\t\t\tlinkBuffer.append(\">;rel=\\\"\" + actionSchemeSubStr + \"/\");\n\t\t\t\t\tlinkBuffer.append(link.getKind().getTerm() + \"/action#\");\n\t\t\t\t\tlinkBuffer.append(actionName.substring(actionName\n\t\t\t\t\t\t\t.lastIndexOf(\"#\") + 1) + \"\\\" \");\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (linked != null) {\n\t\t\tlinkBuffer.append(linked);\n\t\t}\n\n\t\t// xOcciLocation.add(\"Link\", linkBuffer.toString());\n\n\t\txOcciLocation.add(\"Category\", category);\n\t\txOcciLocation.add(\"X-OCCI-Location\", location);\n\t\txOcciLocation.add(\"X-OCCI-Attribute\",\n\t\t\t\tlinkBuffer.toString().replace(\"X-OCCI-Attribute: \", \"\"));\n\t}\n\n\tpublic static void setHeaderRendering(Mixin mixin) {\n\t\tForm xOcciLocation = new Form();\n\t\tResponse.getCurrent().getAttributes()\n\t\t\t\t.put(\"org.restlet.http.headers\", xOcciLocation);\n\t\tString category = mixin.getTitle();\n\t\tString clazz = \"mixin\";\n\t\tString scheme = mixin.getScheme().toString();\n\t\tString rel = \"\";\n\t\tint i = 1;\n\t\tif (mixin.getRelated() != null) {\n\t\t\tfor (Mixin related : mixin.getRelated()) {\n\t\t\t\tif (mixin.getRelated().size() >= i) {\n\t\t\t\t\trel += related.getTerm();\n\t\t\t\t} else {\n\t\t\t\t\trel += related.getTerm() + \",\";\n\t\t\t\t}\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t\tString entities = \"\";\n\t\tif (mixin.getEntities() != null) {\n\t\t\tfor (Entity entity : mixin.getEntities()) {\n\t\t\t\tentities += entity.getKind().getTerm() + \"/\" + entity.getId();\n\t\t\t}\n\t\t}\n\t\txOcciLocation.add(\"Category\", category);\n\t\txOcciLocation.add(\"Class\", clazz);\n\t\txOcciLocation.add(\"Scheme\", scheme);\n\t\tif (!entities.equals(\"\")) {\n\t\t\txOcciLocation.add(\"X-OCCI-Location\", entities);\n\t\t}\n\t}\n\n\tpublic static boolean isUUID(String string) {\n\t\tif (!string.matches(\"[\\\\w]{8}-[\\\\w]{4}-[\\\\w]{4}-[\\\\w]{4}-[\\\\w]{12}\")) {\n\t\t\treturn false;\n\t\t} else {\n\t\t\treturn true;\n\t\t}\n\t}\n}", "public class Network extends Resource {\n\t/**\n\t * 802.1q VLAN Ientifier (e.g. 343).\n\t */\n\tprivate int vlan;\n\t/**\n\t * Tag based VLANs (e.g. external-dmz).\n\t */\n\tprivate String label;\n\t/**\n\t * Current state of the instance.\n\t */\n\tprivate State state;\n\n\t/**\n\t * Possible status of the instance\n\t */\n\tpublic enum State {\n\t\tactive, inactive\n\t}\n\n\t/**\n\t * Static HashSet of all network attributes.\n\t */\n\tprivate static HashSet<String> attributes = new HashSet<String>();\n\n\t/**\n\t * Static Hashmap of all Network Resources. The Key is a UUID, the Value a\n\t * Network Object.\n\t */\n\tprivate static Map<UUID, Network> networkList = new HashMap<UUID, Network>();\n\n\t/*\n\t * All possible network actions.\n\t */\n\tprivate static ListableBeanFactory beanFactory = new ClassPathXmlApplicationContext(\n\t\t\t\"occiConfig.xml\");\n\tprivate static Action up = (Action) beanFactory.getBean(\"up\");\n\tprivate static Action down = (Action) beanFactory.getBean(\"down\");\n\n\tprivate final static HashSet<Action> actionSet = new HashSet<Action>();\n\tprivate final static HashSet<String> actionNames = new HashSet<String>();\n\n\t/**\n\t * Minimal constructor.\n\t * \n\t * @param links\n\t * @param attributes\n\t * @throws URISyntaxException\n\t * @throws SchemaViolationException\n\t */\n\tpublic Network(State state, Set<Link> links, Set<String> attributes)\n\t\t\tthrows URISyntaxException, SchemaViolationException {\n\t\tsuper(links, attributes);\n\t\tthis.state = state;\n\n\t\tsetKind(new Kind(actionSet, null, null, null, \"network\", \"network\",\n\t\t\t\tOcciConfig.getInstance().config.getString(\"occi.scheme\")\n\t\t\t\t\t\t+ \"/infrastructure#\", attributes));\n\n\t\tnetworkList.put(UUID.fromString(getId().toString()), this);\n\t\tgenerateActionNames();\n\t\tgenerateActionNames();\n\t\tgenerateAttributeList();\n\t}\n\n\tpublic Network(State state, String label, Set<Link> links,\n\t\t\tSet<String> attributes) throws URISyntaxException,\n\t\t\tSchemaViolationException {\n\t\tsuper(links, attributes);\n\t\tthis.state = state;\n\t\tthis.label = label;\n\n\t\tnetworkList.put(UUID.fromString(getId().toString()), this);\n\t\tgenerateActionNames();\n\t\tgenerateAttributeList();\n\t}\n\n\tpublic Network(State state, int vlan, Set<Link> links,\n\t\t\tSet<String> attributes) throws URISyntaxException,\n\t\t\tSchemaViolationException {\n\t\tsuper(links, attributes);\n\t\tthis.state = state;\n\t\tthis.vlan = vlan;\n\n\t\tnetworkList.put(UUID.fromString(getId().toString()), this);\n\t\tgenerateActionNames();\n\t\tgenerateAttributeList();\n\t}\n\n\tpublic Network(State state, String label, int vlan, Set<Link> links,\n\t\t\tSet<String> attributes) throws URISyntaxException,\n\t\t\tSchemaViolationException {\n\t\tsuper(links, attributes);\n\t\tthis.state = state;\n\n\t\tnetworkList.put(UUID.fromString(getId().toString()), this);\n\t\tgenerateActionNames();\n\t\tgenerateAttributeList();\n\t}\n\n\tpublic Network(HashMap<String, String> attributes)\n\t\t\tthrows SchemaViolationException, URISyntaxException {\n\t\tsuper(attributes);\n\n\t\tnetworkList.put(UUID.fromString(getId().toString()), this);\n\t\tgenerateActionNames();\n\t\tgenerateAttributeList();\n\t}\n\n\t/**\n\t * Sets vlan integer.\n\t * \n\t * @param vlan\n\t */\n\tpublic final void setVlan(int vlan) {\n\t\tthis.vlan = vlan;\n\t}\n\n\t/**\n\t * Returns vlan of the network interface.\n\t * \n\t * @return vlan\n\t */\n\tpublic final int getVlan() {\n\t\treturn vlan;\n\t}\n\n\t/**\n\t * Returns state of the network interface.\n\t * \n\t * @return state\n\t */\n\tpublic final State getState() {\n\t\treturn this.state;\n\t}\n\n\t/**\n\t * Sets the state of the instance.\n\t * \n\t * @param state\n\t */\n\tpublic final void setState(State state) {\n\t\tthis.state = state;\n\t}\n\n\t/**\n\t * Sets the label of the instance.\n\t * \n\t * @param label\n\t */\n\tpublic final void setLabel(String label) {\n\t\tthis.label = label;\n\t}\n\n\t/**\n\t * Returns the label of the instance.\n\t * \n\t * @return label\n\t */\n\tpublic final String getLabel() {\n\t\treturn label;\n\t}\n\n\t/**\n\t * Returns list of all network resources.\n\t * \n\t * @return network map\n\t */\n\tpublic final static Map<UUID, Network> getNetworkList() {\n\t\treturn networkList;\n\t}\n\n\t/**\n\t * Return list of all action names.\n\t * \n\t * @return action names\n\t */\n\tpublic final static HashSet<String> getActionNames() {\n\t\treturn actionNames;\n\t}\n\n\t/**\n\t * Generate list with action names.\n\t */\n\tpublic final static HashSet<String> generateActionNames() {\n\t\tif (actionNames.isEmpty()) {\n\t\t\tfor (int i = 0; i < beanFactory.getBeanDefinitionNames().length; i++) {\n\t\t\t\tif (beanFactory\n\t\t\t\t\t\t.getBean(beanFactory.getBeanDefinitionNames()[i])\n\t\t\t\t\t\t.toString().contains(\"network\")) {\n\t\t\t\t\tactionNames.add(OcciConfig.getInstance().config\n\t\t\t\t\t\t\t.getString(\"occi.scheme\")\n\t\t\t\t\t\t\t+ \"/infrastructure/network/action#\"\n\t\t\t\t\t\t\t+ beanFactory.getBeanDefinitionNames()[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn actionNames;\n\t}\n\n\t/**\n\t * Generate list with actions.\n\t * \n\t * @return hash set of actions\n\t */\n\tpublic final static HashSet<Action> generateActionSet() {\n\t\tif (actionSet.isEmpty()) {\n\t\t\tfor (int i = 0; i < beanFactory.getBeanDefinitionNames().length; i++) {\n\t\t\t\tif (beanFactory\n\t\t\t\t\t\t.getBean(beanFactory.getBeanDefinitionNames()[i])\n\t\t\t\t\t\t.toString().contains(\"network\")) {\n\t\t\t\t\tactionSet.add((Action) beanFactory.getBean(beanFactory\n\t\t\t\t\t\t\t.getBeanDefinitionNames()[i]));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn actionSet;\n\t}\n\n\t/**\n\t * Generate attribute List.\n\t */\n\tpublic final static void generateAttributeList() {\n\t\tif (attributes.isEmpty()) {\n\t\t\t// add all attributes to attribute list\n\t\t\tattributes.add(\"occi.network.vlan\");\n\t\t\tattributes.add(\"occi.network.label\");\n\t\t\tattributes.add(\"occi.network.state\");\n\t\t}\n\t}\n\n\t/**\n\t * Return the network attributes.\n\t * \n\t * @return attributes\n\t */\n\tpublic static HashSet<String> getAttributes() {\n\t\treturn attributes;\n\t}\n}", "public enum State {\n\tactive, inactive\n}", "public class NetworkInterface extends Link {\n\t/**\n\t * Identifier that relates the link to the link's device interface. [T. Metsch, A. Edmonds - Open Cloud Computing Interface - Infrastructure, http://ogf.org/documents/GFD.184.pdf, Apr. 2011]\n\t */\n\tprivate final String networkInterface;\n\t/**\n\t * MAC address associated with the link's device interface. [T. Metsch, A. Edmonds - Open Cloud Computing Interface - Infrastructure, http://ogf.org/documents/GFD.184.pdf, Apr. 2011]\n\t */\n\tprivate String mac;\n\t/**\n\t * Current status of the instance. [T. Metsch, A. Edmonds - Open Cloud Computing Interface - Infrastructure, http://ogf.org/documents/GFD.184.pdf, Apr. 2011]\n\t */\n\tprivate final State state;\n\n\t/**\n\t * Possible status of the instance. [T. Metsch, A. Edmonds - Open Cloud Computing Interface - Infrastructure, http://ogf.org/documents/GFD.184.pdf, Apr. 2011]\n\t */\n\tpublic enum State {\n\t\tactive, inactive\n\t}\n\n\t/**\n\t * Random UUID of the compute resource.\n\t */\n\tprivate final UUID uuid;\n\n\tpublic static Map<UUID, NetworkInterface> networkInterfaceList = new HashMap<UUID, NetworkInterface>();\n\n\t/**\n\t * Static HashSet of all network interface attributes.\n\t */\n\tprivate static HashSet<String> attributes = new HashSet<String>();\n\n\tpublic NetworkInterface(String networkInterface, String mac, State state,\n\t\t\tResource link, Resource target) throws URISyntaxException,\n\t\t\tSchemaViolationException {\n\t\tsuper(link, target);\n\t\tthis.networkInterface = networkInterface;\n\t\tthis.mac = mac;\n\t\tthis.state = state;\n\t\tuuid = UUID.randomUUID();\n\t\tsetId(new URI(uuid.toString()));\n\t\t// put resource into networkinterface list\n\t\tnetworkInterfaceList.put(uuid, this);\n\n\t\t// setKind(new Kind(this, target.getKind().getTerm(), target.getKind()\n\t\t// .getTitle(), attributes));\n\n\t\t// Generate attribute list\n\t\tgenerateAttributeList();\n\t}\n\n\t/**\n\t * Generate attribute List.\n\t */\n\tpublic static void generateAttributeList() {\n\t\tif (attributes.isEmpty()) {\n\t\t\t// add all attributes to attribute list\n\t\t\tattributes.add(\"occi.networkinterface.interface\");\n\t\t\tattributes.add(\"occi.networkinterface.mac\");\n\t\t\tattributes.add(\"occi.networkinterface.state\");\n\t\t}\n\t}\n\n\t/**\n\t * Return the network interface attributes.\n\t * \n\t * @return attributes\n\t */\n\tpublic static HashSet<String> getAttributes() {\n\t\treturn attributes;\n\t}\n\n\t/**\n\t * Returns the network interface.\n\t * \n\t * @return string\n\t */\n\tpublic String getNetworkInterface() {\n\t\treturn networkInterface;\n\t}\n\n\t/**\n\t * Sets the mac adress of the network interface.\n\t * \n\t * @param mac\n\t */\n\tpublic void setMac(String mac) {\n\t\tthis.mac = mac;\n\t}\n\n\t/**\n\t * Returns the mac adress of the network interface.\n\t * \n\t * @return string\n\t */\n\tpublic String getMac() {\n\t\treturn mac;\n\t}\n\n\t/**\n\t * Returns the state of the network interface.\n\t * \n\t * @return state\n\t */\n\tpublic State getState() {\n\t\treturn state;\n\t}\n\t\n\t/**\n\t * Returns the list with all network interface instances.\n\t * \n\t * @return list with network interfaces\n\t */\n\tpublic static Map<UUID, NetworkInterface> getNetworkInterfaceList() {\n\t\treturn networkInterfaceList;\n\t}\n\t\n\t/**\n\t * Sets the network interface list.\n\t * \n\t * @param networkInterfaceList\n\t */\n\tpublic void setNetworkInterfaceList(Map<UUID, NetworkInterface> networkInterfaceList) {\n\t\tNetworkInterface.networkInterfaceList = networkInterfaceList;\n\t}\n}" ]
import java.util.HashMap; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; import java.util.UUID; import occi.config.OcciConfig; import occi.core.Kind; import occi.core.Mixin; import occi.http.check.OcciCheck; import occi.infrastructure.Network; import occi.infrastructure.Network.State; import occi.infrastructure.links.NetworkInterface; import org.restlet.Response; import org.restlet.data.Form; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.resource.Delete; import org.restlet.resource.Get; import org.restlet.resource.Post; import org.restlet.resource.Put; import org.restlet.resource.ServerResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
if (requestHeaders.getFirstValue(acceptCase).equals("text/occi")) { // generate header rendering occiCheck.setHeaderRendering(null, networkinterface, buffer .toString(), buffer2); // set right representation and status code getResponse().setEntity(representation); getResponse().setStatus(Status.SUCCESS_OK); return " "; } // set right representation and status code getResponse().setEntity(representation); getResponse().setStatus(Status.SUCCESS_OK, buffer.toString()); return buffer.toString(); } /** * Deletes the resource which applies to the parameters in the header. * * @return string deleted or not */ @Delete public String deleteOCCIRequest() { // set occi version info getServerInfo().setAgent( OcciConfig.getInstance().config.getString("occi.version")); LOGGER.debug("Incoming delete request at network"); try { // get network resource that should be deleted NetworkInterface networkInterface = NetworkInterface.getNetworkInterfaceList() .get(UUID.fromString(getReference().getLastSegment())); // remove it from network resource list if (NetworkInterface.getNetworkInterfaceList().remove(UUID .fromString(networkInterface.getId().toString())) == null) { throw new NullPointerException( "There is no resorce with the given ID"); } // set network resource to null networkInterface = null; getResponse().setStatus(Status.SUCCESS_OK); return " "; } catch (NullPointerException e) { getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND, e.getMessage()); return "UUID not found! " + e.toString() + "\n Network resource could not be deleted."; } catch (Exception e) { getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND, e.getMessage()); return e.toString(); } } /** * Method to create a new network instance. * * @param representation * @return string * @throws Exception */ @Post public String postOCCIRequest(Representation representation) throws Exception { LOGGER.info("Incoming POST request."); // set occi version info getServerInfo().setAgent( OcciConfig.getInstance().config.getString("occi.version")); try { // access the request headers and get the X-OCCI-Attribute Form requestHeaders = (Form) getRequest().getAttributes().get( "org.restlet.http.headers"); LOGGER.debug("Current request: " + requestHeaders); String attributeCase = OcciCheck.checkCaseSensitivity( requestHeaders.toString()).get("x-occi-attribute"); String xocciattributes = requestHeaders.getValues(attributeCase) .replace(",", " "); LOGGER.debug("Media-Type: " + requestHeaders.getFirstValue("accept", true)); // OcciCheck.countColons(xocciattributes, 2); // split the single occi attributes and put it into a (key,value) // map LOGGER.debug("Raw X-OCCI Attributes: " + xocciattributes); StringTokenizer xoccilist = new StringTokenizer(xocciattributes); HashMap<String, Object> xoccimap = new HashMap<String, Object>(); LOGGER.debug("Tokens in XOCCIList: " + xoccilist.countTokens()); while (xoccilist.hasMoreTokens()) { String[] temp = xoccilist.nextToken().split("\\="); if (temp[0] != null && temp[1] != null) { LOGGER.debug(temp[0] + " " + temp[1] + "\n"); xoccimap.put(temp[0], temp[1]); } } // put occi attributes into a buffer for the response StringBuffer buffer = new StringBuffer(); buffer.append("occi.networkinterface.interface=").append( xoccimap.get("occi.networkinterface.interface")); buffer.append(" occi.networkinterface.mac=").append( xoccimap.get("occi.networkinterface.mac")); buffer.append(" occi.networkinterface.state=").append( xoccimap.get("occi.networkinterface.state")); Set<String> set = new HashSet<String>(); set.add("summary: "); set.add(buffer.toString()); set.add(requestHeaders.getFirstValue("scheme")); if (!requestHeaders.contains("Link")) { // create new NetworkInterface instance with the given // attributes NetworkInterface networkInterface = new NetworkInterface( (String) xoccimap .get("occi.networkinterface.interface"), (String) xoccimap.get("occi.networkinterface.mac"), occi.infrastructure.links.NetworkInterface.State.inactive, null, null);
networkInterface.setKind(new Kind(null, "networkinterface",
1
protolambda/blocktopograph
app/src/main/java/com/protolambda/blocktopograph/WorldActivity.java
[ "public enum Dimension {\n\n OVERWORLD(0, \"overworld\", \"Overworld\", 16, 16, 128, 1, MapType.OVERWORLD_SATELLITE),\n NETHER(1, \"nether\", \"Nether\", 16, 16, 128, 8, MapType.NETHER),\n END(2, \"end\", \"End\", 16, 16, 128, 1, MapType.END_SATELLITE);//mcpe: SOON^TM /jk\n\n public final int id;\n public final int chunkW, chunkL, chunkH;\n public final int dimensionScale;\n public final String dataName, name;\n public final MapType defaultMapType;\n\n Dimension(int id, String dataName, String name, int chunkW, int chunkL, int chunkH, int dimensionScale, MapType defaultMapType){\n this.id = id;\n this.dataName = dataName;\n this.name = name;\n this.chunkW = chunkW;\n this.chunkL = chunkL;\n this.chunkH = chunkH;\n this.dimensionScale = dimensionScale;\n this.defaultMapType = defaultMapType;\n }\n\n private static Map<String, Dimension> dimensionMap = new HashMap<>();\n\n static {\n for(Dimension dimension : Dimension.values()){\n dimensionMap.put(dimension.dataName, dimension);\n }\n }\n\n public static Dimension getDimension(String dataName){\n if(dataName == null) return null;\n return dimensionMap.get(dataName.toLowerCase());\n }\n\n public static Dimension getDimension(int id){\n for(Dimension dimension : values()){\n if(dimension.id == id) return dimension;\n }\n return null;\n }\n\n}", "public class AbstractMarker implements NamedBitmapProviderHandle {\n\n public final int x, y, z;\n public final Dimension dimension;\n\n public final NamedBitmapProvider namedBitmapProvider;\n\n public final boolean isCustom;\n\n public AbstractMarker(int x, int y, int z, Dimension dimension, NamedBitmapProvider namedBitmapProvider, boolean isCustom) {\n this.x = x;\n this.y = y;\n this.z = z;\n this.dimension = dimension;\n this.namedBitmapProvider = namedBitmapProvider;\n this.isCustom = isCustom;\n }\n\n public int getChunkX(){\n return x >> 4;\n }\n\n public int getChunkZ(){\n return z >> 4;\n }\n\n public MarkerImageView view;\n\n public MarkerImageView getView(Context context) {\n if(view != null) return view;\n view = new MarkerImageView(context, this);\n this.loadIcon(view);\n return view;\n }\n\n /**\n * Loads the provided bitmap into the image view.\n * @param iconView The view to load the icon into.\n */\n public void loadIcon(ImageView iconView) {\n iconView.setImageBitmap(this.getNamedBitmapProvider().getBitmap());\n }\n\n @NonNull\n @Override\n public NamedBitmapProvider getNamedBitmapProvider() {\n return namedBitmapProvider;\n }\n\n public AbstractMarker copy(int x, int y, int z, Dimension dimension) {\n return new AbstractMarker(x, y, z, dimension, this.namedBitmapProvider, this.isCustom);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n AbstractMarker that = (AbstractMarker) o;\n\n return x == that.x\n && y == that.y\n && z == that.z\n && dimension == that.dimension\n && (namedBitmapProvider != null\n ? namedBitmapProvider.equals(that.namedBitmapProvider)\n : that.namedBitmapProvider == null);\n\n }\n\n @Override\n public int hashCode() {\n int result = Vector3.intHash(x, y, z);\n result = 31 * result + (dimension != null ? dimension.hashCode() : 0);\n result = 31 * result + (namedBitmapProvider != null ? namedBitmapProvider.hashCode() : 0);\n return result;\n }\n}", "public class NBTConstants {\n\n public enum NBTType {\n\n END(0, EndTag.class, \"EndTag\"),\n BYTE(1, ByteTag.class, \"ByteTag\"),\n SHORT(2, ShortTag.class, \"ShortTag\"),\n INT(3, IntTag.class, \"IntTag\"),\n LONG(4, LongTag.class, \"LongTag\"),\n FLOAT(5, FloatTag.class, \"FloatTag\"),\n DOUBLE(6, DoubleTag.class, \"DoubleTag\"),\n BYTE_ARRAY(7, ByteArrayTag.class, \"ByteArrayTag\"),\n STRING(8, StringTag.class, \"StringTag\"),\n LIST(9, ListTag.class, \"ListTag\"),\n COMPOUND(10, CompoundTag.class, \"CompoundTag\"),\n INT_ARRAY(11, IntArrayTag.class, \"IntArrayTag\"),\n\n //Is this one even used?!? Maybe used in mods?\n SHORT_ARRAY(100, ShortArrayTag.class, \"ShortArrayTag\");\n\n public final int id;\n public final Class<? extends Tag> tagClazz;\n public final String displayName;\n\n static public Map<Integer, NBTType> typesByID = new HashMap<>();\n static public Map<Class<? extends Tag>, NBTType> typesByClazz = new HashMap<>();\n\n NBTType(int id, Class<? extends Tag> tagClazz, String displayName){\n this.id = id;\n this.tagClazz = tagClazz;\n this.displayName = displayName;\n }\n\n //not all NBT types are meant to be created in an editor, the END tag for example.\n public static String[] editorOptions_asString;\n public static NBTType[] editorOptions_asType = new NBTType[]{\n BYTE,\n SHORT,\n INT,\n LONG,\n FLOAT,\n DOUBLE,\n BYTE_ARRAY,\n STRING,\n LIST,\n COMPOUND,\n INT_ARRAY,\n SHORT_ARRAY\n };\n\n static {\n\n\n int len = editorOptions_asType.length;\n editorOptions_asString = new String[len];\n for(int i = 0; i < len; i++){\n editorOptions_asString[i] = editorOptions_asType[i].displayName;\n }\n\n\n //fill maps\n for(NBTType type : NBTType.values()){\n typesByID.put(type.id, type);\n typesByClazz.put(type.tagClazz, type);\n }\n }\n\n public static Tag newInstance(String tagName, NBTType type){\n switch (type){\n case END: return new EndTag();\n case BYTE: return new ByteTag(tagName, (byte) 0);\n case SHORT: return new ShortTag(tagName, (short) 0);\n case INT: return new IntTag(tagName, 0);\n case LONG: return new LongTag(tagName, 0L);\n case FLOAT: return new FloatTag(tagName, 0f);\n case DOUBLE: return new DoubleTag(tagName, 0.0);\n case BYTE_ARRAY: return new ByteArrayTag(tagName, null);\n case STRING: return new StringTag(tagName, \"\");\n case LIST: return new ListTag(tagName, new ArrayList<Tag>());\n case COMPOUND: return new CompoundTag(tagName, new ArrayList<Tag>());\n default: return null;\n }\n }\n\n }\n\n public static final Charset CHARSET = Charset.forName(\"UTF-8\");\n\n}", "public class NBTChunkData extends ChunkData {\n\n public List<Tag> tags = new ArrayList<>();\n\n public final ChunkTag dataType;\n\n public NBTChunkData(Chunk chunk, ChunkTag dataType) {\n super(chunk);\n this.dataType = dataType;\n }\n\n public void load() throws WorldData.WorldDBLoadException, WorldData.WorldDBException, IOException {\n loadFromByteArray(chunk.worldData.getChunkData(chunk.x, chunk.z, dataType, this.chunk.dimension, (byte) 0, false));\n }\n\n public void loadFromByteArray(byte[] data) throws IOException {\n if (data != null && data.length > 0) this.tags = DataConverter.read(data);\n }\n\n public void write() throws WorldData.WorldDBException, IOException {\n if (this.tags == null) this.tags = new ArrayList<>();\n byte[] data = DataConverter.write(this.tags);\n this.chunk.worldData.writeChunkData(this.chunk.x, this.chunk.z, this.dataType, this.chunk.dimension, (byte) 0, false, data);\n }\n\n @Override\n public void createEmpty() {\n if(this.tags == null) this.tags = new ArrayList<>();\n this.tags.add(new IntTag(\"Placeholder\", 42));\n }\n\n}", "public class MapFragment extends Fragment {\n\n private WorldActivityInterface worldProvider;\n\n private MCTileProvider minecraftTileProvider;\n\n private TileView tileView;\n\n //procedural markers can be iterated while other threads add things to it;\n // iterating performance is not really affected because of the small size;\n public CopyOnWriteArraySet<AbstractMarker> proceduralMarkers = new CopyOnWriteArraySet<>();\n\n public Set<AbstractMarker> staticMarkers = new HashSet<>();\n\n public AbstractMarker spawnMarker;\n public AbstractMarker localPlayerMarker;\n\n\n\n\n @Override\n public void onPause() {\n super.onPause();\n\n //pause drawing the map\n this.tileView.pause();\n }\n\n @Override\n public void onStart() {\n super.onStart();\n\n getActivity().setTitle(this.worldProvider.getWorld().getWorldDisplayName());\n\n worldProvider.logFirebaseEvent(WorldActivity.CustomFirebaseEvent.MAPFRAGMENT_OPEN);\n }\n\n @Override\n public void onResume() {\n super.onResume();\n\n //resume drawing the map\n this.tileView.resume();\n\n worldProvider.logFirebaseEvent(WorldActivity.CustomFirebaseEvent.MAPFRAGMENT_RESUME);\n }\n\n @Override\n public void onDestroyView() {\n super.onDestroyView();\n }\n\n\n public DimensionVector3<Float> getMultiPlayerPos(String dbKey) throws Exception {\n try {\n WorldData wData = worldProvider.getWorld().getWorldData();\n wData.openDB();\n byte[] data = wData.db.get(dbKey.getBytes(NBTConstants.CHARSET));\n if(data == null) throw new Exception(\"no data!\");\n final CompoundTag player = (CompoundTag) DataConverter.read(data).get(0);\n\n ListTag posVec = (ListTag) player.getChildTagByKey(\"Pos\");\n if (posVec == null || posVec.getValue() == null)\n throw new Exception(\"No \\\"Pos\\\" specified\");\n if (posVec.getValue().size() != 3)\n throw new Exception(\"\\\"Pos\\\" value is invalid. value: \" + posVec.getValue().toString());\n\n IntTag dimensionId = (IntTag) player.getChildTagByKey(\"DimensionId\");\n if(dimensionId == null || dimensionId.getValue() == null)\n throw new Exception(\"No \\\"DimensionId\\\" specified\");\n Dimension dimension = Dimension.getDimension(dimensionId.getValue());\n if(dimension == null) dimension = Dimension.OVERWORLD;\n\n return new DimensionVector3<>(\n (float) posVec.getValue().get(0).getValue(),\n (float) posVec.getValue().get(1).getValue(),\n (float) posVec.getValue().get(2).getValue(),\n dimension);\n\n } catch (Exception e) {\n Log.e(e.getMessage());\n\n Exception e2 = new Exception(\"Could not find \"+dbKey);\n e2.setStackTrace(e.getStackTrace());\n throw e2;\n }\n }\n\n public DimensionVector3<Float> getPlayerPos() throws Exception {\n try {\n WorldData wData = worldProvider.getWorld().getWorldData();\n wData.openDB();\n byte[] data = wData.db.get(World.SpecialDBEntryType.LOCAL_PLAYER.keyBytes);\n\n final CompoundTag player = data != null\n ? (CompoundTag) DataConverter.read(data).get(0)\n : (CompoundTag) worldProvider.getWorld().level.getChildTagByKey(\"Player\");\n\n ListTag posVec = (ListTag) player.getChildTagByKey(\"Pos\");\n if (posVec == null || posVec.getValue() == null)\n throw new Exception(\"No \\\"Pos\\\" specified\");\n if (posVec.getValue().size() != 3)\n throw new Exception(\"\\\"Pos\\\" value is invalid. value: \" + posVec.getValue().toString());\n\n IntTag dimensionId = (IntTag) player.getChildTagByKey(\"DimensionId\");\n if(dimensionId == null || dimensionId.getValue() == null)\n throw new Exception(\"No \\\"DimensionId\\\" specified\");\n Dimension dimension = Dimension.getDimension(dimensionId.getValue());\n if(dimension == null) dimension = Dimension.OVERWORLD;\n\n return new DimensionVector3<>(\n (float) posVec.getValue().get(0).getValue(),\n (float) posVec.getValue().get(1).getValue(),\n (float) posVec.getValue().get(2).getValue(),\n dimension);\n\n } catch (Exception e) {\n Log.e(e.toString());\n\n Exception e2 = new Exception(\"Could not find player.\");\n e2.setStackTrace(e.getStackTrace());\n throw e2;\n }\n }\n\n public DimensionVector3<Integer> getSpawnPos() throws Exception {\n try {\n CompoundTag level = this.worldProvider.getWorld().level;\n int spawnX = ((IntTag) level.getChildTagByKey(\"SpawnX\")).getValue();\n int spawnY = ((IntTag) level.getChildTagByKey(\"SpawnY\")).getValue();\n int spawnZ = ((IntTag) level.getChildTagByKey(\"SpawnZ\")).getValue();\n if(spawnY == 256){\n TerrainChunkData data = new ChunkManager(\n this.worldProvider.getWorld().getWorldData(), Dimension.OVERWORLD)\n .getChunk(spawnX >> 4, spawnZ >> 4)\n .getTerrain((byte) 0);\n if(data.load2DData()) spawnY = data.getHeightMapValue(spawnX % 16, spawnZ % 16) + 1;\n }\n return new DimensionVector3<>( spawnX, spawnY, spawnZ, Dimension.OVERWORLD);\n } catch (Exception e){\n throw new Exception(\"Could not find spawn\");\n }\n }\n\n public static class MarkerListAdapter extends ArrayAdapter<AbstractMarker> {\n\n\n MarkerListAdapter(Context context, List<AbstractMarker> objects) {\n super(context, 0, objects);\n }\n\n @NonNull\n @Override\n public View getView(int position, View convertView, @NonNull ViewGroup parent) {\n\n RelativeLayout v = (RelativeLayout) convertView;\n\n if (v == null) {\n LayoutInflater vi;\n vi = LayoutInflater.from(getContext());\n v = (RelativeLayout) vi.inflate(R.layout.marker_list_entry, parent, false);\n }\n\n AbstractMarker m = getItem(position);\n\n if (m != null) {\n TextView name = (TextView) v.findViewById(R.id.marker_name);\n TextView xz = (TextView) v.findViewById(R.id.marker_xz);\n ImageView icon = (ImageView) v.findViewById(R.id.marker_icon);\n\n name.setText(m.getNamedBitmapProvider().getBitmapDisplayName());\n String xzStr = String.format(Locale.ENGLISH, \"x: %d, y: %d, z: %d\", m.x, m.y, m.z);\n xz.setText(xzStr);\n\n m.loadIcon(icon);\n\n }\n\n return v;\n }\n\n }\n\n public enum MarkerTapOption {\n\n TELEPORT_LOCAL_PLAYER(R.string.teleport_local_player),\n REMOVE_MARKER(R.string.remove_custom_marker);\n\n public final int stringId;\n\n MarkerTapOption(int id){\n this.stringId = id;\n }\n\n }\n\n public String[] getMarkerTapOptions(){\n MarkerTapOption[] values = MarkerTapOption.values();\n int len = values.length;\n String[] options = new String[len];\n for(int i = 0; i < len; i++){\n options[i] = getString(values[i].stringId);\n }\n return options;\n }\n\n @Nullable\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n\n //TODO handle savedInstance...\n\n\n View rootView = inflater.inflate(R.layout.map_fragment, container, false);\n RelativeLayout worldContainer = (RelativeLayout) rootView.findViewById(R.id.world_tileview_container);\n assert worldContainer != null;\n\n /*\n GPS button: moves camera to player position\n */\n FloatingActionButton fabGPSPlayer = (FloatingActionButton) rootView.findViewById(R.id.fab_menu_gps_player);\n assert fabGPSPlayer != null;\n fabGPSPlayer.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n try {\n if(tileView == null) throw new Exception(\"No map available.\");\n\n DimensionVector3<Float> playerPos = getPlayerPos();\n\n Snackbar.make(tileView,\n getString(R.string.something_at_xyz_dim_float, getString(R.string.player),\n playerPos.x, playerPos.y, playerPos.z, playerPos.dimension.name),\n Snackbar.LENGTH_SHORT)\n .setAction(\"Action\", null).show();\n\n if(playerPos.dimension != worldProvider.getDimension()){\n worldProvider.changeMapType(playerPos.dimension.defaultMapType, playerPos.dimension);\n }\n\n worldProvider.logFirebaseEvent(WorldActivity.CustomFirebaseEvent.GPS_PLAYER);\n\n frameTo((double) playerPos.x, (double) playerPos.z);\n\n } catch (Exception e){\n e.printStackTrace();\n Snackbar.make(view, R.string.failed_find_player, Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n }\n }\n });\n\n /*\n GPS button: moves camera to spawn\n */\n FloatingActionButton fabGPSSpawn = (FloatingActionButton) rootView.findViewById(R.id.fab_menu_gps_spawn);\n assert fabGPSSpawn != null;\n fabGPSSpawn.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n try {\n DimensionVector3<Integer> spawnPos = getSpawnPos();\n\n Snackbar.make(tileView,\n getString(R.string.something_at_xyz_dim_int, getString(R.string.spawn),\n spawnPos.x, spawnPos.y, spawnPos.z, spawnPos.dimension.name),\n Snackbar.LENGTH_SHORT)\n .setAction(\"Action\", null).show();\n\n if(spawnPos.dimension != worldProvider.getDimension()){\n worldProvider.changeMapType(spawnPos.dimension.defaultMapType, spawnPos.dimension);\n }\n\n worldProvider.logFirebaseEvent(WorldActivity.CustomFirebaseEvent.GPS_SPAWN);\n\n frameTo((double) spawnPos.x, (double) spawnPos.z);\n\n } catch (Exception e){\n e.printStackTrace();\n Snackbar.make(view, R.string.failed_find_spawn, Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n }\n }\n });\n\n\n final Activity activity = getActivity();\n\n if(activity == null){\n new Exception(\"MapFragment: activity is null, cannot set worldProvider!\").printStackTrace();\n return null;\n }\n try {\n //noinspection ConstantConditions\n worldProvider = (WorldActivityInterface) activity;\n } catch (ClassCastException e){\n new Exception(\"MapFragment: activity is not an worldprovider, cannot set worldProvider!\", e).printStackTrace();\n return null;\n }\n\n\n //show the toolbar if the fab menu is opened\n FloatingActionMenu fabMenu = (FloatingActionMenu) rootView.findViewById(R.id.fab_menu);\n fabMenu.setOnMenuToggleListener(new FloatingActionMenu.OnMenuToggleListener() {\n @Override\n public void onMenuToggle(boolean opened) {\n if(opened) worldProvider.showActionBar();\n else worldProvider.hideActionBar();\n }\n });\n\n\n\n FloatingActionButton fabGPSMarker = (FloatingActionButton) rootView.findViewById(R.id.fab_menu_gps_marker);\n assert fabGPSMarker != null;\n fabGPSMarker.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n try {\n Collection<AbstractMarker> markers = worldProvider.getWorld().getMarkerManager().getMarkers();\n\n if(markers.isEmpty()){\n AlertDialog.Builder builder = new AlertDialog.Builder(activity);\n TextView msg = new TextView(activity);\n float dpi = activity.getResources().getDisplayMetrics().density;\n msg.setPadding((int)(19*dpi), (int)(5*dpi), (int)(14*dpi), (int)(5*dpi));\n msg.setMaxLines(20);\n msg.setText(R.string.no_custom_markers);\n builder.setView(msg)\n .setTitle(R.string.no_custom_markers_title)\n .setCancelable(true)\n .setNeutralButton(android.R.string.ok, null)\n .show();\n } else {\n\n AlertDialog.Builder markerDialogBuilder = new AlertDialog.Builder(activity);\n markerDialogBuilder.setIcon(R.drawable.ic_place);\n markerDialogBuilder.setTitle(R.string.go_to_a_marker_list);\n\n final MarkerListAdapter arrayAdapter = new MarkerListAdapter(activity, new ArrayList<>(markers));\n\n markerDialogBuilder.setNegativeButton(android.R.string.cancel, null);\n\n markerDialogBuilder.setAdapter(\n arrayAdapter,\n new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int which) {\n AbstractMarker m = arrayAdapter.getItem(which);\n if(m == null) return;\n\n Snackbar.make(tileView,\n activity.getString(R.string.something_at_xyz_dim_int,\n m.getNamedBitmapProvider().getBitmapDisplayName(),\n m.x, m.y, m.z, m.dimension.name),\n Snackbar.LENGTH_SHORT)\n .setAction(\"Action\", null).show();\n\n if(m.dimension != worldProvider.getDimension()){\n worldProvider.changeMapType(m.dimension.defaultMapType, m.dimension);\n }\n\n frameTo((double) m.x, (double) m.z);\n\n worldProvider.logFirebaseEvent(WorldActivity.CustomFirebaseEvent.GPS_MARKER);\n }\n });\n markerDialogBuilder.show();\n }\n\n } catch (Exception e){\n Snackbar.make(view, e.getMessage(), Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n }\n }\n });\n\n\n /*\n GPS button: moves camera to player position\n */\n FloatingActionButton fabGPSMultiplayer = (FloatingActionButton) rootView.findViewById(R.id.fab_menu_gps_multiplayer);\n assert fabGPSMultiplayer != null;\n fabGPSMultiplayer.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(final View view) {\n\n if (tileView == null){\n Snackbar.make(view, R.string.no_map_available, Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n return;\n }\n\n Snackbar.make(tileView,\n R.string.searching_for_players,\n Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n\n //this can take some time... ...do it in the background\n (new AsyncTask<Void, Void, String[]>(){\n\n @Override\n protected String[] doInBackground(Void... arg0) {\n try {\n return worldProvider.getWorld().getWorldData().getPlayers();\n } catch (Exception e){\n return null;\n }\n }\n\n protected void onPostExecute(final String[] players) {\n getActivity().runOnUiThread(new Runnable() {\n @Override\n public void run() {\n\n if(players == null){\n Snackbar.make(view, R.string.failed_to_retrieve_player_data, Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n return;\n }\n\n if(players.length == 0){\n Snackbar.make(view, R.string.no_multiplayer_data_found, Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n return;\n }\n\n\n\n //NBT tag type spinner\n final Spinner spinner = new Spinner(activity);\n ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<>(activity,\n android.R.layout.simple_spinner_item, players);\n\n spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);\n spinner.setAdapter(spinnerArrayAdapter);\n\n\n //wrap layout in alert\n new AlertDialog.Builder(activity)\n .setTitle(R.string.go_to_player)\n .setView(spinner)\n .setPositiveButton(R.string.go_loud, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int whichButton) {\n\n //new tag type\n int spinnerIndex = spinner.getSelectedItemPosition();\n String playerKey = players[spinnerIndex];\n\n try {\n DimensionVector3<Float> playerPos = getMultiPlayerPos(playerKey);\n\n Snackbar.make(tileView,\n getString(R.string.something_at_xyz_dim_float,\n playerKey,\n playerPos.x,\n playerPos.y,\n playerPos.z,\n playerPos.dimension.name),\n Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n\n worldProvider.logFirebaseEvent(WorldActivity.CustomFirebaseEvent.GPS_MULTIPLAYER);\n\n if(playerPos.dimension != worldProvider.getDimension()){\n worldProvider.changeMapType(playerPos.dimension.defaultMapType, playerPos.dimension);\n }\n\n frameTo((double) playerPos.x, (double) playerPos.z);\n\n } catch (Exception e){\n Snackbar.make(view, e.getMessage(), Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n }\n\n }\n })\n //or alert is cancelled\n .setNegativeButton(android.R.string.cancel, null)\n .show();\n }\n });\n }\n\n }).execute();\n\n }\n });\n\n\n /*\n GPS button: moves camera to player position\n */\n FloatingActionButton fabGPSCoord = (FloatingActionButton) rootView.findViewById(R.id.fab_menu_gps_coord);\n assert fabGPSCoord != null;\n fabGPSCoord.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n try {\n if(tileView == null) throw new Exception(\"No map available.\");\n\n View xzForm = LayoutInflater.from(activity).inflate(R.layout.xz_coord_form, null);\n final EditText xInput = (EditText) xzForm.findViewById(R.id.x_input);\n xInput.setText(\"0\");\n final EditText zInput = (EditText) xzForm.findViewById(R.id.z_input);\n zInput.setText(\"0\");\n\n //wrap layout in alert\n new AlertDialog.Builder(activity)\n .setTitle(R.string.go_to_coordinate)\n .setView(xzForm)\n .setPositiveButton(R.string.go_loud, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n\n int inX, inZ;\n try{\n inX = Integer.parseInt(xInput.getText().toString());\n } catch (NullPointerException | NumberFormatException e){\n Toast.makeText(activity, R.string.invalid_x_coordinate,Toast.LENGTH_LONG).show();\n return;\n }\n try{\n inZ = Integer.parseInt(zInput.getText().toString());\n } catch (NullPointerException | NumberFormatException e){\n Toast.makeText(activity, R.string.invalid_z_coordinate,Toast.LENGTH_LONG).show();\n return;\n }\n\n worldProvider.logFirebaseEvent(WorldActivity.CustomFirebaseEvent.GPS_COORD);\n\n frameTo((double) inX, (double) inZ);\n }\n })\n .setCancelable(true)\n .setNegativeButton(android.R.string.cancel, null)\n .show();\n\n } catch (Exception e){\n Snackbar.make(view, e.getMessage(), Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n }\n }\n });\n\n\n\n try {\n Entity.loadEntityBitmaps(activity.getAssets());\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n try {\n Block.loadBitmaps(activity.getAssets());\n } catch (IOException e) {\n e.printStackTrace();\n }\n try{\n CustomIcon.loadCustomBitmaps(activity.getAssets());\n } catch (IOException e){\n e.printStackTrace();\n }\n\n\n\n\n /*\n Create tile view\n */\n this.tileView = new TileView(activity) {\n\n @Override\n public void onLongPress(MotionEvent event) {\n\n Dimension dimension = worldProvider.getDimension();\n\n // 1 chunk per tile on scale 1.0\n int pixelsPerBlockW_unscaled = MCTileProvider.TILESIZE / dimension.chunkW;\n int pixelsPerBlockL_unscaled = MCTileProvider.TILESIZE / dimension.chunkL;\n\n float pixelsPerBlockScaledW = pixelsPerBlockW_unscaled * this.getScale();\n float pixelsPerBlockScaledL = pixelsPerBlockL_unscaled * this.getScale();\n\n\n double worldX = ((( this.getScrollX() + event.getX()) / pixelsPerBlockScaledW) - MCTileProvider.HALF_WORLDSIZE) / dimension.dimensionScale;\n double worldZ = ((( this.getScrollY() + event.getY()) / pixelsPerBlockScaledL) - MCTileProvider.HALF_WORLDSIZE) / dimension.dimensionScale;\n\n MapFragment.this.onLongClick(worldX, worldZ);\n }\n };\n\n this.tileView.setId(ViewID.generateViewId());\n\n //set the map-type\n tileView.getDetailLevelManager().setLevelType(worldProvider.getMapType());\n\n /*\n Add tile view to main layout\n */\n\n //add world view to its container in the main layout\n worldContainer.addView(tileView);\n\n\n /*\n Create tile(=bitmap) provider\n */\n this.minecraftTileProvider = new MCTileProvider(worldProvider);\n\n\n\n /*\n Set the bitmap-provider of the tile view\n */\n this.tileView.setBitmapProvider(this.minecraftTileProvider);\n\n\n /*\n Change tile view settings\n */\n\n this.tileView.setBackgroundColor(0xFF494E8E);\n\n // markers should align to the coordinate along the horizontal center and vertical bottom\n tileView.setMarkerAnchorPoints(-0.5f, -1.0f);\n\n this.tileView.defineBounds(\n -1.0,\n -1.0,\n 1.0,\n 1.0\n );\n\n this.tileView.setSize(MCTileProvider.viewSizeW, MCTileProvider.viewSizeL);\n\n for(MapType mapType : MapType.values()){\n this.tileView.addDetailLevel(0.0625f, \"0.0625\", MCTileProvider.TILESIZE, MCTileProvider.TILESIZE, mapType);// 1/(1/16)=16 chunks per tile\n this.tileView.addDetailLevel(0.125f, \"0.125\", MCTileProvider.TILESIZE, MCTileProvider.TILESIZE, mapType);\n this.tileView.addDetailLevel(0.25f, \"0.25\", MCTileProvider.TILESIZE, MCTileProvider.TILESIZE, mapType);\n this.tileView.addDetailLevel(0.5f, \"0.5\", MCTileProvider.TILESIZE, MCTileProvider.TILESIZE, mapType);\n this.tileView.addDetailLevel(1f, \"1\", MCTileProvider.TILESIZE, MCTileProvider.TILESIZE, mapType);// 1/1=1 chunk per tile\n\n }\n\n this.tileView.setScale(0.5f);\n\n\n boolean framedToPlayer = false;\n\n //TODO multi-thread this\n try {\n\n DimensionVector3<Float> playerPos = getPlayerPos();\n float x = playerPos.x, y = playerPos.y, z = playerPos.z;\n Log.d(\"Placed player marker at: \"+x+\";\"+y+\";\"+z+\" [\"+playerPos.dimension.name+\"]\");\n localPlayerMarker = new AbstractMarker((int) x, (int) y, (int) z,\n playerPos.dimension, new CustomNamedBitmapProvider(Entity.PLAYER, \"~local_player\"), false);\n this.staticMarkers.add(localPlayerMarker);\n addMarker(localPlayerMarker);\n\n if(localPlayerMarker.dimension != worldProvider.getDimension()){\n worldProvider.changeMapType(localPlayerMarker.dimension.defaultMapType, localPlayerMarker.dimension);\n }\n\n frameTo((double) x, (double) z);\n framedToPlayer = true;\n\n } catch (Exception e){\n e.printStackTrace();\n Log.d(\"Failed to place player marker. \"+e.toString());\n }\n\n\n try {\n DimensionVector3<Integer> spawnPos = getSpawnPos();\n\n spawnMarker = new AbstractMarker(spawnPos.x, spawnPos.y, spawnPos.z, spawnPos.dimension,\n new CustomNamedBitmapProvider(CustomIcon.SPAWN_MARKER, \"Spawn\"), false);\n this.staticMarkers.add(spawnMarker);\n addMarker(spawnMarker);\n\n if(!framedToPlayer){\n\n if(spawnMarker.dimension != worldProvider.getDimension()){\n worldProvider.changeMapType(spawnMarker.dimension.defaultMapType, spawnMarker.dimension);\n }\n\n frameTo((double) spawnPos.x, (double) spawnPos.z);\n }\n\n } catch (Exception e){\n //no spawn defined...\n if(!framedToPlayer) frameTo(0.0, 0.0);\n\n }\n\n\n\n\n\n\n tileView.getMarkerLayout().setMarkerTapListener(new MarkerLayout.MarkerTapListener() {\n @Override\n public void onMarkerTap(View view, int tapX, int tapY) {\n if(!(view instanceof MarkerImageView)){\n Log.d(\"Markertaplistener found a marker that is not a MarkerImageView! \"+view.toString());\n return;\n }\n\n final AbstractMarker marker = ((MarkerImageView) view).getMarkerHook();\n if(marker == null){\n Log.d(\"abstract marker is null! \"+view.toString());\n return;\n }\n\n AlertDialog.Builder builder = new AlertDialog.Builder(activity);\n builder\n .setTitle(String.format(getString(R.string.marker_info), marker.getNamedBitmapProvider().getBitmapDisplayName(), marker.getNamedBitmapProvider().getBitmapDataName(), marker.x, marker.y, marker.z, marker.dimension))\n .setItems(getMarkerTapOptions(), new DialogInterface.OnClickListener() {\n @SuppressWarnings(\"RedundantCast\")\n @SuppressLint(\"SetTextI18n\")\n public void onClick(DialogInterface dialog, int which) {\n\n final MarkerTapOption chosen = MarkerTapOption.values()[which];\n\n switch (chosen){\n case TELEPORT_LOCAL_PLAYER: {\n try {\n final EditableNBT playerEditable = worldProvider.getEditablePlayer();\n if (playerEditable == null)\n throw new Exception(\"Player is null\");\n\n Iterator playerIter = playerEditable.getTags().iterator();\n if (!playerIter.hasNext())\n throw new Exception(\"Player DB entry is empty!\");\n\n //db entry consists of one compound tag\n final CompoundTag playerTag = (CompoundTag) playerIter.next();\n\n ListTag posVec = (ListTag) playerTag.getChildTagByKey(\"Pos\");\n\n if (posVec == null) throw new Exception(\"No \\\"Pos\\\" specified\");\n\n final List<Tag> playerPos = posVec.getValue();\n if (playerPos == null)\n throw new Exception(\"No \\\"Pos\\\" specified\");\n if (playerPos.size() != 3)\n throw new Exception(\"\\\"Pos\\\" value is invalid. value: \" + posVec.getValue().toString());\n\n IntTag dimensionId = (IntTag) playerTag.getChildTagByKey(\"DimensionId\");\n if(dimensionId == null || dimensionId.getValue() == null)\n throw new Exception(\"No \\\"DimensionId\\\" specified\");\n\n\n int newX = marker.x;\n int newY = marker.y;\n int newZ = marker.z;\n Dimension newDimension = marker.dimension;\n\n ((FloatTag) playerPos.get(0)).setValue(((float) newX) + 0.5f);\n ((FloatTag) playerPos.get(1)).setValue(((float) newY) + 0.5f);\n ((FloatTag) playerPos.get(2)).setValue(((float) newZ) + 0.5f);\n dimensionId.setValue(newDimension.id);\n\n\n if(playerEditable.save()){\n\n localPlayerMarker = moveMarker(localPlayerMarker,newX, newY, newZ, newDimension);\n\n //TODO could be improved for translation friendliness\n Snackbar.make(tileView,\n activity.getString(R.string.teleported_player_to_xyz_dimension)+newX+\";\"+newY+\";\"+newZ+\" [\"+newDimension.name+\"] (\"+marker.getNamedBitmapProvider().getBitmapDisplayName()+\")\",\n Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n\n } else throw new Exception(\"Failed saving player\");\n\n } catch (Exception e){\n Log.w(e.toString());\n\n Snackbar.make(tileView, R.string.failed_teleporting_player,\n Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n }\n return;\n }\n case REMOVE_MARKER: {\n if(marker.isCustom){\n MapFragment.this.removeMarker(marker);\n MarkerManager mng = MapFragment.this.worldProvider.getWorld().getMarkerManager();\n mng.removeMarker(marker, true);\n\n mng.save();\n\n } else {\n //only custom markers are meant to be removable\n Snackbar.make(tileView, R.string.marker_is_not_removable,\n Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n }\n }\n }\n }\n })\n .setCancelable(true)\n .setNegativeButton(android.R.string.cancel, null)\n .show();\n\n }\n });\n\n\n\n //do not loop the scale\n tileView.setShouldLoopScale(false);\n\n //prevents flickering\n this.tileView.setTransitionsEnabled(false);\n\n //more responsive rendering\n this.tileView.setShouldRenderWhilePanning(true);\n\n this.tileView.setSaveEnabled(true);\n\n\n\n return rootView;\n }\n\n /**\n * Creates a new marker (looking exactly the same as the old one) on the new position,\n * while removing the old marker.\n * @param marker Marker to be recreated\n * @param x new pos X\n * @param y new pos Y\n * @param z new pos Z\n * @param dimension new pos Dimension\n * @return the newly created marker, which should replace the old one.\n */\n public AbstractMarker moveMarker(AbstractMarker marker, int x, int y, int z, Dimension dimension){\n AbstractMarker newMarker = marker.copy(x, y, z, dimension);\n if(staticMarkers.remove(marker)) staticMarkers.add(newMarker);\n this.removeMarker(marker);\n this.addMarker(newMarker);\n\n if(marker.isCustom){\n MarkerManager mng = this.worldProvider.getWorld().getMarkerManager();\n mng.removeMarker(marker, true);\n mng.addMarker(newMarker, true);\n }\n\n return newMarker;\n }\n\n private final static int MARKER_INTERVAL_CHECK = 50;\n private int proceduralMarkersInterval = 0;\n private volatile AsyncTask shrinkProceduralMarkersTask;\n\n\n /**\n * Calculates viewport of tileview, expressed in blocks.\n * @param marginX horizontal viewport-margin, in pixels\n * @param marginZ vertical viewport-margin, in pixels\n * @return minimum_X, maximum_X, minimum_Z, maximum_Z, dimension. (min and max are expressed in blocks!)\n */\n public Object[] calculateViewPort(int marginX, int marginZ){\n\n Dimension dimension = this.worldProvider.getDimension();\n\n // 1 chunk per tile on scale 1.0\n int pixelsPerBlockW_unscaled = MCTileProvider.TILESIZE / dimension.chunkW;\n int pixelsPerBlockL_unscaled = MCTileProvider.TILESIZE / dimension.chunkL;\n\n float scale = tileView.getScale();\n\n //scale the amount of pixels, less pixels per block if zoomed out\n double pixelsPerBlockW = pixelsPerBlockW_unscaled * scale;\n double pixelsPerBlockL = pixelsPerBlockL_unscaled * scale;\n\n long blockX = Math.round( (tileView.getScrollX() - marginX) / pixelsPerBlockW ) - MCTileProvider.HALF_WORLDSIZE;\n long blockZ = Math.round( (tileView.getScrollY() - marginZ) / pixelsPerBlockL ) - MCTileProvider.HALF_WORLDSIZE;\n long blockW = Math.round( (tileView.getWidth() + marginX + marginX) / pixelsPerBlockW );\n long blockH = Math.round( (tileView.getHeight() + marginZ + marginZ) / pixelsPerBlockL );\n\n return new Object[]{ blockX, blockX + blockW, blockZ, blockH, dimension };\n }\n\n public AsyncTask retainViewPortMarkers(final Runnable callback){\n\n DisplayMetrics displayMetrics = this.getActivity().getResources().getDisplayMetrics();\n return new AsyncTask<Object, AbstractMarker, Void>(){\n @Override\n protected Void doInBackground(Object... params) {\n long minX = (long) params[0],\n maxX = (long) params[1],\n minY = (long) params[2],\n maxY = (long) params[3];\n Dimension reqDim = (Dimension) params[4];\n\n for (AbstractMarker p : MapFragment.this.proceduralMarkers){\n\n // do not remove static markers\n if(MapFragment.this.staticMarkers.contains(p)) continue;\n\n if(p.x < minX || p.x > maxX || p.y < minY || p.y > maxY || p.dimension != reqDim){\n this.publishProgress(p);\n }\n }\n return null;\n }\n\n @Override\n protected void onProgressUpdate(final AbstractMarker... values) {\n for(AbstractMarker v : values) {\n MapFragment.this.removeMarker(v);\n }\n }\n\n @Override\n protected void onPostExecute(Void aVoid) {\n callback.run();\n }\n\n }.execute(this.calculateViewPort(\n displayMetrics.widthPixels / 2,\n displayMetrics.heightPixels / 2)\n );\n }\n\n /**\n * Important: this method should be run from the UI thread.\n * @param marker The marker to remove from the tile view.\n */\n public void removeMarker(AbstractMarker marker){\n staticMarkers.remove(marker);\n proceduralMarkers.remove(marker);\n if(marker.view != null) tileView.removeMarker(marker.view);\n }\n\n /**\n * Important: this method should be run from the UI thread.\n * @param marker The marker to add to the tile view.\n */\n public void addMarker(AbstractMarker marker){\n\n if(proceduralMarkers.contains(marker)) return;\n\n if(shrinkProceduralMarkersTask == null\n && ++proceduralMarkersInterval > MARKER_INTERVAL_CHECK){\n //shrink set of markers to viewport every so often\n shrinkProceduralMarkersTask = retainViewPortMarkers(new Runnable() {\n @Override\n public void run() {\n //reset this to start accepting viewport update requests again.\n shrinkProceduralMarkersTask = null;\n }\n });\n\n proceduralMarkersInterval = 0;\n }\n\n\n proceduralMarkers.add(marker);\n\n\n Activity act = getActivity();\n if (act == null) return;\n MarkerImageView markerView = marker.getView(act);\n\n this.filterMarker(marker);\n\n if(tileView.getMarkerLayout().indexOfChild(markerView) >= 0){\n tileView.getMarkerLayout().removeMarker(markerView);\n }\n\n\n tileView.addMarker(markerView,\n marker.dimension.dimensionScale * (double) marker.x / (double) MCTileProvider.HALF_WORLDSIZE,\n marker.dimension.dimensionScale * (double) marker.z / (double) MCTileProvider.HALF_WORLDSIZE,\n -0.5f, -0.5f);\n }\n\n public void toggleMarkers(){\n int visibility = tileView.getMarkerLayout().getVisibility();\n tileView.getMarkerLayout().setVisibility( visibility == View.VISIBLE ? View.GONE : View.VISIBLE);\n }\n\n\n public enum LongClickOption {\n\n TELEPORT_LOCAL_PLAYER(R.string.teleport_local_player, null),\n CREATE_MARKER(R.string.create_custom_marker, null),\n //TODO TELEPORT_MULTI_PLAYER(\"Teleport other player\", null),\n ENTITY(R.string.open_chunk_entity_nbt, ChunkTag.ENTITY),\n TILE_ENTITY(R.string.open_chunk_tile_entity_nbt, ChunkTag.BLOCK_ENTITY);\n\n public final int stringId;\n public final ChunkTag dataType;\n\n LongClickOption(int id, ChunkTag dataType){\n this.stringId = id;\n this.dataType = dataType;\n }\n\n }\n\n public String[] getLongClickOptions(){\n LongClickOption[] values = LongClickOption.values();\n int len = values.length;\n String[] options = new String[len];\n for(int i = 0; i < len; i++){\n options[i] = getString(values[i].stringId);\n }\n return options;\n }\n\n\n public void onLongClick(final double worldX, final double worldZ){\n\n\n final Activity activity = MapFragment.this.getActivity();\n\n\n final Dimension dim = this.worldProvider.getDimension();\n\n double chunkX = worldX / dim.chunkW;\n double chunkZ = worldZ / dim.chunkL;\n\n //negative doubles are rounded up when casting to int; floor them\n final int chunkXint = chunkX < 0 ? (((int) chunkX) - 1) : ((int) chunkX);\n final int chunkZint = chunkZ < 0 ? (((int) chunkZ) - 1) : ((int) chunkZ);\n\n\n\n final View container = activity.findViewById(R.id.world_content);\n if(container == null){\n Log.w(\"CANNOT FIND MAIN CONTAINER, WTF\");\n return;\n }\n\n new AlertDialog.Builder(activity)\n .setTitle(getString(R.string.postion_2D_floats_with_chunkpos, worldX, worldZ, chunkXint, chunkZint, dim.name))\n .setItems(getLongClickOptions(), new DialogInterface.OnClickListener() {\n @SuppressLint(\"SetTextI18n\")\n public void onClick(DialogInterface dialog, int which) {\n\n final LongClickOption chosen = LongClickOption.values()[which];\n\n\n switch (chosen){\n case TELEPORT_LOCAL_PLAYER:{\n try {\n\n final EditableNBT playerEditable = MapFragment.this.worldProvider.getEditablePlayer();\n if(playerEditable == null) throw new Exception(\"Player is null\");\n\n Iterator playerIter = playerEditable.getTags().iterator();\n if(!playerIter.hasNext()) throw new Exception(\"Player DB entry is empty!\");\n\n //db entry consists of one compound tag\n final CompoundTag playerTag = (CompoundTag) playerIter.next();\n\n ListTag posVec = (ListTag) playerTag.getChildTagByKey(\"Pos\");\n\n if (posVec == null) throw new Exception(\"No \\\"Pos\\\" specified\");\n\n final List<Tag> playerPos = posVec.getValue();\n if(playerPos == null)\n throw new Exception(\"No \\\"Pos\\\" specified\");\n if (playerPos.size() != 3)\n throw new Exception(\"\\\"Pos\\\" value is invalid. value: \" + posVec.getValue().toString());\n\n final IntTag dimensionId = (IntTag) playerTag.getChildTagByKey(\"DimensionId\");\n if(dimensionId == null || dimensionId.getValue() == null)\n throw new Exception(\"No \\\"DimensionId\\\" specified\");\n\n\n float playerY = (float) playerPos.get(1).getValue();\n\n\n View yForm = LayoutInflater.from(activity).inflate(R.layout.y_coord_form, null);\n final EditText yInput = (EditText) yForm.findViewById(R.id.y_input);\n yInput.setText(String.valueOf(playerY));\n\n final float newX = (float) worldX;\n final float newZ = (float) worldZ;\n\n new AlertDialog.Builder(activity)\n .setTitle(chosen.stringId)\n .setView(yForm)\n .setPositiveButton(R.string.action_teleport, new DialogInterface.OnClickListener() {\n @SuppressWarnings(\"RedundantCast\")\n @Override\n public void onClick(DialogInterface dialog, int which) {\n\n float newY;\n Editable value = yInput.getText();\n if(value == null) newY = 64f;\n else {\n try {\n newY = (float) Float.parseFloat(value.toString());//removes excessive precision\n } catch (Exception e){\n newY = 64f;\n }\n }\n\n ((FloatTag) playerPos.get(0)).setValue(newX);\n ((FloatTag) playerPos.get(1)).setValue(newY);\n ((FloatTag) playerPos.get(2)).setValue(newZ);\n dimensionId.setValue(dim.id);\n\n if(playerEditable.save()){\n\n MapFragment.this.localPlayerMarker = MapFragment.this.moveMarker(\n MapFragment.this.localPlayerMarker,\n (int) newX, (int) newY, (int) newZ, dim);\n\n Snackbar.make(container,\n String.format(getString(R.string.teleported_player_to_xyz_dim), newX, newY, newZ, dim.name),\n Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n } else {\n Snackbar.make(container,\n R.string.failed_teleporting_player,\n Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n }\n }\n })\n .setCancelable(true)\n .setNegativeButton(android.R.string.cancel, null)\n .show();\n return;\n\n } catch (Exception e){\n e.printStackTrace();\n Snackbar.make(container, R.string.failed_to_find_or_edit_local_player_data,\n Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n return;\n }\n }\n case CREATE_MARKER:{\n\n View createMarkerForm = LayoutInflater.from(activity).inflate(R.layout.create_marker_form, null);\n\n final EditText markerNameInput = (EditText) createMarkerForm.findViewById(R.id.marker_displayname_input);\n markerNameInput.setText(R.string.default_custom_marker_name);\n final EditText markerIconNameInput = (EditText) createMarkerForm.findViewById(R.id.marker_iconname_input);\n markerIconNameInput.setText(\"blue_marker\");\n final EditText xInput = (EditText) createMarkerForm.findViewById(R.id.x_input);\n xInput.setText(String.valueOf((int) worldX));\n final EditText yInput = (EditText) createMarkerForm.findViewById(R.id.y_input);\n yInput.setText(String.valueOf(64));\n final EditText zInput = (EditText) createMarkerForm.findViewById(R.id.z_input);\n zInput.setText(String.valueOf((int) worldZ));\n\n\n new AlertDialog.Builder(activity)\n .setTitle(chosen.stringId)\n .setView(createMarkerForm)\n .setPositiveButton(\"Create marker\", new DialogInterface.OnClickListener() {\n\n public void failParseSnackbarReport(int msg){\n Snackbar.make(container, msg,\n Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n }\n\n @Override\n public void onClick(DialogInterface dialog, int which) {\n\n try {\n String displayName = markerNameInput.getText().toString();\n if (displayName.equals(\"\") || displayName.contains(\"\\\"\")) {\n failParseSnackbarReport(R.string.marker_invalid_name);\n return;\n }\n String iconName = markerIconNameInput.getText().toString();\n if (iconName.equals(\"\") || iconName.contains(\"\\\"\")) {\n failParseSnackbarReport(R.string.invalid_icon_name);\n return;\n }\n\n int xM, yM, zM;\n\n String xStr = xInput.getText().toString();\n try {\n xM = Integer.parseInt(xStr);\n } catch (NumberFormatException e) {\n failParseSnackbarReport(R.string.invalid_x_coordinate);\n return;\n }\n String yStr = yInput.getText().toString();\n try {\n yM = Integer.parseInt(yStr);\n } catch (NumberFormatException e) {\n failParseSnackbarReport(R.string.invalid_y_coordinate);\n return;\n }\n\n String zStr = zInput.getText().toString();\n try {\n zM = Integer.parseInt(zStr);\n } catch (NumberFormatException e) {\n failParseSnackbarReport(R.string.invalid_z_coordinate);\n return;\n }\n\n AbstractMarker marker = MarkerManager.markerFromData(displayName, iconName, xM, yM, zM, dim);\n MarkerManager mng = MapFragment.this.worldProvider.getWorld().getMarkerManager();\n mng.addMarker(marker, true);\n\n MapFragment.this.addMarker(marker);\n\n mng.save();\n\n } catch (Exception e){\n e.printStackTrace();\n failParseSnackbarReport(R.string.failed_to_create_marker);\n }\n }\n })\n .setCancelable(true)\n .setNegativeButton(android.R.string.cancel, null)\n .show();\n\n\n\n\n\n return;\n }\n /* TODO multi player teleporting\n case TELEPORT_MULTI_PLAYER:{\n\n break;\n }*/\n case ENTITY:\n case TILE_ENTITY:{\n\n final World world = MapFragment.this.worldProvider.getWorld();\n final ChunkManager chunkManager = new ChunkManager(world.getWorldData(), dim);\n final Chunk chunk = chunkManager.getChunk(chunkXint, chunkZint);\n\n if(!chunkDataNBT(chunk, chosen == LongClickOption.ENTITY)){\n Snackbar.make(container, String.format(getString(R.string.failed_to_load_x), getString(chosen.stringId)),\n Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n }\n\n\n }\n }\n\n\n }\n })\n .setCancelable(true)\n .setNegativeButton(android.R.string.cancel, null)\n .show();\n\n }\n\n /**\n * Opens the chunk data nbt editor.\n *\n * @param chunk the chunk to edit\n * @param entity if it is entity data (True) or block-entity data (False)\n * @return false when the chunk data could not be loaded.\n */\n private boolean chunkDataNBT(Chunk chunk, boolean entity){\n NBTChunkData chunkData;\n try {\n chunkData = entity ? chunk.getEntity() : chunk.getBlockEntity();\n } catch (Exception e) {\n e.printStackTrace();\n return false;\n }\n\n //just open the editor if the data is there for us to edit it\n this.worldProvider.openChunkNBTEditor(chunk.x, chunk.z, chunkData, this.tileView);\n return true;\n }\n\n\n @Override\n public void onDestroy() {\n super.onDestroy();\n\n\n tileView.destroy();\n tileView = null;\n minecraftTileProvider = null;\n\n }\n\n public static class BitmapChoiceListAdapter extends ArrayAdapter<BitmapChoiceListAdapter.NamedBitmapChoice> {\n\n public static class NamedBitmapChoice {\n\n //Using a handle to facilitate bitmap swapping without breaking the filter.\n final NamedBitmapProviderHandle namedBitmap;\n boolean enabledTemp;\n boolean enabled;\n\n public NamedBitmapChoice(NamedBitmapProviderHandle namedBitmap, boolean enabled){\n this.namedBitmap = namedBitmap;\n this.enabled = this.enabledTemp = enabled;\n }\n }\n\n public BitmapChoiceListAdapter(Context context, List<NamedBitmapChoice> objects) {\n super(context, 0, objects);\n }\n\n @NonNull\n @Override\n public View getView(final int position, View v, @NonNull ViewGroup parent) {\n\n final NamedBitmapChoice m = getItem(position);\n if(m == null) return new RelativeLayout(getContext());\n\n if (v == null) v = LayoutInflater\n .from(getContext())\n .inflate(R.layout.img_name_check_list_entry, parent, false);\n\n\n ImageView img = (ImageView) v.findViewById(R.id.entry_img);\n TextView text = (TextView) v.findViewById(R.id.entry_text);\n final CheckBox check = (CheckBox) v.findViewById(R.id.entry_check);\n\n img.setImageBitmap(m.namedBitmap.getNamedBitmapProvider().getBitmap());\n text.setText(m.namedBitmap.getNamedBitmapProvider().getBitmapDisplayName());\n check.setTag(position);\n check.setChecked(m.enabledTemp);\n check.setOnCheckedChangeListener(changeListener);\n\n return v;\n }\n\n private CompoundButton.OnCheckedChangeListener changeListener = new CompoundButton.OnCheckedChangeListener() {\n @Override\n public void onCheckedChanged(CompoundButton compoundButton, boolean b) {\n Object tag = compoundButton.getTag();\n if(tag == null) return;\n int position = (int) tag;\n final NamedBitmapChoice m = getItem(position);\n if(m == null) return;\n m.enabledTemp = b;\n }\n };\n\n }\n\n\n //static, remember choice while app is open.\n static Map<NamedBitmapProvider, BitmapChoiceListAdapter.NamedBitmapChoice> markerFilter = new HashMap<>();\n\n static {\n //entities are enabled by default\n for (Entity v : Entity.values()) {\n //skip things without a bitmap (dropped items etc.)\n //skip entities with placeholder ids (900+)\n if(v.sheetPos < 0 || v.id >= 900) continue;\n markerFilter.put(v.getNamedBitmapProvider(),\n new BitmapChoiceListAdapter.NamedBitmapChoice(v, true));\n }\n //tile-entities are disabled by default\n for (TileEntity v : TileEntity.values()) {\n markerFilter.put(v.getNamedBitmapProvider(),\n new BitmapChoiceListAdapter.NamedBitmapChoice(v, false));\n }\n\n }\n\n public void openMarkerFilter() {\n\n final Activity activity = this.getActivity();\n\n\n final List<BitmapChoiceListAdapter.NamedBitmapChoice> choices = new ArrayList<>();\n choices.addAll(markerFilter.values());\n\n //sort on names, nice for the user.\n Collections.sort(choices, new Comparator<BitmapChoiceListAdapter.NamedBitmapChoice>() {\n @Override\n public int compare(BitmapChoiceListAdapter.NamedBitmapChoice a, BitmapChoiceListAdapter.NamedBitmapChoice b) {\n return a.namedBitmap.getNamedBitmapProvider().getBitmapDisplayName().compareTo(b.namedBitmap.getNamedBitmapProvider().getBitmapDisplayName());\n }\n });\n\n\n\n new AlertDialog.Builder(activity)\n .setTitle(R.string.filter_markers)\n .setAdapter(new BitmapChoiceListAdapter(activity, choices), null)\n .setCancelable(true)\n .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialogInterface, int i) {\n //save all the temporary states.\n for(BitmapChoiceListAdapter.NamedBitmapChoice choice : choices){\n choice.enabled = choice.enabledTemp;\n }\n MapFragment.this.updateMarkerFilter();\n }\n })\n .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialogInterface, int i) {\n //reset all the temporary states.\n for(BitmapChoiceListAdapter.NamedBitmapChoice choice : choices){\n choice.enabledTemp = choice.enabled;\n }\n }\n })\n .setOnCancelListener(new DialogInterface.OnCancelListener() {\n @Override\n public void onCancel(DialogInterface dialogInterface) {\n //reset all the temporary states.\n for(BitmapChoiceListAdapter.NamedBitmapChoice choice : choices){\n choice.enabledTemp = choice.enabled;\n }\n }\n })\n .show();\n }\n\n public void updateMarkerFilter(){\n for(AbstractMarker marker : this.proceduralMarkers){\n filterMarker(marker);\n }\n }\n\n public void filterMarker(AbstractMarker marker){\n BitmapChoiceListAdapter.NamedBitmapChoice choice = markerFilter.get(marker.getNamedBitmapProvider());\n if(choice != null){\n marker.getView(this.getActivity()).setVisibility(\n (choice.enabled && marker.dimension == worldProvider.getDimension())\n ? View.VISIBLE : View.INVISIBLE);\n } else {\n marker.getView(this.getActivity())\n .setVisibility(marker.dimension == worldProvider.getDimension()\n ? View.VISIBLE : View.INVISIBLE);\n }\n }\n\n public void resetTileView(){\n if(this.tileView != null){\n worldProvider.logFirebaseEvent(WorldActivity.CustomFirebaseEvent.MAPFRAGMENT_RESET);\n\n updateMarkerFilter();\n\n tileView.getDetailLevelManager().setLevelType(worldProvider.getMapType());\n\n invalidateTileView();\n }\n }\n\n public void invalidateTileView(){\n MapType redo = worldProvider.getMapType();\n DetailLevelManager manager = tileView.getDetailLevelManager();\n //just swap mapType twice; it is not rendered, but it invalidates all tiles.\n manager.setLevelType(MapType.CHESS);\n manager.setLevelType(redo);\n //all tiles will now reload as soon as the tileView is drawn (user scrolls -> redraw)\n }\n\n\n\n /**\n * This is a convenience method to scrollToAndCenter after layout (which won't happen if called directly in onCreate\n * see https://github.com/moagrius/TileView/wiki/FAQ\n */\n public void frameTo( final double worldX, final double worldZ ) {\n this.tileView.post(new Runnable() {\n @Override\n public void run() {\n Dimension dimension = worldProvider.getDimension();\n if(tileView != null) tileView.scrollToAndCenter(\n dimension.dimensionScale * worldX / (double) MCTileProvider.HALF_WORLDSIZE,\n dimension.dimensionScale * worldZ / (double) MCTileProvider.HALF_WORLDSIZE);\n }\n });\n }\n\n\n}", "public enum MapType implements DetailLevelManager.LevelType {\n\n //shows that a chunk was present, but couldn't be renderer\n ERROR(new ChessPatternRenderer(0xFF2B0000, 0xFF580000)),\n\n //simple xor pattern renderer\n DEBUG(new DebugRenderer()),\n\n //simple chess pattern renderer\n CHESS(new ChessPatternRenderer(0xFF2B2B2B, 0xFF585858)),\n\n //just the surface of the world, with shading for height diff\n OVERWORLD_SATELLITE(new SatelliteRenderer()),\n\n //cave mapping\n OVERWORLD_CAVE(new CaveRenderer()),\n\n OVERWORLD_SLIME_CHUNK(new SlimeChunkRenderer()),\n\n //render skylight value of highest block\n OVERWORLD_HEIGHTMAP(new HeightmapRenderer()),\n\n //render biome id as biome-unique color\n OVERWORLD_BIOME(new BiomeRenderer()),\n\n //render the voliage colors\n OVERWORLD_GRASS(new GrassRenderer()),\n\n //render only the valuable blocks to mine (diamonds, emeralds, gold, etc.)\n OVERWORLD_XRAY(new XRayRenderer()),\n\n //block-light renderer: from light-sources like torches etc.\n OVERWORLD_BLOCK_LIGHT(new BlockLightRenderer()),\n\n NETHER(new NetherRenderer()),\n\n NETHER_XRAY(new XRayRenderer()),\n\n NETHER_BLOCK_LIGHT(new BlockLightRenderer()),\n\n END_SATELLITE(new SatelliteRenderer()),\n\n END_HEIGHTMAP(new HeightmapRenderer()),\n\n END_BLOCK_LIGHT(new BlockLightRenderer());\n\n //REDSTONE //TODO redstone circuit mapping\n //TRAFFIC //TODO traffic mapping (land = green, water = blue, gravel/stone/etc. = gray, rails = yellow)\n\n\n public final MapRenderer renderer;\n\n MapType(MapRenderer renderer){\n this.renderer = renderer;\n }\n\n}", "public class EditorFragment extends Fragment {\n\n /**\n *\n * TODO:\n *\n * - The onSomethingChanged listeners should start Asynchronous tasks\n * when directly modifying NBT.\n *\n * - This editor should be refactored into parts, it grew too large.\n *\n * - The functions lack documentation. Add it. Ask @protolambda for now...\n *\n */\n\n private EditableNBT nbt;\n\n public void setEditableNBT(EditableNBT nbt){\n this.nbt = nbt;\n }\n\n public static class ChainTag {\n\n public Tag parent, self;\n\n public ChainTag(Tag parent, Tag self){\n this.parent = parent;\n this.self = self;\n }\n }\n\n public static class RootNodeHolder extends TreeNode.BaseNodeViewHolder<EditableNBT>{\n\n\n public RootNodeHolder(Context context) {\n super(context);\n }\n\n @Override\n public View createNodeView(TreeNode node, EditableNBT value) {\n\n final LayoutInflater inflater = LayoutInflater.from(context);\n\n final View tagView = inflater.inflate(R.layout.tag_root_layout, null, false);\n TextView tagName = (TextView) tagView.findViewById(R.id.tag_name);\n tagName.setText(value.getRootTitle());\n\n return tagView;\n }\n\n @Override\n public void toggle(boolean active) {\n }\n\n @Override\n public int getContainerStyle() {\n return R.style.TreeNodeStyleCustomRoot;\n }\n }\n\n\n public static class NBTNodeHolder extends TreeNode.BaseNodeViewHolder<ChainTag> {\n\n private final EditableNBT nbt;\n\n public NBTNodeHolder(EditableNBT nbt, Context context) {\n super(context);\n this.nbt = nbt;\n }\n\n @SuppressLint(\"SetTextI18n\")\n @Override\n public View createNodeView(TreeNode node, final ChainTag chain) {\n\n if(chain == null) return null;\n Tag tag = chain.self;\n if(tag == null) return null;\n\n final LayoutInflater inflater = LayoutInflater.from(context);\n\n int layoutID;\n\n switch (tag.getType()) {\n case COMPOUND: {\n List<Tag> value = ((CompoundTag) tag).getValue();\n if (value != null) {\n for (Tag child : value) {\n node.addChild(new TreeNode(new ChainTag(tag, child)).setViewHolder(new NBTNodeHolder(nbt, context)));\n }\n }\n\n layoutID = R.layout.tag_compound_layout;\n break;\n }\n case LIST: {\n List<Tag> value = ((ListTag) tag).getValue();\n\n if (value != null) {\n for (Tag child : value) {\n node.addChild(new TreeNode(new ChainTag(tag, child)).setViewHolder(new NBTNodeHolder(nbt, context)));\n }\n }\n\n layoutID = R.layout.tag_list_layout;\n break;\n }\n case BYTE_ARRAY: {\n layoutID = R.layout.tag_default_layout;\n break;\n }\n case BYTE: {\n String name = tag.getName().toLowerCase();\n\n //TODO differentiate boolean tags from byte tags better\n if (name.startsWith(\"has\") || name.startsWith(\"is\")) {\n layoutID = R.layout.tag_boolean_layout;\n } else {\n layoutID = R.layout.tag_byte_layout;\n }\n break;\n }\n case SHORT:\n layoutID = R.layout.tag_short_layout;\n break;\n case INT:\n layoutID = R.layout.tag_int_layout;\n break;\n case LONG:\n layoutID = R.layout.tag_long_layout;\n break;\n case FLOAT:\n layoutID = R.layout.tag_float_layout;\n break;\n case DOUBLE:\n layoutID = R.layout.tag_double_layout;\n break;\n case STRING:\n layoutID = R.layout.tag_string_layout;\n break;\n default:\n layoutID = R.layout.tag_default_layout;\n break;\n }\n\n final View tagView = inflater.inflate(layoutID, null, false);\n TextView tagName = (TextView) tagView.findViewById(R.id.tag_name);\n tagName.setText(tag.getName());\n\n switch (layoutID){\n case R.layout.tag_boolean_layout: {\n final CheckBox checkBox = (CheckBox) tagView.findViewById(R.id.checkBox);\n final ByteTag byteTag = (ByteTag) tag;\n checkBox.setChecked(byteTag.getValue() == (byte) 1);\n checkBox.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {\n /**\n * Called when the checked state of a compound button has changed.\n *\n * @param buttonView The compound button view whose state has changed.\n * @param isChecked The new checked state of buttonView.\n */\n @Override\n public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {\n byteTag.setValue(isChecked ? (byte) 1 : (byte) 0);\n nbt.setModified();\n }\n });\n break;\n }\n case R.layout.tag_byte_layout: {\n final EditText editText = (EditText) tagView.findViewById(R.id.byteField);\n final ByteTag byteTag = (ByteTag) tag;\n //parse the byte as an unsigned byte\n editText.setText(\"\"+(((int) byteTag.getValue()) & 0xFF));\n editText.addTextChangedListener(new TextWatcher() {\n @Override\n public void beforeTextChanged(CharSequence s, int start, int count, int after) { }\n\n @Override\n public void onTextChanged(CharSequence s, int start, int before, int count) { }\n\n @Override\n public void afterTextChanged(Editable s) {\n String sValue = s.toString();\n try {\n int value = Integer.parseInt(sValue);\n if(value < 0 || value > 0xff)\n throw new NumberFormatException(\"No unsigned byte.\");\n byteTag.setValue((byte) value);\n nbt.setModified();\n } catch (NumberFormatException e){\n editText.setError(String.format(context.getString(R.string.x_is_invalid), sValue));\n }\n }\n });\n break;\n }\n case R.layout.tag_short_layout: {\n final EditText editText = (EditText) tagView.findViewById(R.id.shortField);\n final ShortTag shortTag = (ShortTag) tag;\n editText.setText(shortTag.getValue().toString());\n editText.addTextChangedListener(new TextWatcher() {\n @Override\n public void beforeTextChanged(CharSequence s, int start, int count, int after) { }\n\n @Override\n public void onTextChanged(CharSequence s, int start, int before, int count) { }\n\n @Override\n public void afterTextChanged(Editable s) {\n String sValue = s.toString();\n try {\n shortTag.setValue(Short.valueOf(sValue));\n nbt.setModified();\n } catch (NumberFormatException e){\n editText.setError(String.format(context.getString(R.string.x_is_invalid), sValue));\n }\n }\n });\n break;\n }\n case R.layout.tag_int_layout: {\n final EditText editText = (EditText) tagView.findViewById(R.id.intField);\n final IntTag intTag = (IntTag) tag;\n editText.setText(intTag.getValue().toString());\n editText.addTextChangedListener(new TextWatcher() {\n @Override\n public void beforeTextChanged(CharSequence s, int start, int count, int after) { }\n\n @Override\n public void onTextChanged(CharSequence s, int start, int before, int count) { }\n\n @Override\n public void afterTextChanged(Editable s) {\n String sValue = s.toString();\n try {\n intTag.setValue(Integer.valueOf(sValue));\n nbt.setModified();\n } catch (NumberFormatException e){\n editText.setError(String.format(context.getString(R.string.x_is_invalid), sValue));\n }\n }\n });\n break;\n }\n case R.layout.tag_long_layout: {\n final EditText editText = (EditText) tagView.findViewById(R.id.longField);\n final LongTag longTag = (LongTag) tag;\n editText.setText(longTag.getValue().toString());\n editText.addTextChangedListener(new TextWatcher() {\n @Override\n public void beforeTextChanged(CharSequence s, int start, int count, int after) { }\n\n @Override\n public void onTextChanged(CharSequence s, int start, int before, int count) { }\n\n @Override\n public void afterTextChanged(Editable s) {\n String sValue = s.toString();\n try {\n longTag.setValue(Long.valueOf(sValue));\n nbt.setModified();\n } catch (NumberFormatException e){\n editText.setError(String.format(context.getString(R.string.x_is_invalid), sValue));\n }\n }\n });\n break;\n }\n case R.layout.tag_float_layout: {\n final EditText editText = (EditText) tagView.findViewById(R.id.floatField);\n final FloatTag floatTag = (FloatTag) tag;\n editText.setText(floatTag.getValue().toString());\n editText.addTextChangedListener(new TextWatcher() {\n @Override\n public void beforeTextChanged(CharSequence s, int start, int count, int after) { }\n\n @Override\n public void onTextChanged(CharSequence s, int start, int before, int count) { }\n\n @Override\n public void afterTextChanged(Editable s) {\n String sValue = s.toString();\n try {\n floatTag.setValue(Float.valueOf(sValue));\n nbt.setModified();\n } catch (NumberFormatException e){\n editText.setError(String.format(context.getString(R.string.x_is_invalid), sValue));\n }\n }\n });\n break;\n }\n case R.layout.tag_double_layout: {\n final EditText editText = (EditText) tagView.findViewById(R.id.doubleField);\n final DoubleTag doubleTag = (DoubleTag) tag;\n editText.setText(doubleTag.getValue().toString());\n editText.addTextChangedListener(new TextWatcher() {\n @Override\n public void beforeTextChanged(CharSequence s, int start, int count, int after) { }\n\n @Override\n public void onTextChanged(CharSequence s, int start, int before, int count) { }\n\n @Override\n public void afterTextChanged(Editable s) {\n String sValue = s.toString();\n try {\n doubleTag.setValue(Double.valueOf(sValue));\n nbt.setModified();\n } catch (NumberFormatException e){\n editText.setError(String.format(context.getString(R.string.x_is_invalid), sValue));\n }\n }\n });\n break;\n }\n case R.layout.tag_string_layout: {\n final EditText editText = (EditText) tagView.findViewById(R.id.stringField);\n final StringTag stringTag = (StringTag) tag;\n editText.setText(stringTag.getValue());\n editText.addTextChangedListener(new TextWatcher() {\n @Override\n public void beforeTextChanged(CharSequence s, int start, int count, int after) { }\n\n @Override\n public void onTextChanged(CharSequence s, int start, int before, int count) { }\n\n @Override\n public void afterTextChanged(Editable s) {\n nbt.setModified();\n stringTag.setValue(s.toString());\n }\n });\n break;\n }\n default:\n break;\n\n }\n\n return tagView;\n }\n\n @Override\n public void toggle(boolean active) {\n }\n\n @Override\n public int getContainerStyle() {\n return R.style.TreeNodeStyleCustom;\n }\n\n }\n\n public enum NBTEditOption {\n\n CANCEL(R.string.edit_cancel),\n COPY(R.string.edit_copy),\n PASTE_OVERWRITE(R.string.edit_paste_overwrite),\n PASTE_SUBTAG(R.string.edit_paste_sub_tag),\n DELETE(R.string.edit_delete),\n RENAME(R.string.edit_rename),\n ADD_SUBTAG(R.string.edit_add_sub_tag);\n\n public final int stringId;\n\n NBTEditOption(int stringId){\n this.stringId = stringId;\n }\n }\n\n public String[] getNBTEditOptions(){\n NBTEditOption[] values = NBTEditOption.values();\n int len = values.length;\n String[] options = new String[len];\n for(int i = 0; i < len; i++){\n options[i] = getString(values[i].stringId);\n }\n return options;\n }\n\n public enum RootNBTEditOption {\n\n ADD_NBT_TAG(R.string.edit_root_add),\n PASTE_SUB_TAG(R.string.edit_root_paste_sub_tag),\n REMOVE_ALL_TAGS(R.string.edit_root_remove_all);\n\n public final int stringId;\n\n RootNBTEditOption(int stringId){\n this.stringId = stringId;\n }\n\n }\n\n public String[] getRootNBTEditOptions(){\n RootNBTEditOption[] values = RootNBTEditOption.values();\n int len = values.length;\n String[] options = new String[len];\n for(int i = 0; i < len; i++){\n options[i] = getString(values[i].stringId);\n }\n return options;\n }\n\n\n public static Tag clipboard;\n\n\n //returns true if there is a tag in content with a name equals to key.\n boolean checkKeyCollision(String key, List<Tag> content){\n if(content == null || content.isEmpty()) return false;\n if(key == null) key = \"\";\n String tagName;\n for(Tag tag : content) {\n tagName = tag.getName();\n if(tagName == null) tagName = \"\";\n if(tagName.equals(key)) {\n return true;\n }\n }\n return false;\n }\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n\n\n if(nbt == null){\n new Exception(\"No NBT data provided\").printStackTrace();\n getActivity().finish();\n\n return null;\n }\n\n final View rootView = inflater.inflate(R.layout.nbt_editor, container, false);\n\n // edit functionality\n // ================================\n\n TreeNode superRoot = TreeNode.root();\n TreeNode root = new TreeNode(nbt);\n superRoot.addChild(root);\n root.setExpanded(true);\n root.setSelectable(false);\n\n\n final Activity activity = getActivity();\n\n root.setViewHolder(new RootNodeHolder(activity));\n\n for(Tag tag : nbt.getTags()){\n root.addChild(new TreeNode(new ChainTag(null, tag)).setViewHolder(new NBTNodeHolder(nbt, activity)));\n }\n\n FrameLayout frame = (FrameLayout) rootView.findViewById(R.id.nbt_editor_frame);\n\n final AndroidTreeView tree = new AndroidTreeView(getActivity(), superRoot);\n tree.setUse2dScroll(true);\n\n final View treeView = tree.getView();\n\n treeView.setScrollContainer(true);\n\n tree.setDefaultNodeLongClickListener(new TreeNode.TreeNodeLongClickListener() {\n @Override\n public boolean onLongClick(final TreeNode node, final Object value) {\n\n Log.d(\"NBT editor: Long click!\");\n\n\n //root tag has nbt as value\n if(value instanceof EditableNBT){\n\n if(!nbt.enableRootModifications){\n Toast.makeText(activity, R.string.cannot_edit_root_NBT_tag, Toast.LENGTH_LONG).show();\n return true;\n }\n\n AlertDialog.Builder builder = new AlertDialog.Builder(activity);\n\n builder.setTitle(R.string.root_NBT_options)\n .setItems(getRootNBTEditOptions(), new DialogInterface.OnClickListener() {\n\n private void showMsg(int msg){\n Toast.makeText(activity, msg, Toast.LENGTH_LONG).show();\n }\n\n public void onClick(DialogInterface dialog, int which) {\n try {\n RootNBTEditOption option = RootNBTEditOption.values()[which];\n\n switch (option){\n case ADD_NBT_TAG:{\n final EditText nameText = new EditText(activity);\n nameText.setHint(R.string.hint_tag_name_here);\n\n //NBT tag type spinner\n final Spinner spinner = new Spinner(activity);\n ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<>(\n activity, android.R.layout.simple_spinner_item, NBTConstants.NBTType.editorOptions_asString);\n\n spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);\n spinner.setAdapter(spinnerArrayAdapter);\n\n //wrap editText and spinner in linear layout\n LinearLayout linearLayout = new LinearLayout(activity);\n linearLayout.setOrientation(LinearLayout.VERTICAL);\n linearLayout.setLayoutParams(\n new LinearLayout.LayoutParams(\n LinearLayout.LayoutParams.WRAP_CONTENT,\n LinearLayout.LayoutParams.WRAP_CONTENT,\n Gravity.BOTTOM));\n linearLayout.addView(nameText);\n linearLayout.addView(spinner);\n\n //wrap layout in alert\n AlertDialog.Builder alert = new AlertDialog.Builder(activity);\n alert.setTitle(R.string.create_nbt_tag);\n alert.setView(linearLayout);\n\n //alert can create a new tag\n alert.setPositiveButton(R.string.create, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n\n //new tag name\n Editable newNameEditable = nameText.getText();\n String newName = (newNameEditable == null || newNameEditable.toString().equals(\"\")) ? null : newNameEditable.toString();\n\n //new tag type\n int spinnerIndex = spinner.getSelectedItemPosition();\n NBTConstants.NBTType nbtType = NBTConstants.NBTType.editorOptions_asType[spinnerIndex];\n\n //create new tag\n Tag newTag = NBTConstants.NBTType.newInstance(newName, nbtType);\n\n //add tag to nbt\n nbt.addRootTag(newTag);\n tree.addNode(node, new TreeNode(new ChainTag(null, newTag)).setViewHolder(new NBTNodeHolder(nbt, activity)));\n\n nbt.setModified();\n\n }\n });\n\n //or alert is cancelled\n alert.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n Log.d(\"NBT tag creation cancelled\");\n }\n });\n\n alert.show();\n\n return;\n }\n case PASTE_SUB_TAG: {\n if(clipboard == null){\n showMsg(R.string.clipboard_is_empty);\n return;\n }\n\n Tag copy = clipboard.getDeepCopy();\n nbt.addRootTag(copy);\n tree.addNode(node, new TreeNode(new ChainTag(null, copy)).setViewHolder(new NBTNodeHolder(nbt, activity)));\n nbt.setModified();\n\n return;\n }\n case REMOVE_ALL_TAGS:{\n\n //wrap layout in alert\n AlertDialog.Builder alert = new AlertDialog.Builder(activity);\n alert.setTitle(R.string.confirm_delete_all_nbt_tags);\n\n //alert can create a new tag\n alert.setPositiveButton(R.string.delete_loud, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int whichButton) {\n\n List<TreeNode> children = new ArrayList<>(node.getChildren());\n //new tag name\n for(TreeNode child : children){\n tree.removeNode(child);\n Object childValue = child.getValue();\n if(childValue != null && childValue instanceof ChainTag)\n nbt.removeRootTag(((ChainTag) childValue).self);\n }\n nbt.setModified();\n }\n\n });\n\n //or alert is cancelled\n alert.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n Log.d(\"NBT tag creation cancelled\");\n }\n });\n\n alert.show();\n\n break;\n }\n default: {\n Log.d(\"User clicked unknown NBTEditOption! \"+option.name());\n }\n }\n } catch (Exception e){\n showMsg(R.string.failed_to_do_NBT_change);\n }\n }\n\n });\n builder.show();\n return true;\n\n\n } else if(value instanceof ChainTag){\n //other tags have a chain-tag as value\n\n\n AlertDialog.Builder builder = new AlertDialog.Builder(activity);\n\n builder.setTitle(R.string.nbt_tag_options)\n .setItems(getNBTEditOptions(), new DialogInterface.OnClickListener() {\n\n private void showMsg(int msg){\n Toast.makeText(activity, msg, Toast.LENGTH_LONG).show();\n }\n\n @SuppressWarnings(\"unchecked\")\n public void onClick(DialogInterface dialog, int which) {\n try{\n NBTEditOption editOption = NBTEditOption.values()[which];\n\n final Tag parent = ((ChainTag) value).parent;\n final Tag self = ((ChainTag) value).self;\n\n if(self == null) return;//WTF?\n\n if(editOption == null) return;//WTF?\n\n switch (editOption){\n case CANCEL: {\n return;\n }\n case COPY: {\n clipboard = self.getDeepCopy();\n return;\n }\n case PASTE_OVERWRITE: {\n if(clipboard == null){\n showMsg(R.string.clipboard_is_empty);\n return;\n }\n\n if(parent == null){\n //it is one of the children of the root node\n nbt.removeRootTag(self);\n Tag copy = clipboard.getDeepCopy();\n nbt.addRootTag(copy);\n tree.addNode(node.getParent(), new TreeNode(new ChainTag(null, copy)).setViewHolder(new NBTNodeHolder(nbt, activity)));\n tree.removeNode(node);\n nbt.setModified();\n return;\n } else {\n\n ArrayList<Tag> content;\n switch (parent.getType()) {\n case LIST: {\n content = ((ListTag) parent).getValue();\n break;\n }\n case COMPOUND: {\n content = ((CompoundTag) parent).getValue();\n if(checkKeyCollision(clipboard.getName(), content)){\n showMsg(R.string.clipboard_key_exists_in_compound);\n return;\n }\n break;\n }\n default: {\n showMsg(R.string.error_cannot_overwrite_tag_unknow_parent_type);\n return;\n }\n }\n if(content != null){\n content.remove(self);\n Tag copy = clipboard.getDeepCopy();\n content.add(copy);\n tree.addNode(node.getParent(), new TreeNode(new ChainTag(parent, copy)).setViewHolder(new NBTNodeHolder(nbt, activity)));\n tree.removeNode(node);\n nbt.setModified();\n return;\n }\n else showMsg(R.string.error_cannot_overwrite_in_empty_parent);\n return;\n }\n }\n case PASTE_SUBTAG: {\n if(clipboard == null){\n showMsg(R.string.clipboard_is_empty);\n return;\n }\n\n ArrayList<Tag> content;\n switch (self.getType()) {\n case LIST: {\n content = ((ListTag) self).getValue();\n break;\n }\n case COMPOUND: {\n content = ((CompoundTag) self).getValue();\n if(checkKeyCollision(clipboard.getName(), content)){\n showMsg(R.string.clipboard_key_exists_in_compound);\n return;\n }\n break;\n }\n default: {\n showMsg(R.string.error_cannot_paste_as_sub_unknown_parent_type);\n return;\n }\n }\n if(content == null){\n content = new ArrayList<>();\n self.setValue(content);\n }\n\n Tag copy = clipboard.getDeepCopy();\n content.add(copy);\n tree.addNode(node, new TreeNode(new ChainTag(self, copy)).setViewHolder(new NBTNodeHolder(nbt, activity)));\n nbt.setModified();\n\n return;\n }\n case DELETE: {\n if(parent == null){\n //it is one of the children of the root node\n tree.removeNode(node);\n nbt.removeRootTag(self);\n nbt.setModified();\n return;\n }\n\n ArrayList<Tag> content;\n switch (parent.getType()){\n case LIST:{\n content = ((ListTag) parent).getValue();\n break;\n }\n case COMPOUND:{\n content = ((CompoundTag) parent).getValue();\n break;\n }\n default:{\n showMsg(R.string.error_cannot_overwrite_tag_unknow_parent_type);\n return;\n }\n }\n if(content != null){\n content.remove(self);\n tree.removeNode(node);\n nbt.setModified();\n }\n else showMsg(R.string.error_cannot_remove_from_empty_list);\n return;\n }\n case RENAME: {\n final EditText edittext = new EditText(activity);\n edittext.setHint(R.string.hint_tag_name_here);\n\n AlertDialog.Builder alert = new AlertDialog.Builder(activity);\n alert.setTitle(R.string.rename_nbt_tag);\n\n alert.setView(edittext);\n\n alert.setPositiveButton(R.string.rename, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n Editable newNameEditable = edittext.getText();\n String newName = (newNameEditable == null || newNameEditable.toString().equals(\"\")) ? null : newNameEditable.toString();\n\n if(parent != null\n && parent instanceof CompoundTag\n && checkKeyCollision(newName, ((CompoundTag) parent).getValue())){\n showMsg(R.string.error_parent_already_contains_child_with_same_key);\n return;\n }\n\n self.setName(newName);\n\n //refresh view with new TreeNode\n tree.addNode(node.getParent(), new TreeNode(new ChainTag(parent, self)).setViewHolder(new NBTNodeHolder(nbt, activity)));\n tree.removeNode(node);\n\n nbt.setModified();\n }\n });\n\n alert.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n Log.d(\"Cancelled rename NBT tag\");\n }\n });\n\n alert.show();\n\n return;\n }\n case ADD_SUBTAG: {\n switch (self.getType()){\n case LIST:\n case COMPOUND:{\n final EditText nameText = new EditText(activity);\n nameText.setHint(R.string.hint_tag_name_here);\n\n //NBT tag type spinner\n final Spinner spinner = new Spinner(activity);\n ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<>(\n activity, android.R.layout.simple_spinner_item, NBTConstants.NBTType.editorOptions_asString);\n\n spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);\n spinner.setAdapter(spinnerArrayAdapter);\n\n //wrap editText and spinner in linear layout\n LinearLayout linearLayout = new LinearLayout(activity);\n linearLayout.setOrientation(LinearLayout.VERTICAL);\n linearLayout.setLayoutParams(\n new LinearLayout.LayoutParams(\n LinearLayout.LayoutParams.WRAP_CONTENT,\n LinearLayout.LayoutParams.WRAP_CONTENT,\n Gravity.BOTTOM));\n linearLayout.addView(nameText);\n linearLayout.addView(spinner);\n\n //wrap layout in alert\n AlertDialog.Builder alert = new AlertDialog.Builder(activity);\n alert.setTitle(R.string.create_nbt_tag);\n alert.setView(linearLayout);\n\n //alert can create a new tag\n alert.setPositiveButton(R.string.create, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n\n //new tag name\n Editable newNameEditable = nameText.getText();\n String newName = (newNameEditable == null || newNameEditable.toString().equals(\"\")) ? null : newNameEditable.toString();\n\n //new tag type\n int spinnerIndex = spinner.getSelectedItemPosition();\n NBTConstants.NBTType nbtType = NBTConstants.NBTType.editorOptions_asType[spinnerIndex];\n\n\n ArrayList<Tag> content;\n if(self instanceof CompoundTag) {\n\n content = ((CompoundTag) self).getValue();\n\n if(checkKeyCollision(newName, content)){\n showMsg(R.string.error_key_already_exists_in_compound);\n return;\n }\n }\n else if(self instanceof ListTag){\n content = ((ListTag) self).getValue();\n }\n else return;//WTF?\n\n if(content == null){\n content = new ArrayList<>();\n self.setValue(content);\n }\n\n //create new tag\n Tag newTag = NBTConstants.NBTType.newInstance(newName, nbtType);\n\n //add tag to nbt\n content.add(newTag);\n tree.addNode(node, new TreeNode(new ChainTag(self, newTag)).setViewHolder(new NBTNodeHolder(nbt, activity)));\n\n nbt.setModified();\n\n }\n });\n\n //or alert is cancelled\n alert.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n Log.d(\"NBT tag creation cancelled\");\n }\n });\n\n alert.show();\n\n return;\n\n }\n default:{\n showMsg(R.string.sub_tags_only_add_compound_list);\n return;\n }\n }\n }\n default: {\n Log.d(\"User clicked unknown NBTEditOption! \"+editOption.name());\n }\n\n }\n } catch (Exception e) {\n showMsg(R.string.failed_to_do_NBT_change);\n }\n\n }\n });\n\n builder.show();\n return true;\n }\n return false;\n }\n });\n frame.addView(treeView, 0);\n\n\n\n // save functionality\n // ================================\n\n FloatingActionButton fabSaveNBT = (FloatingActionButton) rootView.findViewById(R.id.fab_save_nbt);\n assert fabSaveNBT != null;\n fabSaveNBT.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(final View view) {\n if(!nbt.isModified()){\n Snackbar.make(view, R.string.no_data_changed_nothing_to_save, Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n } else {\n new AlertDialog.Builder(activity)\n .setTitle(R.string.nbt_editor)\n .setMessage(R.string.confirm_nbt_editor_changes)\n .setIcon(R.drawable.ic_action_save_b)\n .setPositiveButton(android.R.string.yes,\n new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n Snackbar.make(view, \"Saving NBT data...\", Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n if(nbt.save()){\n //nbt is not \"modified\" anymore, in respect to the new saved data\n nbt.modified = false;\n\n Snackbar.make(view, \"Saved NBT data!\", Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n ((WorldActivityInterface) activity).logFirebaseEvent(WorldActivity.CustomFirebaseEvent.NBT_EDITOR_SAVE);\n } else {\n Snackbar.make(view, \"Error: failed to save the NBT data.\", Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n }\n }})\n .setNegativeButton(android.R.string.no, null).show();\n }\n\n }\n });\n\n return rootView;\n }\n\n\n @Override\n public void onStart() {\n super.onStart();\n\n getActivity().setTitle(R.string.nbt_editor);\n\n Bundle bundle = new Bundle();\n bundle.putString(\"title\", nbt.getRootTitle());\n\n ((WorldActivityInterface) getActivity()).logFirebaseEvent(WorldActivity.CustomFirebaseEvent.NBT_EDITOR_OPEN, bundle);\n }\n\n @Override\n public void onResume() {\n super.onResume();\n\n ((WorldActivityInterface) getActivity()).showActionBar();\n\n }\n}", "public class CompoundTag extends Tag<ArrayList<Tag>> {\n\n private static final long serialVersionUID = 4540757946052775740L;\n\n public CompoundTag(String name, ArrayList<Tag> value) {\n super(name, value);\n }\n\n @Override\n public NBTConstants.NBTType getType() {\n return NBTConstants.NBTType.COMPOUND;\n }\n\n\n public Tag getChildTagByKey(String key){\n List<Tag> list = getValue();\n if(list == null) return null;\n for(Tag tag : list){\n if(key.equals(tag.getName())) return tag;\n }\n return null;\n }\n\n public String toString(){\n String name = getName();\n String type = getType().name();\n ArrayList<Tag> value = getValue();\n StringBuilder bldr = new StringBuilder();\n bldr.append(type == null ? \"?\" : (\"TAG_\" + type))\n .append(name == null ? \"(?)\" : (\"(\" + name + \")\"));\n\n if(value != null) {\n bldr.append(\": \")\n .append(value.size())\n .append(\" entries\\n{\\n\");\n for (Tag entry : value) {\n //pad every line of the value\n bldr.append(\" \")\n .append(entry.toString().replaceAll(\"\\n\", \"\\n \"))\n .append(\"\\n\");\n }\n bldr.append(\"}\");\n\n } else bldr.append(\":?\");\n\n return bldr.toString();\n }\n\n @Override\n public CompoundTag getDeepCopy() {\n if(value != null){\n ArrayList<Tag> copy = new ArrayList<>();\n for(Tag tag : value){\n copy.add(tag.getDeepCopy());\n }\n return new CompoundTag(name, copy);\n } else return new CompoundTag(name, null);\n }\n\n}" ]
import android.app.AlertDialog; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.Context; import android.content.DialogInterface; import android.os.Build; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v7.app.ActionBar; import android.text.Editable; import android.view.View; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import com.google.firebase.analytics.FirebaseAnalytics; import com.protolambda.blocktopograph.map.Dimension; import com.protolambda.blocktopograph.map.marker.AbstractMarker; import com.protolambda.blocktopograph.nbt.convert.NBTConstants; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.protolambda.blocktopograph.chunk.NBTChunkData; import com.protolambda.blocktopograph.map.MapFragment; import com.protolambda.blocktopograph.map.renderer.MapType; import com.protolambda.blocktopograph.nbt.EditableNBT; import com.protolambda.blocktopograph.nbt.EditorFragment; import com.protolambda.blocktopograph.nbt.convert.DataConverter; import com.protolambda.blocktopograph.nbt.tags.CompoundTag; import com.protolambda.blocktopograph.nbt.tags.Tag;
public void openMultiplayerEditor(){ //takes some time to find all players... // TODO make more responsive // TODO maybe cache player keys for responsiveness? // Or messes this too much with the first perception of present players? final String[] players = getWorld().getWorldData().getPlayers(); final View content = WorldActivity.this.findViewById(R.id.world_content); if(players.length == 0){ if(content != null) Snackbar.make(content, R.string.no_multiplayer_data_found, Snackbar.LENGTH_LONG) .setAction("Action", null).show(); return; } //spinner (drop-out list) of players; // just the database keys (loading each name from NBT could take an even longer time!) final Spinner spinner = new Spinner(this); ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, players); spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(spinnerArrayAdapter); //wrap layout in alert new AlertDialog.Builder(this) .setTitle(R.string.select_player) .setView(spinner) .setPositiveButton(R.string.open_nbt, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { //new tag type int spinnerIndex = spinner.getSelectedItemPosition(); String playerKey = players[spinnerIndex]; try { final EditableNBT editableNBT = WorldActivity.this .openEditableNbtDbEntry(playerKey); changeContentFragment(new OpenFragmentCallback() { @Override public void onOpen() { try { openNBTEditor(editableNBT); } catch (Exception e){ new AlertDialog.Builder(WorldActivity.this) .setMessage(e.getMessage()) .setCancelable(false) .setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { changeContentFragment( new OpenFragmentCallback() { @Override public void onOpen() { openWorldMap(); } }); } }).show(); } } }); } catch (Exception e){ e.printStackTrace(); Log.d("Failed to open player entry in DB. key: "+playerKey); if(content != null) Snackbar.make(content, String.format(getString(R.string.failed_read_player_from_db_with_key_x), playerKey), Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } } }) //or alert is cancelled .setNegativeButton(android.R.string.cancel, null) .show(); } public void openPlayerEditor(){ changeContentFragment(new OpenFragmentCallback() { @Override public void onOpen() { try { openNBTEditor(getEditablePlayer()); } catch (Exception e){ new AlertDialog.Builder(WorldActivity.this) .setMessage(e.getMessage()) .setCancelable(false) .setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { changeContentFragment(new OpenFragmentCallback() { @Override public void onOpen() { openWorldMap(); } }); } }).show(); } } }); } /** Opens an editableNBT for just the subTag if it is not null. Opens the whole level.dat if subTag is null. **/ public EditableNBT openEditableNbtLevel(String subTagName){ //make a copy first, the user might not want to save changed tags.
final CompoundTag workCopy = world.level.getDeepCopy();
7
otto-de/jlineup
core/src/test/java/de/otto/jlineup/report/HTMLReportWriterTest.java
[ "@JsonDeserialize(builder = ScreenshotContext.Builder.class)\npublic final class ScreenshotContext {\n public final String url;\n public final String urlSubPath;\n public final DeviceConfig deviceConfig;\n public final List<Cookie> cookies;\n @JsonIgnore\n public final Step step;\n @JsonIgnore\n public final UrlConfig urlConfig;\n @JsonIgnore\n final String fullPathOfReportDir;\n @JsonIgnore\n final boolean dontShareBrowser;\n @JsonIgnore\n final String originalUrl;\n\n ScreenshotContext(String url, String urlSubPath, DeviceConfig deviceConfig, List<Cookie> cookies, Step step, UrlConfig urlConfig, String fullPathOfReportDir, boolean dontShareBrowser, String originalUrl) {\n this.url = url;\n this.urlSubPath = urlSubPath;\n this.deviceConfig = deviceConfig;\n this.cookies = cookies;\n this.step = step;\n this.urlConfig = urlConfig;\n this.fullPathOfReportDir = fullPathOfReportDir;\n this.dontShareBrowser = dontShareBrowser;\n this.originalUrl = originalUrl;\n }\n\n //Used by Jackson\n private ScreenshotContext() {\n this(screenshotContextBuilder());\n }\n\n private ScreenshotContext(Builder builder) {\n url = builder.url;\n urlSubPath = builder.urlSubPath;\n deviceConfig = builder.deviceConfig;\n cookies = builder.cookies;\n step = builder.step;\n urlConfig = builder.urlConfig;\n fullPathOfReportDir = builder.fullPathOfReportDir;\n dontShareBrowser = builder.dontShareBrowser;\n originalUrl = builder.originalUrl;\n }\n\n //Used in Tests only\n public static ScreenshotContext of(String url, String path, DeviceConfig deviceConfig, Step step, UrlConfig urlConfig, List<Cookie> cookies, String originalUrl) {\n return new ScreenshotContext(url, path, deviceConfig, cookies, step, urlConfig, null, false, originalUrl);\n }\n\n //Used in Tests only\n public static ScreenshotContext of(String url, String path, DeviceConfig deviceConfig, Step step, UrlConfig urlConfig, List<Cookie> cookies) {\n return new ScreenshotContext(url, path, deviceConfig, cookies, step, urlConfig, null, false, url);\n }\n\n //Used in Tests only\n public static ScreenshotContext of(String url, String path, DeviceConfig deviceConfig, Step step, UrlConfig urlConfig) {\n return new ScreenshotContext(url, path, deviceConfig, urlConfig.cookies, step, urlConfig, null, false, url);\n }\n\n public static Builder screenshotContextBuilder() {\n return new Builder();\n }\n\n public static Builder copyOfBuilder(ScreenshotContext copy) {\n Builder builder = new Builder();\n builder.url = copy.url;\n builder.urlSubPath = copy.urlSubPath;\n builder.deviceConfig = copy.deviceConfig;\n builder.cookies = copy.cookies;\n builder.step = copy.step;\n builder.urlConfig = copy.urlConfig;\n builder.fullPathOfReportDir = copy.fullPathOfReportDir;\n builder.dontShareBrowser = copy.dontShareBrowser;\n builder.originalUrl = copy.originalUrl;\n return builder;\n }\n\n /*\n *\n *\n *\n * BEGIN of getters block\n *\n * For GraalVM (JSON is empty if no getters are here)\n *\n *\n *\n */\n\n public String getUrl() {\n return url;\n }\n\n public String getUrlSubPath() {\n return urlSubPath;\n }\n\n public DeviceConfig getDeviceConfig() {\n return deviceConfig;\n }\n\n public List<Cookie> getCookies() {\n return cookies;\n }\n\n /*\n *\n *\n *\n * END of getters block\n *\n * For GraalVM (JSON is empty if no getters are here)\n *\n *\n *\n */\n\n public int contextHash() {\n return Objects.hash(originalUrl, urlSubPath, deviceConfig, cookies);\n }\n\n public boolean equalsIgnoreStep(ScreenshotContext that) {\n if (this == that) return true;\n if (that == null) return false;\n return Objects.equals(url, that.url) &&\n Objects.equals(urlSubPath, that.urlSubPath) &&\n Objects.equals(deviceConfig, that.deviceConfig) &&\n Objects.equals(urlConfig, that.urlConfig) &&\n Objects.equals(fullPathOfReportDir, that.fullPathOfReportDir) &&\n Objects.equals(originalUrl, that.originalUrl);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n ScreenshotContext that = (ScreenshotContext) o;\n return dontShareBrowser == that.dontShareBrowser && Objects.equals(url, that.url) && Objects.equals(urlSubPath, that.urlSubPath) && Objects.equals(deviceConfig, that.deviceConfig) && Objects.equals(cookies, that.cookies) && step == that.step && Objects.equals(urlConfig, that.urlConfig) && Objects.equals(fullPathOfReportDir, that.fullPathOfReportDir) && Objects.equals(originalUrl, that.originalUrl);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(url, urlSubPath, deviceConfig, cookies, step, urlConfig, fullPathOfReportDir, dontShareBrowser, originalUrl);\n }\n\n @Override\n public String toString() {\n return \"ScreenshotContext{\" +\n \"url='\" + url + '\\'' +\n \", urlSubPath='\" + urlSubPath + '\\'' +\n \", deviceConfig=\" + deviceConfig +\n \", cookies=\" + cookies +\n \", step=\" + step +\n \", urlConfig=\" + urlConfig +\n \", fullPathOfReportDir='\" + fullPathOfReportDir + '\\'' +\n \", dontShareBrowser=\" + dontShareBrowser +\n \", originalUrl='\" + originalUrl + '\\'' +\n '}';\n }\n\n public static final class Builder {\n private String url;\n private String urlSubPath;\n private DeviceConfig deviceConfig;\n private List<Cookie> cookies = Collections.emptyList();\n private Step step;\n private UrlConfig urlConfig;\n private String fullPathOfReportDir;\n private boolean dontShareBrowser;\n private String originalUrl;\n\n private Builder() {\n }\n\n public Builder withUrl(String val) {\n url = val;\n return this;\n }\n\n public Builder withUrlSubPath(String val) {\n urlSubPath = val;\n return this;\n }\n\n public Builder withDeviceConfig(DeviceConfig val) {\n deviceConfig = val;\n return this;\n }\n\n public Builder withCookies(List<Cookie> val) {\n cookies = val;\n return this;\n }\n\n public Builder withStep(Step val) {\n step = val;\n return this;\n }\n\n public Builder withUrlConfig(UrlConfig val) {\n urlConfig = val;\n return this;\n }\n\n public Builder withFullPathOfReportDir(String val) {\n fullPathOfReportDir = val;\n return this;\n }\n\n public Builder withDontShareBrowser(boolean val) {\n dontShareBrowser = val;\n return this;\n }\n\n public Builder withOriginalUrl(String val) {\n originalUrl = val;\n return this;\n }\n\n public ScreenshotContext build() {\n return new ScreenshotContext(this);\n }\n }\n}", "@JsonDeserialize(builder = DeviceConfig.Builder.class)\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\n//@JsonNaming(PropertyNamingStrategy.KebabCaseStrategy.class)\npublic class DeviceConfig {\n\n static final String DESKTOP_DEVICE_NAME = \"DESKTOP\";\n static final String MOBILE_DEVICE_NAME = \"MOBILE\";\n private static final String DEFAULT_DEVICE_NAME = DESKTOP_DEVICE_NAME;\n private static final String DEFAULT_USER_AGENT = null;\n private static final boolean DEFAULT_TOUCH_OPTION = false;\n\n //\n // See http://chromedriver.chromium.org/mobile-emulation for information about Chrome mobile emulation\n //\n\n public final int width;\n\n public final int height;\n\n @JsonAlias(\"pixelRatio\")\n public final float pixelRatio;\n\n @JsonAlias(\"deviceName\")\n public final String deviceName;\n\n @JsonAlias(\"userAgent\")\n public final String userAgent;\n\n public final boolean touch;\n\n public DeviceConfig() {\n deviceName = DEFAULT_DEVICE_NAME;\n width = DEFAULT_WINDOW_WIDTH;\n height = DEFAULT_WINDOW_HEIGHT;\n pixelRatio = DEFAULT_PIXEL_RATIO;\n touch = DEFAULT_TOUCH_OPTION;\n userAgent = DEFAULT_USER_AGENT;\n }\n\n private DeviceConfig(int width, int height, float pixelRatio, String deviceName, String userAgent, boolean touch) {\n this.width = width;\n this.height = height;\n this.pixelRatio = pixelRatio;\n this.deviceName = deviceName;\n this.userAgent = userAgent;\n this.touch = touch;\n }\n\n private DeviceConfig(Builder builder) {\n width = builder.width;\n height = builder.height;\n pixelRatio = builder.pixelRatio;\n deviceName = builder.deviceName;\n userAgent = builder.userAgent;\n touch = builder.touch;\n }\n\n public static DeviceConfig deviceConfig(int width, int height) {\n return DeviceConfig.deviceConfigBuilder().withWidth(width).withHeight(height).build();\n }\n\n /*\n *\n *\n *\n * BEGIN of getters block\n *\n * For GraalVM (JSON is empty if no getters are here)\n *\n *\n *\n */\n\n public int getWidth() {\n return width;\n }\n\n public int getHeight() {\n return height;\n }\n\n public float getPixelRatio() {\n return pixelRatio;\n }\n\n public String getDeviceName() {\n return deviceName;\n }\n\n public String getUserAgent() {\n return userAgent;\n }\n////@JsonNaming(PropertyNamingStrategy.KebabCaseStrategy.class)\n public boolean isTouch() {\n return touch;\n }\n\n /*\n *\n *\n *\n * END of getters block\n *\n * For GraalVM (JSON is empty if no getters are here)\n *\n *\n *\n */\n\n public static Builder deviceConfigBuilder() {\n return new Builder();\n }\n\n @JsonIgnore\n public boolean isDesktop() {\n return DESKTOP_DEVICE_NAME.equalsIgnoreCase(deviceName.trim());\n }\n\n @JsonIgnore\n public boolean isMobile() {\n return !DESKTOP_DEVICE_NAME.equalsIgnoreCase(deviceName.trim());\n }\n\n @JsonIgnore\n public boolean isGenericMobile() {\n return MOBILE_DEVICE_NAME.equalsIgnoreCase(deviceName.trim());\n }\n\n public static final class Builder {\n private int width = DEFAULT_WINDOW_WIDTH;\n private int height = DEFAULT_WINDOW_HEIGHT;\n private float pixelRatio = DEFAULT_PIXEL_RATIO;\n private String deviceName = DEFAULT_DEVICE_NAME;\n private String userAgent = DEFAULT_USER_AGENT;\n private boolean touch = DEFAULT_TOUCH_OPTION;\n\n private Builder() {\n }\n\n public Builder withWidth(int val) {\n width = val;\n return this;\n }\n\n public Builder withHeight(int val) {\n height = val;\n return this;\n }\n\n @JsonAlias(\"pixelRatio\")\n public Builder withPixelRatio(float val) {\n pixelRatio = val;\n return this;\n }\n\n @JsonAlias(\"deviceName\")\n public Builder withDeviceName(String val) {\n deviceName = val;\n return this;\n }\n\n @JsonAlias(\"userAgent\")\n public Builder withUserAgent(String val) {\n userAgent = val;\n return this;\n }\n\n public Builder withTouch(boolean val) {\n touch = val;\n return this;\n }\n\n public DeviceConfig build() {\n return new DeviceConfig(this);\n }\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n DeviceConfig that = (DeviceConfig) o;\n return width == that.width &&\n height == that.height &&\n Float.compare(that.pixelRatio, pixelRatio) == 0 &&\n touch == that.touch &&\n Objects.equals(deviceName, that.deviceName) &&\n Objects.equals(userAgent, that.userAgent);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(width, height, pixelRatio, deviceName, userAgent, touch);\n }\n\n @Override\n public String toString() {\n return \"DeviceConfig{\" +\n \"width=\" + width +\n \", height=\" + height +\n \", pixelRatio=\" + pixelRatio +\n \", deviceName='\" + deviceName + '\\'' +\n \", userAgent='\" + userAgent + '\\'' +\n \", touch=\" + touch +\n '}';\n }\n}", "@JsonIgnoreProperties(ignoreUnknown = true)\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\n@JsonDeserialize(builder = JobConfig.Builder.class)\n//@JsonNaming(PropertyNamingStrategy.KebabCaseStrategy.class)\npublic final class JobConfig {\n\n static final String LINEUP_CONFIG_DEFAULT_PATH = \"./lineup.json\";\n static final String EXAMPLE_URL = \"https://www.example.com\";\n\n public static final int DEFAULT_WARMUP_BROWSER_CACHE_TIME = 0;\n public static final int DEFAULT_REPORT_FORMAT = 2;\n\n static final Browser.Type DEFAULT_BROWSER = Browser.Type.CHROME_HEADLESS;\n static final float DEFAULT_MAX_DIFF = 0;\n static final int DEFAULT_WINDOW_WIDTH = 800;\n public static final int DEFAULT_WINDOW_HEIGHT = 800;\n static final float DEFAULT_PIXEL_RATIO = 1.0f;\n static final float DEFAULT_GLOBAL_WAIT_AFTER_PAGE_LOAD = 0f;\n public static final String DEFAULT_PATH = \"\";\n static final int DEFAULT_MAX_SCROLL_HEIGHT = 100000;\n static final float DEFAULT_WAIT_AFTER_PAGE_LOAD = 0;\n static final float DEFAULT_WAIT_AFTER_SCROLL = 0;\n static final float DEFAULT_WAIT_FOR_NO_ANIMATION_AFTER_SCROLL = 0;\n static final float DEFAULT_WAIT_FOR_FONTS_TIME = 0;\n public static final float DEFAULT_MAX_COLOR_DISTANCE = 2.3f;\n static final int DEFAULT_THREADS = 0; // '0' means not set which is transformed to '1' when creating the threadpool\n static final int DEFAULT_PAGELOAD_TIMEOUT = 120;\n static final int DEFAULT_SCREENSHOT_RETRIES = 0;\n static final int DEFAULT_GLOBAL_TIMEOUT = 600;\n public static final float DEFAULT_WAIT_FOR_SELECTORS_TIMEOUT = 10.0f;\n\n public final Map<String, UrlConfig> urls;\n public final Browser.Type browser;\n\n @JsonInclude(Include.NON_DEFAULT)\n public final String name;\n\n @JsonProperty(\"wait-after-page-load\")\n @JsonAlias({\"async-wait\"})\n public final Float globalWaitAfterPageLoad;\n public final int pageLoadTimeout;\n public final Integer windowHeight;\n @JsonInclude(value = Include.CUSTOM, valueFilter = ReportFormatFilter.class)\n public final Integer reportFormat;\n @JsonInclude(Include.NON_DEFAULT)\n public final int screenshotRetries;\n @JsonInclude(Include.NON_DEFAULT)\n public final int threads;\n @JsonProperty(\"timeout\")\n public final int globalTimeout;\n public final boolean debug;\n @JsonInclude(Include.NON_DEFAULT)\n public final boolean logToFile;\n public final boolean checkForErrorsInLog;\n @JsonInclude(value = Include.CUSTOM, valueFilter = HttpCheckFilter.class)\n public final HttpCheckConfig httpCheck;\n\n public JobConfig() {\n this(jobConfigBuilder());\n }\n\n private JobConfig(Builder builder) {\n urls = builder.urls;\n browser = builder.browser;\n globalWaitAfterPageLoad = builder.globalWaitAfterPageLoad;\n pageLoadTimeout = builder.pageLoadTimeout;\n windowHeight = builder.windowHeight;\n threads = builder.threads;\n screenshotRetries = builder.screenshotRetries;\n reportFormat = builder.reportFormat;\n globalTimeout = builder.globalTimeout;\n debug = builder.debug;\n logToFile = builder.logToFile;\n checkForErrorsInLog = builder.checkForErrorsInLog;\n httpCheck = builder.httpCheck;\n name = builder.name;\n }\n\n public static String prettyPrint(JobConfig jobConfig) {\n return JacksonWrapper.serializeObject(jobConfig);\n }\n\n public static String prettyPrintWithAllFields(JobConfig jobConfig) {\n ObjectMapper objectMapper = JsonMapper.builder()\n .configure(JsonReadFeature.ALLOW_TRAILING_COMMA, true)\n .configure(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS, true)\n .configure(ACCEPT_CASE_INSENSITIVE_ENUMS, true)\n .configure(ALLOW_COMMENTS, true)\n .configure(INDENT_OUTPUT, true)\n .build();\n objectMapper.setPropertyNamingStrategy(PropertyNamingStrategies.KEBAB_CASE);\n objectMapper.addMixIn(JobConfig.class, JobConfigMixIn.class);\n objectMapper.addMixIn(UrlConfig.class, UrlConfigMixIn.class);\n try {\n return objectMapper.writeValueAsString(jobConfig);\n } catch (JsonProcessingException e) {\n throw new RuntimeException(\"There is a problem while writing the \" + jobConfig.getClass().getCanonicalName() + \" with Jackson.\", e);\n }\n }\n\n /*\n *\n *\n *\n * BEGIN of getters block\n *\n * For GraalVM (JSON is empty if no getters are here)\n *\n *\n *\n */\n\n public Map<String, UrlConfig> getUrls() {\n return urls;\n }\n\n public Browser.Type getBrowser() {\n return browser;\n }\n\n public String getName() {\n return name;\n }\n\n public Float getGlobalWaitAfterPageLoad() {\n return globalWaitAfterPageLoad;\n }\n\n public int getPageLoadTimeout() {\n return pageLoadTimeout;\n }\n\n public Integer getWindowHeight() {\n return windowHeight;\n }\n\n public Integer getReportFormat() {\n return reportFormat;\n }\n\n public int getScreenshotRetries() {\n return screenshotRetries;\n }\n\n public int getThreads() {\n return threads;\n }\n\n public int getGlobalTimeout() {\n return globalTimeout;\n }\n\n public boolean isDebug() {\n return debug;\n }\n\n public boolean isLogToFile() {\n return logToFile;\n }\n\n public boolean isCheckForErrorsInLog() {\n return checkForErrorsInLog;\n }\n\n public HttpCheckConfig getHttpCheck() {\n return httpCheck;\n }\n\n /*\n *\n *\n *\n * END of getters block\n *\n * For GraalVM (JSON is empty if no getters are here)\n *\n *\n *\n */\n\n public static Builder copyOfBuilder(JobConfig jobConfig) {\n return jobConfigBuilder()\n .withName(jobConfig.name)\n .withUrls(jobConfig.urls)\n .withHttpCheck(jobConfig.httpCheck)\n .withBrowser(jobConfig.browser)\n .withGlobalWaitAfterPageLoad(jobConfig.globalWaitAfterPageLoad)\n .withPageLoadTimeout(jobConfig.pageLoadTimeout)\n .withWindowHeight(jobConfig.windowHeight)\n .withThreads(jobConfig.threads)\n .withScreenshotRetries(jobConfig.screenshotRetries)\n .withReportFormat(jobConfig.reportFormat)\n .withGlobalTimeout(jobConfig.globalTimeout)\n .withDebug(jobConfig.debug)\n .withLogToFile(jobConfig.logToFile)\n .withCheckForErrorsInLog(jobConfig.checkForErrorsInLog);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n JobConfig jobConfig = (JobConfig) o;\n return pageLoadTimeout == jobConfig.pageLoadTimeout &&\n screenshotRetries == jobConfig.screenshotRetries &&\n threads == jobConfig.threads &&\n globalTimeout == jobConfig.globalTimeout &&\n debug == jobConfig.debug &&\n logToFile == jobConfig.logToFile &&\n checkForErrorsInLog == jobConfig.checkForErrorsInLog &&\n Objects.equals(urls, jobConfig.urls) &&\n browser == jobConfig.browser &&\n Objects.equals(name, jobConfig.name) &&\n Objects.equals(globalWaitAfterPageLoad, jobConfig.globalWaitAfterPageLoad) &&\n Objects.equals(windowHeight, jobConfig.windowHeight) &&\n Objects.equals(reportFormat, jobConfig.reportFormat) &&\n Objects.equals(httpCheck, jobConfig.httpCheck);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(urls, browser, name, globalWaitAfterPageLoad, pageLoadTimeout, windowHeight, reportFormat, screenshotRetries, threads, globalTimeout, debug, logToFile, checkForErrorsInLog, httpCheck);\n }\n\n @Override\n public String toString() {\n return \"JobConfig{\" +\n \"urls=\" + urls +\n \", browser=\" + browser +\n \", name='\" + name + '\\'' +\n \", globalWaitAfterPageLoad=\" + globalWaitAfterPageLoad +\n \", pageLoadTimeout=\" + pageLoadTimeout +\n \", windowHeight=\" + windowHeight +\n \", reportFormat=\" + reportFormat +\n \", screenshotRetries=\" + screenshotRetries +\n \", threads=\" + threads +\n \", globalTimeout=\" + globalTimeout +\n \", debug=\" + debug +\n \", logToFile=\" + logToFile +\n \", checkForErrorsInLog=\" + checkForErrorsInLog +\n \", httpCheck=\" + httpCheck +\n '}';\n }\n\n public static JobConfig defaultConfig() {\n return defaultConfig(EXAMPLE_URL);\n }\n\n public static JobConfig defaultConfig(String url) {\n return jobConfigBuilder().withName(\"Default\").withUrls(ImmutableMap.of(url, urlConfigBuilder().build())).build();\n }\n\n public static Builder jobConfigBuilder() {\n return new Builder();\n }\n\n public static JobConfig exampleConfig() {\n return exampleConfigBuilder().build();\n }\n\n public static JobConfig.Builder exampleConfigBuilder() {\n return jobConfigBuilder()\n .withName(\"Example\")\n .withCheckForErrorsInLog(true)\n .withUrls(ImmutableMap.of(\"http://www.example.com\",\n\n urlConfigBuilder()\n .withPaths(ImmutableList.of(\"/\"))\n .withCookies(ImmutableList.of(\n new Cookie(\"exampleCookieName\", \"exampleValue\", \"www.example.com\", \"/\", new Date(1000L), false, false)\n ))\n .withEnvMapping(ImmutableMap.of(\"live\", \"www\"))\n .withLocalStorage(ImmutableMap.of(\"exampleLocalStorageKey\", \"value\"))\n .withSessionStorage(ImmutableMap.of(\"exampleSessionStorageKey\", \"value\"))\n .withDevices(ImmutableList.of(deviceConfig(850,600), deviceConfig(1000, 850), deviceConfig(1200, 1000)))\n .withJavaScript(\"console.log('This is JavaScript!')\")\n .withHttpCheck(new HttpCheckConfig(true))\n .withStrictColorComparison(false)\n .withRemoveSelectors(ImmutableSet.of(\"#removeNodeWithThisId\", \".removeNodesWithThisClass\"))\n .withWaitForSelectors(ImmutableSet.of(\"h1\"))\n .withFailIfSelectorsNotFound(false)\n .build())\n );\n }\n\n\n public static JobConfig readConfig(final String workingDir, final String configFileName) throws IOException {\n List<String> searchPaths = new ArrayList<>();\n Path configFilePath = Paths.get(workingDir + \"/\" + configFileName);\n searchPaths.add(configFilePath.toString());\n if (!Files.exists(configFilePath)) {\n configFilePath = Paths.get(configFileName);\n searchPaths.add(configFilePath.toString());\n if (!Files.exists(configFilePath)) {\n configFilePath = Paths.get(LINEUP_CONFIG_DEFAULT_PATH);\n searchPaths.add(configFilePath.toString());\n if (!Files.exists(configFilePath)) {\n String cwd = Paths.get(\".\").toAbsolutePath().normalize().toString();\n throw new FileNotFoundException(\"JobConfig file not found. Search locations were: \" + Arrays.toString(searchPaths.toArray()) + \" - working dir: \" + cwd);\n }\n }\n }\n BufferedReader br = new BufferedReader(new FileReader(configFilePath.toString()));\n return JacksonWrapper.deserializeConfig(br);\n }\n\n public static final class Builder {\n private String name = null;\n private Map<String, UrlConfig> urls = null;\n private Browser.Type browser = DEFAULT_BROWSER;\n private float globalWaitAfterPageLoad = DEFAULT_GLOBAL_WAIT_AFTER_PAGE_LOAD;\n private int pageLoadTimeout = DEFAULT_PAGELOAD_TIMEOUT;\n private int windowHeight = DEFAULT_WINDOW_HEIGHT;\n private int reportFormat = DEFAULT_REPORT_FORMAT;\n private int screenshotRetries = DEFAULT_SCREENSHOT_RETRIES;\n private int threads = DEFAULT_THREADS;\n private int globalTimeout = DEFAULT_GLOBAL_TIMEOUT;\n private boolean debug = false;\n private boolean logToFile = false;\n private boolean checkForErrorsInLog = false;\n private HttpCheckConfig httpCheck = new HttpCheckConfig();\n\n private Builder() {\n }\n\n public Builder withName(String val) {\n name = val;\n return this;\n }\n\n public Builder withUrls(Map<String, UrlConfig> val) {\n urls = val;\n return this;\n }\n\n public Builder withBrowser(Browser.Type val) {\n browser = val;\n return this;\n }\n\n @JsonProperty(\"wait-after-page-load\")\n @JsonAlias({\"async-wait\"})\n public Builder withGlobalWaitAfterPageLoad(float val) {\n globalWaitAfterPageLoad = val;\n return this;\n }\n\n public Builder withPageLoadTimeout(int val) {\n pageLoadTimeout = val;\n return this;\n }\n\n public Builder withWindowHeight(int val) {\n windowHeight = val;\n return this;\n }\n\n @JsonInclude(value = Include.CUSTOM, valueFilter = ReportFormatFilter.class)\n public Builder withReportFormat(int val) {\n reportFormat = val;\n return this;\n }\n\n public Builder withScreenshotRetries(int val) {\n screenshotRetries = val;\n return this;\n }\n\n public Builder withThreads(int val) {\n threads = val;\n return this;\n }\n\n public Builder withDebug(boolean val) {\n debug = val;\n return this;\n }\n\n public Builder withLogToFile(boolean val) {\n logToFile = val;\n return this;\n }\n\n @JsonProperty(\"timeout\")\n public Builder withGlobalTimeout(int val) {\n globalTimeout = val;\n return this;\n }\n\n public Builder withCheckForErrorsInLog(boolean val) {\n checkForErrorsInLog = val;\n return this;\n }\n\n @JsonInclude(value = Include.CUSTOM, valueFilter = HttpCheckFilter.class)\n public Builder withHttpCheck(HttpCheckConfig val) {\n httpCheck = val;\n return this;\n }\n\n public JobConfig build() {\n return new JobConfig(this);\n }\n\n public Builder addUrlConfig(String url, UrlConfig urlConfig) {\n if (urls == null) {\n urls = ImmutableMap.of(url, urlConfig);\n }\n else {\n urls = ImmutableMap.<String, UrlConfig>builder().putAll(urls).put(url, urlConfig).build();\n }\n return this;\n }\n }\n}", "public enum Step {\n before,\n after,\n compare\n}", "public class FileService {\n\n private final static Logger LOG = LoggerFactory.getLogger(lookup().lookupClass());\n\n public final static String FILE_SEPARATOR = FileSystems.getDefault().getSeparator();\n\n public static final String DIVIDER = \"_\";\n public static final String PNG_EXTENSION = \".png\";\n private static final int MAX_URL_TO_FILENAME_LENGTH = 180;\n\n public static final String FILETRACKER_FILENAME = \"files.json\";\n public static final String REPORT_HTML_FILENAME = \"report.html\";\n public static final String LEGACY_REPORT_HTML_FILENAME = \"report_legacy.html\";\n public static final String REPORT_JSON_FILENAME = \"report.json\";\n\n private final RunStepConfig runStepConfig;\n\n public FileTracker getFileTracker() {\n return fileTracker;\n }\n\n public ScreenshotContext getRecordedContext(int hash) {\n return fileTracker.getScreenshotContextFileTracker(hash).screenshotContext;\n }\n\n private final FileTracker fileTracker;\n\n public FileService(RunStepConfig runStepConfig, JobConfig jobConfig) {\n this.runStepConfig = runStepConfig;\n if (runStepConfig.getStep() == Step.before) {\n this.fileTracker = FileTracker.create(jobConfig);\n } else {\n Path path = Paths.get(runStepConfig.getWorkingDirectory(), runStepConfig.getReportDirectory(), FILETRACKER_FILENAME);\n this.fileTracker = JacksonWrapper.readFileTrackerFile(path.toFile());\n }\n }\n\n @VisibleForTesting\n Path createDirIfNotExists(String dirPath) throws IOException {\n Path path = Paths.get(dirPath);\n Files.createDirectories(path);\n return path;\n }\n\n\n public void createOrClearReportDirectory() throws IOException {\n createOrClearDirectoryBelowWorkingDir(runStepConfig.getWorkingDirectory(), runStepConfig.getReportDirectory());\n }\n\n @VisibleForTesting\n Path getScreenshotDirectory() {\n return Paths.get(String.format(\"%s/%s\", runStepConfig.getWorkingDirectory(), runStepConfig.getScreenshotsDirectory()));\n }\n\n private Path getReportDirectory() {\n return Paths.get(String.format(\"%s/%s\", runStepConfig.getWorkingDirectory(), runStepConfig.getReportDirectory()));\n }\n\n public void createWorkingDirectoryIfNotExists() throws IOException {\n try {\n createDirIfNotExists(runStepConfig.getWorkingDirectory());\n } catch (IOException e) {\n throw new IOException(\"Could not create or open working directory.\", e);\n }\n }\n\n public void createOrClearScreenshotsDirectory() throws IOException {\n createOrClearDirectoryBelowWorkingDir(runStepConfig.getWorkingDirectory(), runStepConfig.getScreenshotsDirectory());\n }\n\n private void createOrClearDirectoryBelowWorkingDir(String workingDirectory, String subDirectory) throws IOException {\n try {\n final String subDirectoryPath = workingDirectory + FILE_SEPARATOR + subDirectory;\n createDirIfNotExists(subDirectoryPath);\n clearDirectory(subDirectoryPath);\n } catch (IOException e) {\n throw new IOException(\"Could not create or open \" + subDirectory + \" directory.\", e);\n }\n }\n\n @VisibleForTesting\n String generateScreenshotFileName(String url, String urlSubPath, int width, int yPosition, String type) {\n\n String fileName = generateScreenshotFileNamePrefix(url, urlSubPath)\n + String.format(\"%04d\", width)\n + DIVIDER\n + String.format(\"%05d\", yPosition)\n + DIVIDER\n + type;\n\n fileName = fileName + PNG_EXTENSION;\n\n return fileName;\n }\n\n private String generateScreenshotFileNamePrefix(String url, String urlSubPath) {\n\n @SuppressWarnings(\"deprecation\") String hash = Hashing.sha1().hashString(url + urlSubPath, Charsets.UTF_8).toString().substring(0, 7);\n\n if (urlSubPath.equals(\"/\") || urlSubPath.equals(\"\")) {\n urlSubPath = \"root\";\n }\n if (url.endsWith(\"/\")) {\n url = url.substring(0, url.length() - 1);\n }\n\n String fileNamePrefix = url + DIVIDER + urlSubPath + DIVIDER;\n fileNamePrefix = fileNamePrefix.replace(\"://\", DIVIDER);\n fileNamePrefix = fileNamePrefix.replaceAll(\"[^A-Za-z0-9\\\\-_]\", DIVIDER);\n\n if (fileNamePrefix.length() > MAX_URL_TO_FILENAME_LENGTH) {\n fileNamePrefix = fileNamePrefix.substring(0, MAX_URL_TO_FILENAME_LENGTH) + DIVIDER;\n }\n\n fileNamePrefix = fileNamePrefix + hash + DIVIDER;\n\n return fileNamePrefix;\n }\n\n @VisibleForTesting\n String getScreenshotPath(String url, String urlSubPath, int width, int yPosition, String step) {\n return runStepConfig.getWorkingDirectory() + (runStepConfig.getWorkingDirectory().endsWith(FILE_SEPARATOR) ? \"\" : FILE_SEPARATOR)\n + runStepConfig.getScreenshotsDirectory() + (runStepConfig.getScreenshotsDirectory().endsWith(FILE_SEPARATOR) ? \"\" : FILE_SEPARATOR)\n + generateScreenshotFileName(url, urlSubPath, width, yPosition, step);\n }\n\n private String getScreenshotPath(String fileName) {\n return runStepConfig.getWorkingDirectory() + (runStepConfig.getWorkingDirectory().endsWith(FILE_SEPARATOR) ? \"\" : FILE_SEPARATOR)\n + runStepConfig.getScreenshotsDirectory() + (runStepConfig.getScreenshotsDirectory().endsWith(FILE_SEPARATOR) ? \"\" : FILE_SEPARATOR)\n + fileName;\n }\n\n public BufferedImage readScreenshot(String fileName) throws IOException {\n return ImageIO.read(new File(getScreenshotPath(fileName)));\n }\n\n private static void writeScreenshot(String fileName, BufferedImage image) throws IOException {\n LOG.debug(\"Writing screenshot to {}\", fileName);\n File screenshotFile = new File(fileName);\n ImageIO.write(image, \"png\", screenshotFile);\n }\n\n public String writeScreenshot(ScreenshotContext screenshotContext, BufferedImage image,\n int yPosition) throws IOException {\n\n createDirIfNotExists(getScreenshotDirectory().toString() + FILE_SEPARATOR + screenshotContext.contextHash());\n String fileName = getScreenshotFilenameBelowScreenshotsDir(screenshotContext, yPosition);\n writeScreenshot(Paths.get(getScreenshotDirectory().toString(), fileName).toString(), image);\n fileTracker.addScreenshot(screenshotContext, fileName, yPosition);\n return fileName;\n }\n\n private String getScreenshotFilenameBelowScreenshotsDir(ScreenshotContext screenshotContext, int yPosition) {\n return screenshotContext.contextHash() + FILE_SEPARATOR + generateScreenshotFileName(screenshotContext.url, screenshotContext.urlSubPath, screenshotContext.deviceConfig.width, yPosition, screenshotContext.step.name());\n }\n\n public String getRelativePathFromReportDirToScreenshotsDir() {\n Path screenshotDirectory = getScreenshotDirectory().toAbsolutePath();\n Path reportDirectory = getReportDirectory().toAbsolutePath();\n Path relative = reportDirectory.relativize(screenshotDirectory);\n return relative.toString().equals(\"\") ? \"\" : relative.toString() + FILE_SEPARATOR;\n }\n\n public void writeJsonReport(String reportJson) throws FileNotFoundException {\n try (PrintStream out = new PrintStream(new FileOutputStream(getReportDirectory().toString() + FILE_SEPARATOR + REPORT_JSON_FILENAME))) {\n out.print(reportJson);\n }\n }\n\n public void writeHtmlReport(String htmlReport) throws FileNotFoundException {\n writeHtmlReport(htmlReport, LEGACY_REPORT_HTML_FILENAME);\n }\n\n public void writeHtmlReport(String htmlReport, String filename) throws FileNotFoundException {\n try (PrintStream out = new PrintStream(new FileOutputStream(getReportDirectory().toString() + FILE_SEPARATOR + filename))) {\n out.print(htmlReport);\n }\n }\n\n public void writeHtml(String html, Step step) throws FileNotFoundException {\n try (PrintStream out = new PrintStream(new FileOutputStream(getReportDirectory().toString() + FILE_SEPARATOR + step + \".html\"))) {\n out.print(html);\n }\n }\n\n public void writeFileTrackerData() throws IOException {\n Path path = Paths.get(getReportDirectory().toString(), FILETRACKER_FILENAME);\n Files.write(path, JacksonWrapper.serializeObject(fileTracker).getBytes());\n }\n\n public void setBrowserAndVersion(ScreenshotContext screenshotContext, String browserAndVersion) {\n fileTracker.setBrowserAndVersion(screenshotContext, browserAndVersion);\n }\n\n public Map<Step, String> getBrowsers() {\n return fileTracker.browsers;\n }\n}" ]
import com.google.common.collect.ImmutableMap; import de.otto.jlineup.browser.ScreenshotContext; import de.otto.jlineup.config.DeviceConfig; import de.otto.jlineup.config.JobConfig; import de.otto.jlineup.config.Step; import de.otto.jlineup.config.UrlConfig; import de.otto.jlineup.file.FileService; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import java.io.FileNotFoundException; import java.util.List; import java.util.Map; import static java.util.Collections.singletonList; import static java.util.Collections.singletonMap; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.not; import static org.hamcrest.core.StringEndsWith.endsWith; import static org.hamcrest.core.StringStartsWith.startsWith; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks;
package de.otto.jlineup.report; public class HTMLReportWriterTest { private HTMLReportWriter testee; @Mock private FileService fileServiceMock; private final List<ScreenshotComparisonResult> screenshotComparisonResults = singletonList(new ScreenshotComparisonResult(1887, "someurl/somepath", DeviceConfig.deviceConfig(1337,200), 1338, 0d, "before", "after", "differenceSum", 0)); private Summary summary = new Summary(true, 1d, 0.5d, 0); private Summary localSummary = new Summary(true, 2d, 0.3d, 0); private final Map<String, UrlReport> screenshotComparisonResultList = singletonMap("test", new UrlReport(screenshotComparisonResults, localSummary)); private Report report = new Report(summary, screenshotComparisonResultList, JobConfig.exampleConfig()); @Before public void setup() { initMocks(this); testee = new HTMLReportWriter(fileServiceMock);
when(fileServiceMock.getRecordedContext(anyInt())).thenReturn(ScreenshotContext.of("someUrl", "somePath", DeviceConfig.deviceConfig(1337,200), Step.before, UrlConfig.urlConfigBuilder().build()));
3
palominolabs/benchpress
examples/multi-db/mongodb/src/main/java/com/palominolabs/benchpress/example/multidb/mongodb/MongoDbTaskFactory.java
[ "public abstract class TaskFactoryBase {\n protected final ValueGeneratorFactory valueGeneratorFactory;\n protected final KeyGeneratorFactory keyGeneratorFactory;\n protected final TaskOperation taskOperation;\n protected final int numThreads;\n protected final int numQuanta;\n protected final int batchSize;\n\n protected TaskFactoryBase(TaskOperation taskOperation, ValueGeneratorFactory valueGeneratorFactory, int batchSize,\n KeyGeneratorFactory keyGeneratorFactory, int numQuanta, int numThreads) {\n this.taskOperation = taskOperation;\n this.valueGeneratorFactory = valueGeneratorFactory;\n this.batchSize = batchSize;\n this.keyGeneratorFactory = keyGeneratorFactory;\n this.numQuanta = numQuanta;\n this.numThreads = numThreads;\n }\n\n}", "@ThreadSafe\npublic interface KeyGeneratorFactory {\n /**\n * Should be called by each worker thread.\n *\n * @return a KeyGenerator\n */\n KeyGenerator getKeyGenerator();\n}", "@NotThreadSafe\npublic interface TaskFactory {\n\n /**\n * @param jobId job id\n * @param sliceId the slice of the overall job that these tasks are part of\n * @param workerId the worker that these tasks are running in\n * @param progressClient client the workers can use to hand any notable data back to the controller\n * @return runnables\n * @throws IOException if task creation fails\n */\n @Nonnull\n Collection<Runnable> getRunnables(@Nonnull UUID jobId, int sliceId, @Nonnull UUID workerId,\n @Nonnull ScopedProgressClient progressClient) throws\n IOException;\n\n // TODO actually call this somewhere\n void shutdown();\n}", "public enum TaskOperation {\n /** A write operation */\n WRITE,\n /** A read operation */\n READ\n}", "@NotThreadSafe\npublic interface ValueGeneratorFactory {\n ValueGenerator getValueGenerator();\n}", "public class ScopedProgressClient {\n\n private final UUID jobId;\n\n private final int sliceId;\n\n private final String jobFinishedUrl;\n private final String jobProgressUrl;\n private final TaskProgressClient client;\n\n public ScopedProgressClient(UUID jobId, int sliceId, String jobFinishedUrl, String jobProgressUrl, TaskProgressClient client) {\n this.jobId = jobId;\n this.sliceId = sliceId;\n this.jobFinishedUrl = jobFinishedUrl;\n this.jobProgressUrl = jobProgressUrl;\n this.client = client;\n }\n\n public void reportFinished(Duration duration) {\n client.reportFinished(jobId, sliceId, duration, jobFinishedUrl);\n }\n\n public void reportProgress(JsonNode data) {\n client.reportProgress(jobId, sliceId, data, jobProgressUrl);\n }\n}" ]
import com.google.common.collect.Lists; import com.mongodb.DB; import com.mongodb.Mongo; import com.palominolabs.benchpress.example.multidb.task.TaskFactoryBase; import com.palominolabs.benchpress.example.multidb.key.KeyGeneratorFactory; import com.palominolabs.benchpress.job.task.TaskFactory; import com.palominolabs.benchpress.job.task.TaskOperation; import com.palominolabs.benchpress.example.multidb.value.ValueGeneratorFactory; import com.palominolabs.benchpress.task.reporting.ScopedProgressClient; import javax.annotation.Nonnull; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.UUID;
package com.palominolabs.benchpress.example.multidb.mongodb; final class MongoDbTaskFactory extends TaskFactoryBase implements TaskFactory { private final String hostname; private final int port; private final String dbName; private String collectionName; private Mongo mongo; MongoDbTaskFactory(TaskOperation taskOperation, ValueGeneratorFactory valueGeneratorFactory, int batchSize, KeyGeneratorFactory keyGeneratorFactory, int numQuanta, int numThreads, String hostname, int port, String dbName, String collectionName) { super(taskOperation, valueGeneratorFactory, batchSize, keyGeneratorFactory, numQuanta, numThreads); this.hostname = hostname; this.port = port; this.dbName = dbName; this.collectionName = collectionName; } @Nonnull @Override public Collection<Runnable> getRunnables(@Nonnull UUID jobId, int sliceId, @Nonnull UUID workerId,
@Nonnull ScopedProgressClient progressClient) throws IOException {
5
copygirl/copycore
src/net/mcft/copy/core/client/gui/GuiConfigBase.java
[ "public class Config extends AbstractConfig {\n\t\n\tprivate final File file;\n\tprivate final Configuration forgeConfig;\n\t\n\tprivate final Map<Setting, Object> settingValues = new HashMap<Setting, Object>();\n\tprivate final Map<String, String> categoryComments = new HashMap<String, String>();\n\t\n\tprivate final List<SettingInfo> settings = new ArrayList<SettingInfo>();\n\t\n\tpublic Config(File file) {\n\t\tthis.file = file;\n\t\tforgeConfig = new ModifiedConfiguration(file);\n\t}\n\t\n\t/** Adds a setting to the config. */\n\tpublic <T> Setting<T> add(SettingInfo<T> settingInfo) {\n\t\tSetting<T> setting = settingInfo.setting;\n\t\tsettingValues.put(setting, setting.defaultValue);\n\t\tsettings.add(settingInfo);\n\t\tonSettingChanged(setting, setting.defaultValue);\n\t\treturn setting;\n\t}\n\t\n\t/** Add all static settings of the class automatically via reflection. */\n\tpublic void addAllViaReflection() {\n\t\tfor (Field field : getClass().getFields())\n\t\t\tif (Modifier.isStatic(field.getModifiers()) &&\n\t\t\t (field.getType().isAssignableFrom(Setting.class)))\n\t\t\t\tadd(new SettingInfo(field));\n\t}\n\t\n\t@Override\n\tpublic <T> T get(Setting<T> setting) { return (T)settingValues.get(setting); }\n\t\n\t/** Sets the value of the setting in this config. */\n\tpublic <T> void set(Setting<T> setting, T value) {\n\t\tif (Objects.equals(get(setting), value)) return;\n\t\tsettingValues.put(setting, value);\n\t\tonSettingChanged(setting, value);\n\t}\n\t\n\t@Override\n\tpublic Collection<Setting> getSettings() { return settingValues.keySet(); }\n\t\n\t/** Returns a collection of all setting infos in this config. */\n\tpublic Collection<SettingInfo> getSettingInfos() { return settings; }\n\t\n\t/** Adds a custom comment to a category. */\n\tpublic void addCategoryComment(String category, String comment) {\n\t\tcategoryComments.put(category, comment);\n\t}\n\t\n\t/** Returns if the config file exists. */\n\tpublic boolean exists() {\n\t\treturn file.exists();\n\t}\n\t\n\t/** Loads settings from the config file. */\n\tpublic void load() {\n\t\tforgeConfig.load();\n\t\tfor (Map.Entry<Setting, Object> entry : settingValues.entrySet()) {\n\t\t\tSetting setting = entry.getKey();\n\t\t\tObject value = setting.load(forgeConfig);\n\t\t\tString validationError = setting.validate(value);\n\t\t\tif (validationError != null) {\n\t\t\t\tvalue = setting.defaultValue;\n\t\t\t\tcopycore.log.warn(String.format(\n\t\t\t\t\t\t\"Config setting %s in %s is invalid: %s. Using default value: %s.\",\n\t\t\t\t\t\tsetting, file.getName(), validationError, value));\n\t\t\t}\n\t\t\tset(setting, value);\n\t\t}\n\t}\n\t\n\t/** Saves settings to the config file. */\n\tpublic void save() {\n\t\tfor (Map.Entry<Setting, Object> entry : settingValues.entrySet())\n\t\t\tentry.getKey().save(forgeConfig, entry.getValue());\n\t\tfor (Map.Entry<String, String> entry : categoryComments.entrySet())\n\t\t\tforgeConfig.setCategoryComment(entry.getKey(), entry.getValue());\n\t\tforgeConfig.save();\n\t}\n\t\n\tprivate static class ModifiedConfiguration extends Configuration {\n\t\tprivate static boolean preventLoad = false;\n\t\tprivate final File file;\n\t\tpublic ModifiedConfiguration(File file) {\n\t\t\t// Hacky way of preventing the config file from\n\t\t\t// being loaded when the configuration is constructed.\n\t\t\tsuper((preventLoad = true) ? file : null);\n\t\t\tpreventLoad = false;\n\t\t\tthis.file = file;\n\t\t}\n\t\t@Override public void load() {\n\t\t\t// Don't load/create the config file when it doesn't exist.\n\t\t\tif (!preventLoad && file.exists()) super.load();\n\t\t}\n\t}\n\t\n}", "public class SettingInfo<T> {\n\t\n\tpublic final Setting<T> setting;\n\t\n\tpublic final boolean requiresWorldRestart;\n\tpublic final boolean requiresMinecraftRestart;\n\t\n\tpublic final boolean showInConfigGui;\n\tpublic final String configElementClass;\n\tpublic final String configEntryClass;\n\t\n\tpublic SettingInfo(Setting<T> setting, boolean requiresWorldRestart, boolean requiresMinecraftRestart,\n\t boolean showInConfigGui, String configElementClass, String configEntryClass) {\n\t\tthis.setting = setting;\n\t\t\n\t\tthis.requiresWorldRestart = requiresWorldRestart;\n\t\tthis.requiresMinecraftRestart = requiresMinecraftRestart;\n\t\t\n\t\tthis.showInConfigGui = showInConfigGui;\n\t\tthis.configElementClass = configElementClass;\n\t\tthis.configEntryClass = configEntryClass;\n\t}\n\tpublic SettingInfo(Setting<T> setting, boolean requiresWorldRestart, boolean requiresMinecraftRestart) {\n\t\tthis(setting, requiresWorldRestart, requiresMinecraftRestart, true, \"\", \"\");\n\t}\n\t\n\tpublic SettingInfo(Field field) {\n\t\ttry { setting = (Setting<T>)field.get(null); }\n\t\tcatch (Exception e) { throw new RuntimeException(e); }\n\t\t\n\t\tConfigSetting annotation = field.getAnnotation(ConfigSetting.class);\n\t\t\n\t\trequiresMinecraftRestart = ((annotation != null) && annotation.requiresMinecraftRestart());\n\t\trequiresWorldRestart = (requiresMinecraftRestart || ((annotation != null) && annotation.requiresWorldRestart()));\n\t\t\n\t\tshowInConfigGui = true;\n\t\tconfigElementClass = ((annotation != null) ? annotation.getConfigElementClass() : \"\");\n\t\tconfigEntryClass = ((annotation != null) ? annotation.getConfigEntryClass() : \"\");\n\t}\n\t\n\t\n\t\n}", "public class BooleanSetting extends SinglePropertySetting<Boolean> {\n\t\n\tpublic BooleanSetting(String fullName, Boolean defaultValue) {\n\t\tsuper(fullName, defaultValue);\n\t}\n\tpublic BooleanSetting(String fullName) {\n\t\tthis(fullName, false);\n\t}\n\t\n\t@Override\n\tpublic BooleanSetting setComment(String comment) {\n\t\tsuper.setComment(comment);\n\t\treturn this;\n\t}\n\t\n\t@Override\n\tprotected Type getPropertyType() { return Type.BOOLEAN; }\n\t\n\t@Override\n\tpublic Boolean load(Configuration config) { return getProperty(config).getBoolean(defaultValue); }\n\t@Override\n\tpublic void save(Configuration config, Boolean value) { getProperty(config).set(value); }\n\t\n\t@Override\n\tpublic Boolean read(NBTTagCompound compound) { return compound.getBoolean(fullName); }\n\t@Override\n\tpublic void write(NBTTagCompound compound, Boolean value) { compound.setBoolean(fullName, value); }\n\t\n}", "public class DoubleSetting extends SinglePropertySetting<Double> {\n\t\n\tpublic double minValue = Double.MIN_VALUE;\n\tpublic double maxValue = Double.MAX_VALUE;\n\t\n\tpublic DoubleSetting(String fullName, Double defaultValue) {\n\t\tsuper(fullName, defaultValue);\n\t}\n\tpublic DoubleSetting(String fullName) {\n\t\tthis(fullName, 0.0);\n\t}\n\t\n\t@Override\n\tpublic DoubleSetting setComment(String comment) {\n\t\tsuper.setComment(comment);\n\t\treturn this;\n\t}\n\t\n\t/** Sets the valid range of values for this setting. */\n\tpublic DoubleSetting setValidRange(double min, double max) {\n\t\tminValue = min;\n\t\tmaxValue = max;\n\t\treturn this;\n\t}\n\t\n\t@Override\n\tpublic String validate(Double value) {\n\t\tif ((value < minValue) || (value > maxValue))\n\t\t\treturn String.format(\"Value %s is not in valid range, %s to %s\",\n\t\t\t value, minValue, maxValue);\n\t\treturn null;\n\t}\n\t\n\t@Override\n\tprotected Type getPropertyType() { return Type.DOUBLE; }\n\t\n\t@Override\n\tpublic Double load(Configuration config) { return getProperty(config).getDouble(defaultValue); }\n\t@Override\n\tpublic void save(Configuration config, Double value) { getProperty(config).set(value); }\n\t\n\t@Override\n\tpublic Double read(NBTTagCompound compound) { return compound.getDouble(fullName); }\n\t@Override\n\tpublic void write(NBTTagCompound compound, Double value) { compound.setDouble(fullName, value); }\n\t\n}", "public class EnumSetting<T extends Enum<T>> extends SinglePropertySetting<T> {\n\t\n\tprivate final Map<String, T> enumMap = new HashMap<String, T>();\n\tprivate final String validValues;\n\t\n\tpublic EnumSetting(String fullName, T defaultValue) {\n\t\tsuper(fullName, defaultValue);\n\t\tStringBuilder sb = new StringBuilder();\n\t\tfor (T value : ((Class<T>)defaultValue.getClass()).getEnumConstants()) {\n\t\t\tenumMap.put(value.toString(), value);\n\t\t\tsb.append(\", \").append(value);\n\t\t}\n\t\tvalidValues = sb.substring(2);\n\t}\n\t\n\t@Override\n\tpublic EnumSetting<T> setComment(String comment) {\n\t\tsuper.setComment(comment);\n\t\treturn this;\n\t}\n\t\n\t@Override\n\tpublic String validate(T value) {\n\t\treturn ((value == null) ? \"Must be one of \" + validValues + \".\" : null);\n\t}\n\t\n\t@Override\n\tprotected Type getPropertyType() { return Type.STRING; }\n\t\n\t@Override\n\tpublic T load(Configuration config) { return enumMap.get(getProperty(config).getString()); }\n\t@Override\n\tpublic void save(Configuration config, T value) { getProperty(config).set(value.toString()); }\n\t\n\t@Override\n\tpublic T read(NBTTagCompound compound) { return enumMap.get(compound.getString(fullName)); }\n\t@Override\n\tpublic void write(NBTTagCompound compound, T value) { compound.setString(fullName, value.toString()); }\n\t\n}", "public class IntegerSetting extends SinglePropertySetting<Integer> {\n\t\n\tpublic int minValue = Integer.MIN_VALUE;\n\tpublic int maxValue = Integer.MAX_VALUE;\n\tpublic int[] validValues = null;\n\t\n\tpublic IntegerSetting(String fullName, Integer defaultValue) {\n\t\tsuper(fullName, defaultValue);\n\t}\n\tpublic IntegerSetting(String fullName) {\n\t\tthis(fullName, 0);\n\t}\n\t\n\t@Override\n\tpublic IntegerSetting setComment(String comment) {\n\t\tsuper.setComment(comment);\n\t\treturn this;\n\t}\n\t\n\t/** Sets the valid range of values for this setting. */\n\tpublic IntegerSetting setValidRange(int min, int max) {\n\t\tminValue = min;\n\t\tmaxValue = max;\n\t\treturn this;\n\t}\n\t/** Sets the valid values for this setting. */\n\tpublic IntegerSetting setValidValues(int... values) {\n\t\tvalidValues = values;\n\t\treturn this;\n\t}\n\t\n\t@Override\n\tpublic String validate(Integer value) {\n\t\tif ((value < minValue) || (value > maxValue))\n\t\t\treturn String.format(\"Value %s is not in valid range, %s to %s\",\n\t\t\t value, minValue, maxValue);\n\t\tif ((validValues != null) && !ArrayUtils.contains(validValues, value))\n\t\t\treturn String.format(\"Value %s is not valid, needs to be one of %s\",\n\t\t\t value, Arrays.toString(validValues));\n\t\treturn null;\n\t}\n\t\n\t@Override\n\tprotected Type getPropertyType() { return Type.INTEGER; }\n\t\n\t@Override\n\tpublic Integer load(Configuration config) { return getProperty(config).getInt(); }\n\t@Override\n\tpublic void save(Configuration config, Integer value) { getProperty(config).set(value); }\n\t\n\t@Override\n\tpublic Integer read(NBTTagCompound compound) { return compound.getInteger(fullName); }\n\t@Override\n\tpublic void write(NBTTagCompound compound, Integer value) { compound.setInteger(fullName, value); }\n\t\n}", "public abstract class Setting<T> {\n\t\n\t/** The name including the category, for example \"block.storage.flint\". */\n\tpublic final String fullName;\n\t/** The name not including the category, for example \"flint\". */\n\tpublic final String name;\n\t/** The category, for example \"block.storage\". */\n\tpublic final String category;\n\t\n\t/** The default value of this setting. */\n\tpublic final T defaultValue;\n\t/** The comment of this setting setting, null if none. */\n\tpublic String comment = null;\n\t\n\tpublic Setting(String fullName, T defaultValue) {\n\t\tthis.fullName = fullName;\n\t\tint dotIndex = fullName.lastIndexOf('.');\n\t\tif (dotIndex < 1) throw new IllegalArgumentException(\"fullName doesn't contain a category.\");\n\t\tname = fullName.substring(dotIndex + 1);\n\t\tcategory = fullName.substring(0, dotIndex);\n\t\t\n\t\tthis.defaultValue = defaultValue;\n\t}\n\t\n\t/** Sets the comment for this setting. */\n\tpublic Setting<T> setComment(String comment) {\n\t\tthis.comment = comment;\n\t\treturn this;\n\t}\n\t\n\t/** Validates the setting and returns a warning\n\t * string, or null if validation was successful. */\n\tpublic String validate(T value) { return null; }\n\t\n\t/** Loads the setting's value from the config. */\n\tpublic abstract T load(Configuration config);\n\t/** Saves the setting's value to the config. */\n\tpublic abstract void save(Configuration config, T value);\n\t\n\t/** Reads the setting's synced value from the compound tag. */\n\tpublic abstract T read(NBTTagCompound compound);\n\t/** Writes the setting's value to the compound tag. */\n\tpublic abstract void write(NBTTagCompound compound, T value);\n\t\n\t// Equals, hashCode and toString\n\t\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\treturn ((obj instanceof Setting) ? fullName.equals(((Setting)obj).fullName) : false);\n\t}\n\t\n\t@Override\n\tpublic int hashCode() { return fullName.hashCode(); }\n\t\n\t@Override\n\tpublic String toString() { return \"[\" + fullName + \"]\"; }\n\t\n}", "public class StringSetting extends SinglePropertySetting<String> {\n\t\n\tpublic String[] validValues = null;\n\t\n\tpublic StringSetting(String fullName, String defaultValue) {\n\t\tsuper(fullName, defaultValue);\n\t}\n\tpublic StringSetting(String fullName) {\n\t\tthis(fullName, \"\");\n\t}\n\t\n\t@Override\n\tpublic StringSetting setComment(String comment) {\n\t\tsuper.setComment(comment);\n\t\treturn this;\n\t}\n\t\n\t/** Sets the valid values for this setting. */\n\tpublic StringSetting setValidValues(String... values) {\n\t\tvalidValues = values;\n\t\treturn this;\n\t}\n\t\n\t@Override\n\tprotected Type getPropertyType() { return Type.STRING; }\n\t\n\t@Override\n\tpublic String load(Configuration config) { return getProperty(config).getString(); }\n\t@Override\n\tpublic void save(Configuration config, String value) { getProperty(config).set(value); }\n\t\n\t@Override\n\tpublic String read(NBTTagCompound compound) { return compound.getString(fullName); }\n\t@Override\n\tpublic void write(NBTTagCompound compound, String value) { compound.setString(fullName, value); }\n\t\n}" ]
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.mcft.copy.core.config.Config; import net.mcft.copy.core.config.SettingInfo; import net.mcft.copy.core.config.setting.BooleanSetting; import net.mcft.copy.core.config.setting.DoubleSetting; import net.mcft.copy.core.config.setting.EnumSetting; import net.mcft.copy.core.config.setting.IntegerSetting; import net.mcft.copy.core.config.setting.Setting; import net.mcft.copy.core.config.setting.StringSetting; import net.minecraft.client.gui.GuiScreen; import cpw.mods.fml.client.config.ConfigGuiType; import cpw.mods.fml.client.config.DummyConfigElement; import cpw.mods.fml.client.config.DummyConfigElement.DummyCategoryElement; import cpw.mods.fml.client.config.GuiConfig; import cpw.mods.fml.client.config.GuiConfigEntries; import cpw.mods.fml.client.config.GuiConfigEntries.CategoryEntry; import cpw.mods.fml.client.config.GuiConfigEntries.IConfigEntry; import cpw.mods.fml.client.config.IConfigElement; import cpw.mods.fml.client.event.ConfigChangedEvent.OnConfigChangedEvent; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly;
package net.mcft.copy.core.client.gui; @SideOnly(Side.CLIENT) public abstract class GuiConfigBase extends GuiConfig { public final Config config; public GuiConfigBase(GuiScreen parentScreen, String id, String configId, String title, Config config) { super(parentScreen, getElementsFor(config, id), configId, false, false, title); this.config = config; } public GuiConfigBase(GuiScreen parentScreen, String id, String title, Config config) { this(parentScreen, id, id, title, config); } public GuiConfigBase(GuiScreen parentScreen, String id, Config config) { this(parentScreen, id, id, config); } @Override public void initGui() { super.initGui(); FMLCommonHandler.instance().bus().register(this); } @Override public void onGuiClosed() { super.onGuiClosed(); FMLCommonHandler.instance().bus().unregister(this); } @SubscribeEvent public final void onConfigChangedEvent(OnConfigChangedEvent event) { if ((event.modID == modID) && (event.configID == configID)) config.save(); } /** Gets the config entry for a setting in this GUI. */ public IConfigEntry getEntry(Setting setting) { for (IConfigEntry entry : entryList.listEntries) if (setting.fullName.equals(entry.getName())) return entry; return null; } /** Gets the config entry for a category in this GUI. */ public CategoryElement.Entry getCategoryEntry(String category) { for (IConfigEntry entry : entryList.listEntries) if ((entry instanceof CategoryEntry) && category.equals(entry.getName())) return (CategoryElement.Entry)entry; return null; } /** Gets all config elements to display on the config screen. */ public static List<IConfigElement> getElementsFor(Config config, String modId) { List<IConfigElement> list = new ArrayList<IConfigElement>(); Map<String, List<IConfigElement>> categoryMap = new HashMap<String, List<IConfigElement>>(); // Get all static setting fields from the config class. for (SettingInfo info : config.getSettingInfos()) if (info.showInConfigGui) { IConfigElement configElement; // If the setting doesn't have a ConfigSetting annotation or its // custom config element class was not set, use the default one. if (info.configElementClass.isEmpty()) { Class<? extends IConfigEntry> entryClass = null; try { if (!info.configEntryClass.isEmpty()) entryClass = (Class<? extends IConfigEntry>)Class.forName(info.configEntryClass); } catch (Exception ex) { throw new RuntimeException(ex); } configElement = new SettingConfigElement(config, info.setting, modId, info.requiresMinecraftRestart, info.requiresWorldRestart).setConfigEntryClass(entryClass); // Otherwise try to instantiate the custom config element. } else try { configElement = (IConfigElement)Class.forName(info.configElementClass).getConstructor( Config.class, Setting.class, String.class, boolean.class, boolean.class) .newInstance(config, info.setting, modId, info.requiresMinecraftRestart, info.requiresWorldRestart); } catch (Exception ex) { throw new RuntimeException(ex); } // If the setting's category is not "general", add it to the category map. if (!info.setting.category.equals("general")) { List<IConfigElement> categoryList; if ((categoryList = categoryMap.get(info.setting.category)) == null) categoryMap.put(info.setting.category, (categoryList = new ArrayList<IConfigElement>())); categoryList.add(configElement); // Otherwise just add it to the main config screen. } else list.add(configElement); } // Create and add category elements to the main config screen. for (Map.Entry<String, List<IConfigElement>> entry : categoryMap.entrySet()) list.add(new CategoryElement(entry.getKey(), "config." + modId.toLowerCase() + ".category." + entry.getKey(), entry.getValue())); return list; } public static class SettingConfigElement<T> extends DummyConfigElement<T> { public final Config config; public final Setting<T> setting; public SettingConfigElement(Config config, Setting<T> setting, String modId, boolean reqMinecraftRestart, boolean reqWorldRestart) { super(setting.fullName, setting.defaultValue, getGuiType(setting), "config." + modId.toLowerCase() + "." + setting.fullName, getValidValues(setting), null, getMinValue(setting), getMaxValue(setting)); this.config = config; this.setting = setting; requiresMcRestart = reqMinecraftRestart; requiresWorldRestart = reqWorldRestart; } @Override public Object get() { return config.get(setting); } @Override public void set(T value) { if (setting instanceof EnumSetting) value = (T)Enum.valueOf((Class<Enum>)setting.defaultValue.getClass(), (String)value); config.set(setting, value); } public static <T> ConfigGuiType getGuiType(Setting<T> setting) {
if (setting instanceof BooleanSetting) return ConfigGuiType.BOOLEAN;
2
kinabalu/mysticpaste
web/src/main/java/com/mysticcoders/mysticpaste/web/pages/admin/OverviewPage.java
[ "@Entity(\"pastes\")\n@Message\npublic class PasteItem implements Serializable {\n private static final long serialVersionUID = -6467870857777145137L;\n private static Logger logger = LoggerFactory.getLogger(PasteItem.class);\n private static SimpleDateFormat sdf = new SimpleDateFormat(\"MM/dd/yyyy\");\n\n @Id ObjectId id;\n\n private long pasteIndex;\n protected String itemId;\n protected String content;\n protected String type;\n protected Date timestamp;\n protected int abuseCount;\n protected boolean privateFlag;\n protected String parent;\n protected String clientIp;\n protected int viewCount;\n\n private String imageLocation;\n\n public long getPasteIndex() {\n return pasteIndex;\n }\n\n public void setPasteIndex(long pasteIndex) {\n this.pasteIndex = pasteIndex;\n }\n\n public String getItemId() {\n return itemId;\n }\n\n public void setItemId(String itemId) {\n this.itemId = itemId;\n }\n\n public String getContent() {\n return content;\n }\n\n public void setContent(String content) {\n this.content = content;\n }\n\n /**\n * Calculate up to 5 lines for a preview and return it to end user\n *\n * @return up to 5 lines of paste, or empty string\n */\n public String getPreviewContent() {\n if (getContent() == null || getContent().length() == 0) return \"\";\n\n String[] contentLines = getContent().split(\"\\n\");\n\n if (contentLines == null) return \"\";\n\n StringBuffer previewContent = new StringBuffer();\n\n for (int i = 0; i < (contentLines.length < 5 ? contentLines.length : 5); i++) {\n previewContent.append(contentLines[i]).append(\"\\n\");\n }\n return previewContent.toString();\n }\n\n public String getType() {\n return type;\n }\n\n public void setType(String type) {\n this.type = type;\n }\n\n public Date getTimestamp() {\n return timestamp;\n }\n\n public void setTimestamp(Date timestamp) {\n this.timestamp = timestamp;\n }\n\n public int getAbuseCount() {\n return abuseCount;\n }\n\n public void markAbuse() {\n this.abuseCount += 1;\n }\n\n public boolean isPrivate() {\n return privateFlag;\n }\n\n public void setPrivate(boolean privateFlag) {\n this.privateFlag = privateFlag;\n }\n\n public String getParent() {\n return parent;\n }\n\n public void setParent(String parent) {\n this.parent = parent;\n }\n\n public void setClientIp(String clientIp) {\n this.clientIp = clientIp;\n }\n\n public int getViewCount() {\n return viewCount;\n }\n\n public void increaseViewCount() {\n viewCount += 1;\n }\n\n public String getImageLocation() {\n return imageLocation;\n }\n\n public void setImageLocation(String imageLocation) {\n this.imageLocation = imageLocation;\n }\n\n public boolean hasImage() {\n return this.imageLocation != null && this.imageLocation.length() > 0;\n }\n\n public int getContentLineCount() {\n if (getContent() == null || getContent().length() == 0) return 0;\n\n String[] lines = getContent().split(\"\\n\");\n return lines != null ? lines.length : 0;\n }\n\n /**\n * Return a simplistic diff view of 2 pastes\n *\n * @param originalPaste\n * @param revisedPaste\n * @return\n */\n public static Object[] diffPastes(String originalPaste, String revisedPaste) {\n int new_line_count = 0;\n int old_line_count = 0;\n\n logger.info(\"Original: \" + (originalPaste != null ? originalPaste.length() : 0) + \" line(s)\");\n logger.info(\"Revised: \" + (revisedPaste != null ? revisedPaste.length() : 0) + \" line(s)\");\n\n List<String> original = Arrays.asList(originalPaste.split(\"\\n\"));\n List<String> revised = Arrays.asList(revisedPaste.split(\"\\n\"));\n\n List<Integer> changedLines = new ArrayList<Integer>();\n\n int lineIndex = 0;\n\n StringBuilder diffText = new StringBuilder();\n List<Difference> diffs = new Diff<String>(original, revised).diff();\n for (Difference diff : diffs) {\n int del_start = diff.getDeletedStart();\n int del_end = diff.getDeletedEnd();\n int add_start = diff.getAddedStart();\n int add_end = diff.getAddedEnd();\n\n if (del_end != Difference.NONE) {\n for (; old_line_count < del_start; ++old_line_count, ++new_line_count) {\n diffText.append(original.get(old_line_count)).append(\"\\n\");\n lineIndex++;\n }\n for (; old_line_count <= del_end; ++old_line_count) {\n diffText.append(\"- \").append(original.get(old_line_count)).append(\"\\n\");\n changedLines.add(lineIndex);\n lineIndex++;\n }\n }\n\n if (add_end != Difference.NONE) {\n for (; new_line_count < add_start; ++new_line_count, ++old_line_count) {\n diffText.append(revised.get(new_line_count)).append(\"\\n\");\n lineIndex++;\n }\n\n for (; new_line_count <= add_end; ++new_line_count) {\n diffText.append(\"+ \").append(revised.get(new_line_count)).append(\"\\n\");\n changedLines.add(lineIndex);\n lineIndex++;\n }\n\n }\n }\n\n for (; new_line_count < revised.size(); ++new_line_count, ++old_line_count) {\n diffText.append(revised.get(new_line_count));\n }\n\n return new Object[]{changedLines, diffText.toString()};\n\n }\n\n\n public static String getElapsedTimeSincePost(PasteItem pasteItem) {\n String returnString;\n\n Calendar today = Calendar.getInstance();\n Calendar postDate = Calendar.getInstance();\n postDate.setTime(pasteItem.getTimestamp());\n\n long time = today.getTimeInMillis() - postDate.getTimeInMillis();\n long mins = time / 1000 / 60;\n long hours = mins / 60;\n long days = hours / 24;\n\n if (days > 30) {\n // If it is more than 30 days old... just show the post date\n returnString = \"Posted \" + sdf.format(postDate.getTime());\n } else {\n if (days > 0) {\n // Then it is more than 1 day old but less than 30 days old... so show how many days old it is\n returnString = \"Posted \" + days + \" day\" + (days > 1 ? \"s\" : \"\") + \" ago\";\n } else {\n if (hours > 0) {\n // It has been more than 1 hr and less than a day... so display hrs\n returnString = \"Posted \" + hours + \" hour\" + (hours > 1 ? \"s\" : \"\") + \" ago\";\n } else {\n if (mins > 0) {\n // It has been more than 1 min and less than an hour... so display mins\n returnString = \"Posted \" + mins + \" minute\" + (mins > 1 ? \"s\" : \"\") + \" ago\";\n } else {\n returnString = \"Posted less than a minute ago\";\n }\n }\n }\n }\n\n return returnString;\n }\n\n\n @Override\n public String toString() {\n return \"PasteItem{\" +\n \"imageLocation='\" + imageLocation + '\\'' +\n \", itemId='\" + itemId + '\\'' +\n \", content='\" + content + '\\'' +\n \", type='\" + type + '\\'' +\n \", timestamp=\" + timestamp +\n \", abuseCount=\" + abuseCount +\n \", privateFlag=\" + privateFlag +\n \", parent='\" + parent + '\\'' +\n \", clientIp='\" + clientIp + '\\'' +\n \", viewCount=\" + viewCount +\n \", pasteIndex=\" + pasteIndex +\n '}';\n }\n}", "public interface PasteService {\n\n List<PasteItem> getLatestItems(int count, int startIndex);\n\n List<PasteItem> getLatestItems(int count, int startIndex, String filter);\n\n PasteItem getItem(String id);\n\n String createItem(PasteItem item);\n\n String createItem(PasteItem item, boolean twitter);\n\n String createReplyItem(PasteItem item, String parentId)\n throws ParentNotFoundException;\n\n long getLatestItemsCount();\n\n int incViewCount(PasteItem pasteItem);\n\n void increaseAbuseCount(PasteItem pasteItem);\n\n void decreaseAbuseCount(PasteItem pasteItem);\n\n List<PasteItem> hasChildren(PasteItem pasteItem);\n\n String getAdminPassword();\n\n void appendIpAddress(String ipAddress);\n}", "public class HighlighterPanel extends Panel {\n private static final long serialVersionUID = 1L;\n\n\n private static List<LanguageSyntax> types\n = new ArrayList<LanguageSyntax>();\n\n static {\n types.add(new LanguageSyntax(\"as3\", \"Applescript\", \"shBrushAS3.js\"));\n types.add(new LanguageSyntax(\"bash\", \"Bash\", \"shBrushBash.js\"));\n types.add(new LanguageSyntax(\"csharp\", \"C#\", \"shBrushCSharp.js\"));\n types.add(new LanguageSyntax(\"cpp\", \"C / C++\", \"shBrushCpp.js\"));\n types.add(new LanguageSyntax(\"css\", \"CSS\", \"shBrushCss.js\"));\n types.add(new LanguageSyntax(\"delphi\", \"Delphi\", \"shBrushDelphi.js\"));\n types.add(new LanguageSyntax(\"diff\", \"Diff\", \"shBrushDiff.js\"));\n types.add(new LanguageSyntax(\"groovy\", \"Groovy\", \"shBrushGroovy.js\"));\n types.add(new LanguageSyntax(\"java\", \"Java\", \"shBrushJava.js\"));\n types.add(new LanguageSyntax(\"js\", \"JavaScript\", \"shBrushJScript.js\"));\n types.add(new LanguageSyntax(\"javafx\", \"JavaFX\", \"shBrushJavaFX.js\"));\n types.add(new LanguageSyntax(\"perl\", \"Perl\", \"shBrushPerl.js\"));\n types.add(new LanguageSyntax(\"php\", \"PHP\", \"shBrushPhp.js\"));\n types.add(new LanguageSyntax(\"text\", \"Plain Text\", \"shBrushPlain.js\"));\n types.add(new LanguageSyntax(\"powershell\", \"PowerShell\", \"shBrushPowerShell.js\"));\n types.add(new LanguageSyntax(\"python\", \"Python\", \"shBrushPython.js\"));\n types.add(new LanguageSyntax(\"ruby\", \"Ruby\", \"shBrushRuby.js\"));\n types.add(new LanguageSyntax(\"scala\", \"Scala\", \"shBrushScala.js\"));\n types.add(new LanguageSyntax(\"sql\", \"SQL\", \"shBrushSql.js\"));\n types.add(new LanguageSyntax(\"vb\", \"VB / VB.NET\", \"shBrushVb.js\"));\n types.add(new LanguageSyntax(\"xml\", \"XML / XHTML\", \"shBrushXml.js\"));\n }\n\n\n public static List<LanguageSyntax> getLanguageSyntaxList() {\n return types;\n }\n\n public static LanguageSyntax getLanguageSyntax(String language) {\n for (LanguageSyntax syntax : types) {\n if (syntax.getLanguage().equals(language)) {\n return syntax;\n }\n }\n\n return null;\n }\n\n public static String getLanguageScript(String language) {\n for (LanguageSyntax syntax : types) {\n if (syntax.getLanguage().equals(language)) {\n return syntax.getScript();\n }\n }\n\n return null;\n }\n\n public HighlighterPanel(String id, IModel<String> model) {\n this(id, model, null);\n }\n\n public HighlighterPanel(String id, IModel<String> model, String language) {\n this(id, model, language, false, null);\n }\n\n public HighlighterPanel(String id, IModel<String> model, String language, boolean excludeExternalResources) {\n this(id, model, language, excludeExternalResources, null);\n }\n\n public HighlighterPanel(String id, IModel<String> model, String language, final boolean excludeExternalResources, String highlightLines) {\n this(id, model, language, excludeExternalResources, highlightLines, null);\n }\n\n\n public void renderHead(IHeaderResponse response) {\n response.render(CssHeaderItem.forReference(new CssResourceReference(HighlighterPanel.class, \"shCore.css\")));\n response.render(CssHeaderItem.forReference(new CssResourceReference(HighlighterPanel.class, \"shThemeDefault.css\")));\n }\n\n private String language;\n\n /**\n *\n *\n * @param id\n * @param model\n * @param localLanguage\n * @param highlightLines\n */\n public HighlighterPanel(String id, final IModel<String> model, String localLanguage, final boolean excludeExternalResources, String highlightLines, final List<Integer> changedLines) {\n super(id);\n\n this.language = localLanguage;\n\n if (language == null || getLanguageScript(language) == null) language = \"text\";\n\n Label codePanel = new Label(\"code\", model);\n codePanel.add(new Behavior() {\n\n @Override\n public void beforeRender(Component component) {\n\n ResourceReference highlighterCoreResource = new PackageResourceReference(HighlighterPanel.class, \"shCore.js\");\n IRequestHandler highlighterCoreHandler = new ResourceReferenceRequestHandler(highlighterCoreResource);\n\n ResourceReference highlighterLanguageResource = new PackageResourceReference(HighlighterPanel.class, getLanguageScript(language));\n IRequestHandler highlighterLanguageHandler = new ResourceReferenceRequestHandler(highlighterLanguageResource);\n\n\n JavaScriptUtils.writeJavaScriptUrl(component.getResponse(), RequestCycle.get().urlFor(highlighterCoreHandler));\n JavaScriptUtils.writeJavaScriptUrl(component.getResponse(), RequestCycle.get().urlFor(highlighterLanguageHandler));\n JavaScriptUtils.writeJavaScript(component.getResponse(), \"SyntaxHighlighter.defaults['auto-links'] = false;\");\n JavaScriptUtils.writeJavaScript(component.getResponse(), \"SyntaxHighlighter.all();\");\n }\n });\n add(codePanel);\n\n StringBuffer brushConfig = new StringBuffer(\"brush: \");\n brushConfig.append(language);\n brushConfig.append(\"; toolbar: false\");\n if (highlightLines != null)\n brushConfig.append(\"; highlight: [\").append(highlightLines).append(\"]\");\n\n codePanel.add(new AttributeModifier(\"class\", new Model<String>(brushConfig.toString())));\n }\n}", "public class BasePage extends WebPage {\n\n Class activePage;\n Mousetrap mousetrap;\n\n private static final Logger logger = LoggerFactory.getLogger(BasePage.class);\n\n public BasePage() {\n init();\n }\n\n public BasePage(Class activePage) {\n this.activePage = activePage;\n init();\n }\n\n public BasePage(PageParameters params) {\n super(params);\n init();\n }\n\n protected String getTitle() {\n return \"Mystic Paste\";\n }\n\n protected Mousetrap mousetrap() {\n return mousetrap;\n }\n\n private void init() {\n\n add(new HtmlTag(\"html\"));\n\n add(new OptimizedMobileViewportMetaTag(\"viewport\"));\n add(new ChromeFrameMetaTag(\"chrome-frame\"));\n add(new MetaTag(\"description\", Model.of(\"description\"), Model.of(\"Mystic Paste\")));\n add(new MetaTag(\"author\", Model.of(\"author\"), Model.of(\"Andrew Lombardi\")));\n\n add(newNavbar(\"navbar\"));\n add(new Footer(\"footer\"));\n\n add(mousetrap = new Mousetrap());\n add(new HelpModal(\"helpModal\", \"Help\"));\n\n add(new GoogleAnalyticsSnippet(\"ga-js\") {\n public String getTracker() {\n return \"UA-254925-6\";\n }\n\n public boolean isVisible() {\n return true;\n }\n });\n\n final AbstractDefaultAjaxBehavior newNav = new AbstractDefaultAjaxBehavior() {\n @Override\n protected void respond(AjaxRequestTarget target) {\n System.out.println(\"newNav\");\n throw new RestartResponseException(PasteItemPage.class);\n }\n };\n add(newNav);\n\n final AbstractDefaultAjaxBehavior historyNav = new AbstractDefaultAjaxBehavior() {\n @Override\n protected void respond(AjaxRequestTarget target) {\n System.out.println(\"historyNav\");\n throw new RestartResponseException(HistoryPage.class);\n }\n };\n add(historyNav);\n\n// mousetrap.addBind(new KeyBinding().addKeyCombo(\"n\").addKeyCombo(\"N\"), newNav);\n\n String newPasteStr = \"Wicket.Ajax.get({'u': '\" + newNav.getCallbackUrl() + \"'})\";\n mousetrap.addBindJs(new KeyBinding().addKeyCombo(\"n\"), newPasteStr);\n mousetrap.addBind(new KeyBinding(KeyBinding.EVENT_KEYUP).addKeyCombo(\"h\").addKeyCombo(\"H\"),\n historyNav);\n /*\n mousetrap.addBindJs(new KeyBinding().addKeyCombo(\"?\"),\n \"$('#helpModal').modal();\"\n );\n */\n add(new BootstrapBaseBehavior());\n }\n\n /**\n * creates a new {@link Navbar} instance\n *\n * @param markupId The components markup id.\n * @return a new {@link Navbar} instance\n */\n protected Navbar newNavbar(String markupId) {\n Navbar navbar = new Navbar(markupId);\n navbar.setPosition(Navbar.Position.TOP);\n navbar.setInverted(false);\n\n // show brand name and logo\n navbar.brandName(Model.of(\"Mystic Paste\"));\n\n navbar.addComponents(NavbarComponents.transform(Navbar.ComponentPosition.LEFT,\n new NavbarButton<PasteItemPage>(PasteItemPage.class, Model.of(\"New\")),\n new NavbarButton<HistoryPage>(HistoryPage.class, Model.of(\"History\")),\n// new NavbarButton<PopularPage>(PopularPage.class, Model.of(\"Popular\")),\n new NavbarButton<PluginPage>(PluginPage.class, Model.of(\"Plugins\")),\n new NavbarButton<HelpPage>(HelpPage.class, Model.of(\"Help\"))\n ));\n\n return navbar;\n }\n\n @Override\n protected void onBeforeRender() {\n addOrReplace(new Label(\"title\", getTitle()));\n\n super.onBeforeRender();\n }\n\n @Override\n public void renderHead(IHeaderResponse response) {\n super.renderHead(response);\n\n response.render(CssHeaderItem.forReference(FixBootstrapStylesCssResourceReference.INSTANCE));\n response.render(JavaScriptHeaderItem.forReference(Application.get().getJavaScriptLibrarySettings().getJQueryReference()));\n response.render(JavaScriptHeaderItem.forReference(BootstrapJavaScriptReference.instance()));\n }\n\n /**\n * sets the theme for the current user.\n *\n * @param pageParameters current page parameters\n */\n private void configureTheme(PageParameters pageParameters) {\n StringValue theme = pageParameters.get(\"theme\");\n\n if (!theme.isEmpty()) {\n IBootstrapSettings settings = Bootstrap.getSettings(getApplication());\n settings.getActiveThemeProvider().setActiveTheme(theme.toString(\"\"));\n }\n }\n\n @Override\n protected void onConfigure() {\n super.onConfigure();\n\n configureTheme(getPageParameters());\n }\n\n /**\n * Returns the X-Forwarded-For header\n *\n * @return\n */\n protected String getClientIpAddress() {\n ServletWebRequest request = (ServletWebRequest) RequestCycle.get().getRequest();\n String ipAddress = request.getHeader(\"X-Forwarded-For\");\n if (ipAddress == null) {\n ipAddress = request.getContainerRequest().getRemoteHost();\n }\n return ipAddress;\n }\n\n protected String getReferrer() {\n ServletWebRequest request = (ServletWebRequest) RequestCycle.get().getRequest();\n\n return request.getHeader(\"referer\");\n }\n\n private String serverName;\n\n protected String getServerName() {\n return serverName;\n }\n\n}", "public class HistoryDataProvider implements IDataProvider<PasteItem> {\n\n PasteService pasteService;\n\n boolean visible = false;\n\n public HistoryDataProvider(PasteService pasteService) {\n this.pasteService = pasteService;\n }\n\n public Iterator<PasteItem> iterator(long first, long count) {\n return pasteService.getLatestItems((int)count, (int)first).iterator();\n }\n\n public long size() {\n int count = new Long(pasteService.getLatestItemsCount()).intValue();\n visible = count > 0;\n\n return count;\n }\n\n public boolean isVisible() {\n return visible;\n }\n\n public IModel<PasteItem> model(PasteItem pasteItem) {\n return new Model<PasteItem>(pasteItem);\n }\n\n /**\n * @see org.apache.wicket.model.IDetachable#detach()\n */\n public void detach() {\n }\n}", "public class PastePagingNavigator extends AjaxPagingNavigator {\n public PastePagingNavigator(String id, IPageable pageable) {\n super(id, pageable);\n }\n\n public PastePagingNavigator(String id, IPageable pageable, IPagingLabelProvider labelProvider) {\n super(id, pageable, labelProvider);\n }\n\n private PastePagingNavigator dependentNavigator;\n public void setDependentNavigator(PastePagingNavigator dependentNavigator) {\n this.dependentNavigator = dependentNavigator;\n }\n\n protected void onAjaxEvent(AjaxRequestTarget target) {\n super.onAjaxEvent(target);\n\n if(dependentNavigator!=null) {\n target.add(dependentNavigator);\n }\n \t}\n\n/*\n protected PagingNavigation newNavigation(final String id, final IPageable pageable, final IPagingLabelProvider labelProvider) {\n PagingNavigation navigation = super.newNavigation(id, pageable, labelProvider);\n navigation.setRenderBodyOnly(true);\n navigation.setOutputMarkupPlaceholderTag(false);\n return navigation;\n \t}\n*/\n}", "public class ViewPublicPage extends ViewPastePage {\n\n @SpringBean\n PasteService pasteService;\n\n private final Logger logger = LoggerFactory.getLogger(getClass());\n\n public ViewPublicPage(PageParameters params) {\n super(params);\n\n logger.info(\"Client [\"+ getClientIpAddress() +\"] viewing paste with ID[\"+getPasteItem().getItemId()+\"]\");\n pasteService.appendIpAddress(getClientIpAddress());\n }\n\n protected IModel<PasteItem> getPasteModel(String id) {\n return new PasteModel(id);\n }\n\n @Override\n protected boolean isPublic() {\n return true;\n }\n\n private class PasteModel extends LoadableDetachableModel<PasteItem> {\n\n String id;\n\n public PasteModel(String id) {\n this.id = id;\n }\n\n protected PasteItem load() {\n return pasteService.getItem(id);\n }\n }\n\n}" ]
import com.mysticcoders.mysticpaste.model.PasteItem; import com.mysticcoders.mysticpaste.services.PasteService; import com.mysticcoders.mysticpaste.web.components.highlighter.HighlighterPanel; import com.mysticcoders.mysticpaste.web.pages.BasePage; import com.mysticcoders.mysticpaste.web.pages.history.HistoryDataProvider; import com.mysticcoders.mysticpaste.web.pages.history.PastePagingNavigator; import com.mysticcoders.mysticpaste.web.pages.view.ViewPublicPage; import org.apache.wicket.RestartResponseException; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.authroles.authorization.strategies.role.Roles; import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.markup.html.pages.AccessDeniedPage; import org.apache.wicket.markup.repeater.Item; import org.apache.wicket.markup.repeater.data.DataView; import org.apache.wicket.model.PropertyModel; import org.apache.wicket.request.IRequestParameters; import org.apache.wicket.request.http.flow.AbortWithHttpErrorCodeException; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean;
package com.mysticcoders.mysticpaste.web.pages.admin; /** * Paste Admin * * @author Andrew Lombardi <andrew@mysticcoders.com> */ public class OverviewPage extends BasePage { @SpringBean PasteService pasteService; DataView historyDataView; private final int ITEMS_PER_PAGE = 50; private int itemsPerPage; protected String getTitle() { return "Paste Admin - Mystic Paste"; } public OverviewPage() { super(OverviewPage.class); IRequestParameters params = getRequestCycle().getRequest().getQueryParameters(); String pw = pasteService.getAdminPassword(); if(pw == null || params.getParameterValue("pw").isEmpty() || !params.getParameterValue("pw").toString().equals(pw)) { throw new RestartResponseException(AccessDeniedPage.class); } itemsPerPage = params.getParameterValue("itemsPerPage").toInt(ITEMS_PER_PAGE); /* if(!params.getParameterValue("itemsPerPage").isEmpty()) { } else { itemsPerPage = ITEMS_PER_PAGE; } */
final HistoryDataProvider historyDataProvider = new HistoryDataProvider(pasteService);
4
zhouruikevin/ImageLoadPK
imageloadpk/src/main/java/com/example/imageloadpk/model/MainActivity.java
[ "public class FrescoAdapter extends ImageListAdapter {\n\n\n public FrescoAdapter(Context context, WatchListener watchListener) {\n super(context, watchListener);\n Fresco.initialize(context, FrescoConfigFactory.getImagePipelineConfig(context));\n }\n\n @Override\n public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n GenericDraweeHierarchy genericDraweeHierarchy = new GenericDraweeHierarchyBuilder(getContext().getResources())\n .setPlaceholderImage(Drawables.sPlaceholderDrawable)\n .setFailureImage(Drawables.sErrorDrawable)\n// .setProgressBarImage(new ProgressBarDrawable())\n .setActualImageScaleType(ScalingUtils.ScaleType.CENTER_CROP)\n .build();\n WatchDraweeImage watchDraweeImage = new WatchDraweeImage(getContext(), genericDraweeHierarchy);\n return new FrescoHolder(watchDraweeImage, getWatchListener(), parent, getContext());\n }\n\n @Override\n public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {\n FrescoHolder frescoHolder = (FrescoHolder) holder;\n frescoHolder.bind(getItem(position));\n }\n\n @Override\n public void clear() {\n Fresco.shutDown();\n }\n}", "public class GlideAdapter extends ImageListAdapter {\n public GlideAdapter(Context context, WatchListener watchListener) {\n super(context, watchListener);\n }\n\n @Override\n public GlideHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n final WatchImageView watchImageView = new WatchImageView(getContext());\n return new GlideHolder(watchImageView, getWatchListener(), parent, getContext());\n }\n\n @Override\n public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {\n GlideHolder glideHolder = (GlideHolder) holder;\n glideHolder.bind(getItem(position));\n }\n\n @Override\n public void clear() {\n Glide.get(getContext()).clearMemory();\n }\n}", "public abstract class ImageListAdapter extends RecyclerView.Adapter {\n private final Context mContext;\n private List<String> mDatas;\n private final WatchListener mWatchListener;\n\n public ImageListAdapter(Context context, WatchListener watchListener) {\n mContext = context;\n mWatchListener = watchListener;\n mDatas = new ArrayList<>();\n }\n\n protected void addUrl(String url) {\n mDatas.add(url);\n }\n\n public void setDatas() {\n Collections.addAll(mDatas, Data.URLS);\n List<String> copyDatas = new ArrayList<>(mDatas);\n }\n\n public void setRandomDatas() {\n Collections.addAll(mDatas, Data.URLS);\n Collections.shuffle(mDatas);\n List<String> copyDatas = new ArrayList<>(mDatas);\n mDatas.addAll(copyDatas);\n mDatas.addAll(copyDatas);\n }\n\n protected Context getContext() {\n return mContext;\n }\n\n protected WatchListener getWatchListener() {\n return mWatchListener;\n }\n\n public String getItem(final int position) {\n return mDatas.get(position);\n }\n\n @Override\n public int getItemCount() {\n return mDatas == null ? 0 : mDatas.size();\n }\n\n public abstract void clear();\n\n}", "public class ImageLoaderAdapter extends ImageListAdapter {\n\n final private ImageLoader mImageLoader;\n\n public ImageLoaderAdapter(Context context, WatchListener watchListener) {\n super(context, watchListener);\n mImageLoader = ImageLoaderFactory.getImageLoader(context);\n }\n\n @Override\n public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n WatchImageView watchImageView = new WatchImageView(getContext());\n return new ImageLoaderHolder(watchImageView, getWatchListener(), parent, getContext(), mImageLoader);\n }\n\n @Override\n public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {\n ImageLoaderHolder imageLoaderHolder = (ImageLoaderHolder) holder;\n imageLoaderHolder.bind(getItem(position));\n }\n\n @Override\n public void clear() {\n mImageLoader.clearMemoryCache();\n }\n\n}", "public class PicassoAdapter extends ImageListAdapter {\n private Picasso mPicasso;\n\n public PicassoAdapter(Context context, WatchListener watchListener) {\n super(context, watchListener);\n if (mPicasso == null) {\n mPicasso = PicassoConfigFactory.getPicasso(context);\n }\n }\n\n @Override\n public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n WatchImageView watchImageView = new WatchImageView(getContext());\n return new PicassoHolder(watchImageView, getWatchListener(), parent, getContext(), mPicasso);\n }\n\n @Override\n public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {\n PicassoHolder picassoHolder = (PicassoHolder) holder;\n picassoHolder.bind(getItem(position));\n }\n\n @Override\n public void clear() {\n for (int i = 0; i < getItemCount(); i++) {\n mPicasso.invalidate(getItem(i));\n }\n }\n}", "public class Drawables {\n public static Drawable sPlaceholderDrawable;\n public static Drawable sErrorDrawable;\n\n private Drawables() {\n }\n\n public static void init(final Resources resources) {\n if (sPlaceholderDrawable == null) {\n sPlaceholderDrawable = resources.getDrawable(R.drawable.placeholder, null);\n }\n if (sErrorDrawable == null) {\n sErrorDrawable = resources.getDrawable(R.drawable.error, null);\n }\n }\n}", "public class WatchListener {\n private long mRequestTotalTime;\n private long mStartRequests;\n private long mSuccessedRequests;\n private long mFailedRequests;\n private long mCancelledRequests;\n\n public void reportSuccess(long requestTime) {\n mRequestTotalTime += requestTime;\n mSuccessedRequests++;\n }\n\n public void initData() {\n mRequestTotalTime = 0;\n mStartRequests = 0;\n mSuccessedRequests = 0;\n mFailedRequests = 0;\n mCancelledRequests = 0;\n }\n\n public void reportStart() {\n mStartRequests++;\n }\n\n public void reportCancelltion(long requestTime) {\n mCancelledRequests++;\n mRequestTotalTime += requestTime;\n }\n\n public void reportFailure(long requestTime) {\n mFailedRequests++;\n mRequestTotalTime += requestTime;\n }\n\n\n public long getAverageRequestTime() {\n final long completedRequests = getCompletedRequests();\n return completedRequests > 0 ? mRequestTotalTime / completedRequests : 0;\n }\n\n public long getCancelledRequests() {\n return mCancelledRequests;\n }\n\n public long getCompletedRequests() {\n return mSuccessedRequests + mCancelledRequests + mFailedRequests;\n }\n\n public long getTotalRequests() {\n return mStartRequests;\n }\n}" ]
import android.os.Bundle; import android.os.Handler; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.RadioButton; import android.widget.TextView; import com.example.imageloadpk.R; import com.example.imageloadpk.adapter.adapters.FrescoAdapter; import com.example.imageloadpk.adapter.adapters.GlideAdapter; import com.example.imageloadpk.adapter.adapters.ImageListAdapter; import com.example.imageloadpk.adapter.adapters.ImageLoaderAdapter; import com.example.imageloadpk.adapter.adapters.PicassoAdapter; import com.example.imageloadpk.adapter.watcher.Drawables; import com.example.imageloadpk.adapter.watcher.WatchListener; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick;
package com.example.imageloadpk.model; public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; @Bind(R.id.recyclerView) RecyclerView mRecyclerView; @Bind(R.id.refreshLayout) SwipeRefreshLayout mRefreshLayout; @Bind(R.id.tvShowInfo) TextView mTvShowInfo; @Bind(R.id.rbGlide) RadioButton mRbGlide; @Bind(R.id.rbPicasso) RadioButton mRbPicasso; @Bind(R.id.rbImageLoad) RadioButton mRbImageLoad; @Bind(R.id.rbFresco) RadioButton mRbFresco; private GlideAdapter mAdapter; private WatchListener mWatchListener; private Handler mHandler; private Runnable mRunnable = new Runnable() { @Override public void run() { upTvShowInfo(); scheduleNextShow(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); mHandler = new Handler(getMainLooper()); initView(); } @Override protected void onStart() { super.onStart(); scheduleNextShow(); } @Override protected void onStop() { super.onStop(); upTvShowInfo(); cancelScheduleRunnable(); } private void initView() { Drawables.init(getResources()); mWatchListener = new WatchListener(); mRecyclerView.setLayoutManager(new GridLayoutManager(this, 2)); mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { clearOtherLoader(); mRefreshLayout.setRefreshing(false); } }); } private void scheduleNextShow() { mHandler.postDelayed(mRunnable, 1000); } private void cancelScheduleRunnable() { mHandler.removeCallbacks(mRunnable); } public final static long MB = 1024 * 1024; private void upTvShowInfo() { final Runtime runtime = Runtime.getRuntime(); final float totalMemory = (runtime.totalMemory()) / MB; final float heapMemory = (runtime.totalMemory() - runtime.freeMemory()) / MB; String heapStr = String.format("已使用内存:%.1f M\t总共:%.1f M\n", heapMemory, totalMemory); String formatStr = "平均请求时间:%dms\t 总共加载次数:%d\t已完成次数:%d\t取消次数:%d"; String result = String.format(formatStr, mWatchListener.getAverageRequestTime(), mWatchListener.getTotalRequests(), mWatchListener.getCompletedRequests(), mWatchListener.getCancelledRequests()); mTvShowInfo.setText(heapStr + result); } @OnClick({R.id.rbGlide, R.id.rbPicasso, R.id.rbImageLoad, R.id.rbFresco}) public void onClick(View view) { clearOtherLoader(); switch (view.getId()) { case R.id.rbGlide: loadData(new GlideAdapter(this, mWatchListener)); break; case R.id.rbPicasso: loadData(new PicassoAdapter(this, mWatchListener)); break; case R.id.rbImageLoad: loadData(new ImageLoaderAdapter(this, mWatchListener)); break; case R.id.rbFresco:
loadData(new FrescoAdapter(this, mWatchListener));
0
RedditAndroidDev/Tamagotchi
Tamagotchi/src/com/redditandroiddevelopers/tamagotchi/TamagotchiConfiguration.java
[ "public class CreatureDao {\n private CommonDatabase<Creature> db;\n private Mapper<Creature> rowMapper;\n\n public CreatureDao(CommonDatabase<Creature> database,\n Mapper<Creature> mapper) {\n db = database;\n rowMapper = mapper;\n }\n\n public Creature create(Creature creature) {\n return db.insert(creature, CommonDatabase.INFO_TABLE_NAME);\n }\n\n public Creature update(Creature creature) {\n db.update(CommonDatabase.INFO_TABLE_NAME, creature, \"CI_ID = \"\n + creature.id, null);\n return creature;\n }\n\n public void delete(Creature creature) {\n db.delete(CommonDatabase.INFO_TABLE_NAME, \"CI_ID = \" + creature.id,\n null);\n }\n\n public boolean isDatabaseEmpty() {\n List<Creature> c = db.queryList(rowMapper,\n CommonDatabase.INFO_TABLE_NAME, null, null, null, null, null,\n null);\n if (c == null) {\n return true;\n }\n return false;\n }\n\n// public void seedData() {\n// // TODO: debug guard\n// db.seedData();\n// }\n//\n// public void purgeData() {\n// // TODO: debug guard\n// db.deleteDatabase();\n// }\n\n public List<Creature> getAll() {\n return db\n .queryList(\n rowMapper,\n \"CREATURE_INFO join CREATURE_TYPE on (CREATURE_INFO.CT_ID = CREATURE_TYPE.CT_ID)\",\n null, null, null, null, null, null);\n }\n\n public int getNumberOfAlive() {\n return db.getResultCount(CommonDatabase.INFO_TABLE_NAME, null,\n \"CI_ALIVE = 1\", null, null, null, null);\n }\n\n public Creature findById(long id) {\n return db\n .queryUnique(\n rowMapper,\n \"CREATURE_INFO join CREATURE_TYPE on (CREATURE_INFO.CT_ID = CREATURE_TYPE.CT_ID)\",\n null, \"CI_ID = \" + id, null, null, null, null);\n }\n}", "public class CreatureEvolutionDao {\n private CommonDatabase<CreatureEvolution> db;\n Mapper<CreatureEvolution> rowMapper;\n\n public CreatureEvolutionDao(CommonDatabase<CreatureEvolution> database,\n Mapper<CreatureEvolution> mapper) {\n db = database;\n rowMapper = mapper;\n }\n\n public CreatureEvolution create(CreatureEvolution evo) {\n return db.insert(evo, CommonDatabase.EVOLUTION_TABLE_NAME);\n }\n\n public CreatureEvolution update(CreatureEvolution evo) {\n db.update(CommonDatabase.EVOLUTION_TABLE_NAME, evo, \"CE_ID = \"\n + evo.id, null);\n return evo;\n }\n\n public void delete(CreatureEvolution evo) {\n db.delete(CommonDatabase.EVOLUTION_TABLE_NAME, \"CE_ID = \" + evo.id,\n null);\n }\n\n public List<CreatureEvolution> getAll() {\n return db\n .queryList(\n rowMapper,\n \"CREATURE_EVOLUTION join CREATURE_TYPE on (CREATURE_EVOLUTION.CT_ID = CREATURE_TYPE.CT_ID)\",\n null, null, null, null, null, null);\n }\n\n public CreatureEvolution findById(long id) {\n return db\n .queryUnique(\n rowMapper,\n \"CREATURE_EVOLUTION join CREATURE_TYPE on (CREATURE_EVOLUTION.CT_ID = CREATURE_TYPE.CT_ID)\",\n null, \"CE_ID = \" + id, null, null, null, null);\n }\n}", "public class CreatureRaiseTypeDao {\n private CommonDatabase<CreatureRaiseType> db;\n private Mapper<CreatureRaiseType> rowMapper;\n\n public CreatureRaiseTypeDao(CommonDatabase<CreatureRaiseType> database,\n Mapper<CreatureRaiseType> mapper) {\n db = database;\n rowMapper = mapper;\n }\n\n public CreatureRaiseType create(CreatureRaiseType crt) {\n return db.insert(crt, CommonDatabase.RAISE_TYPE_TABLE_NAME);\n }\n\n public CreatureRaiseType update(CreatureRaiseType crt) {\n db.update(CommonDatabase.RAISE_TYPE_TABLE_NAME, crt, \"CRT_ID = \"\n + crt.id, null);\n return crt;\n }\n\n public void delete(CreatureRaiseType crt) {\n db.delete(CommonDatabase.RAISE_TYPE_TABLE_NAME, \"CRT_ID = \" + crt.id,\n null);\n }\n\n public List<CreatureRaiseType> getAll() {\n return db.queryList(rowMapper, CommonDatabase.RAISE_TYPE_TABLE_NAME,\n null, null, null, null, null, null);\n }\n\n public CreatureRaiseType findById(long id) {\n return db.queryUnique(rowMapper,\n CommonDatabase.RAISE_TYPE_TABLE_NAME, null, \"CRT_ID = \" + id,\n null, null, null, null);\n }\n}", "public class CreatureStateDao {\n private CommonDatabase<CreatureState> db;\n private Mapper<CreatureState> rowMapper;\n private static final String SELECT_JOIN = CommonDatabase.STATE_TABLE_NAME\n + \" join \" + CommonDatabase.RAISE_TYPE_TABLE_NAME + \" on ( \"\n + CommonDatabase.STATE_TABLE_NAME + \".CRT_ID = \"\n + CommonDatabase.RAISE_TYPE_TABLE_NAME + \".CRT_ID ) join \"\n + CommonDatabase.INFO_TABLE_NAME + \" on ( \"\n + CommonDatabase.STATE_TABLE_NAME + \".CI_ID = \"\n + CommonDatabase.INFO_TABLE_NAME + \".CI_ID ) join \"\n + CommonDatabase.SICKNESS_TABLE_NAME + \" on ( \"\n + CommonDatabase.STATE_TABLE_NAME + \".S_ID = \"\n + CommonDatabase.SICKNESS_TABLE_NAME + \".S_ID ) join \"\n + CommonDatabase.TYPE_TABLE_NAME + \" on ( \"\n + CommonDatabase.INFO_TABLE_NAME + \".CT_ID = \"\n + CommonDatabase.TYPE_TABLE_NAME + \".CT_ID ) join \"\n + CommonDatabase.MEDICINE_TABLE_NAME + \" on ( \"\n + CommonDatabase.SICKNESS_TABLE_NAME + \".M_ID = \"\n + CommonDatabase.MEDICINE_TABLE_NAME + \".M_ID )\";\n\n public CreatureStateDao(CommonDatabase<CreatureState> database,\n Mapper<CreatureState> mapper) {\n db = database;\n rowMapper = mapper;\n }\n\n public CreatureState create(CreatureState state) {\n return db.insert(state, CommonDatabase.STATE_TABLE_NAME);\n }\n\n public CreatureState update(CreatureState state) {\n db.update(CommonDatabase.STATE_TABLE_NAME, state, \"CS_ID = \"\n + state.id, null);\n return state;\n }\n\n public void delete(CreatureState state) {\n db.delete(CommonDatabase.STATE_TABLE_NAME, \"CS_ID = \" + state.id,\n null);\n }\n\n public List<CreatureState> getAll() {\n return db.queryList(rowMapper, SELECT_JOIN, null, null, null, null,\n null, null);\n }\n\n public CreatureState findById(long id) {\n return db.queryUnique(rowMapper, SELECT_JOIN, null, \"CS_ID = \" + id,\n null, null, null, null);\n }\n}", "public class ExperienceActionDao {\n private CommonDatabase<ExperienceAction> db;\n private Mapper<ExperienceAction> rowMapper;\n \n public ExperienceActionDao(CommonDatabase<ExperienceAction> database,\n Mapper<ExperienceAction> mapper) {\n db = database;\n rowMapper = mapper;\n }\n \n public ExperienceAction create(ExperienceAction exp) {\n return db.insert(exp, CommonDatabase.EXPERIENCE_ACTION_TABLE_NAME);\n }\n \n public ExperienceAction update(ExperienceAction exp) {\n db.update(CommonDatabase.EXPERIENCE_ACTION_TABLE_NAME, \n exp, \n \"EA_ID = \" + exp.id, \n null);\n return exp;\n }\n \n public void delete(ExperienceAction exp) {\n db.delete(CommonDatabase.EXPERIENCE_ACTION_TABLE_NAME, \n \"EA_ID = \" + exp.id, \n null);\n }\n \n public List<ExperienceAction> getAll() {\n return db.queryList(rowMapper, CommonDatabase.EXPERIENCE_ACTION_TABLE_NAME + \" join \"\n + CommonDatabase.TYPE_TABLE_NAME + \" on (\"\n + CommonDatabase.EXPERIENCE_ACTION_TABLE_NAME + \".CT_ID = \"\n + CommonDatabase.TYPE_TABLE_NAME + \".CT_ID )\" + \" join \"\n + CommonDatabase.ACTION_TABLE_NAME + \" on (\"\n + CommonDatabase.EXPERIENCE_ACTION_TABLE_NAME + \".CA_ID = \"\n + CommonDatabase.ACTION_TABLE_NAME + \".CA_ID )\", null, null,\n null, null, null, null);\n }\n \n public ExperienceAction findExperienceById(long id) {\n return db.queryUnique(rowMapper, CommonDatabase.EXPERIENCE_ACTION_TABLE_NAME, null, \n \"EA_ID = \" + id, null, null, null, null);\n }\n}", "public class MedicineDao {\n private CommonDatabase<Medicine> db;\n private Mapper<Medicine> rowMapper;\n\n public MedicineDao(CommonDatabase<Medicine> database,\n Mapper<Medicine> mapper) {\n db = database;\n rowMapper = mapper;\n }\n\n public Medicine create(Medicine m) {\n return db.insert(m, CommonDatabase.MEDICINE_TABLE_NAME);\n }\n\n public Medicine update(Medicine m) {\n db.update(CommonDatabase.MEDICINE_TABLE_NAME, m, \"M_ID = \" + m.id,\n null);\n return m;\n }\n\n public List<Medicine> getAll() {\n return db.queryList(rowMapper, CommonDatabase.MEDICINE_TABLE_NAME,\n null, null, null, null, null, null);\n }\n\n public Medicine findById(long id) {\n return db.queryUnique(rowMapper, CommonDatabase.MEDICINE_TABLE_NAME,\n null, \"M_ID = \" + id, null, null, null, null);\n }\n}", "public class SicknessDao {\n private CommonDatabase<Sickness> db;\n private Mapper<Sickness> rowMapper;\n\n public SicknessDao(CommonDatabase<Sickness> database,\n Mapper<Sickness> mapper) {\n db = database;\n rowMapper = mapper;\n }\n\n /*\n * Sickness\n */\n public Sickness create(Sickness sickness) {\n return db.insert(sickness, CommonDatabase.SICKNESS_TABLE_NAME);\n }\n\n public Sickness update(Sickness sickness) {\n db.update(CommonDatabase.SICKNESS_TABLE_NAME,\n sickness, \"S_ID = \" + sickness.id, null);\n return sickness;\n }\n\n public void delete(Sickness sickness) {\n db.delete(CommonDatabase.SICKNESS_TABLE_NAME,\n \"S_ID = \" + sickness.id, null);\n }\n\n public List<Sickness> getAll() {\n return db.queryList(rowMapper, CommonDatabase.SICKNESS_TABLE_NAME + \" join \"\n + CommonDatabase.MEDICINE_TABLE_NAME + \" on (\"\n + CommonDatabase.SICKNESS_TABLE_NAME + \".M_ID = \"\n + CommonDatabase.MEDICINE_TABLE_NAME + \".M_ID )\", null, null,\n null, null, null, null);\n }\n\n public Sickness findById(long id) {\n return db.queryUnique(rowMapper, CommonDatabase.SICKNESS_TABLE_NAME + \" join \"\n + CommonDatabase.MEDICINE_TABLE_NAME + \" on (\"\n + CommonDatabase.SICKNESS_TABLE_NAME + \".M_ID = \"\n + CommonDatabase.MEDICINE_TABLE_NAME + \".M_ID )\", null,\n \"S_ID = \" + id, null, null, null, null);\n }\n}" ]
import com.badlogic.gdx.Application; import com.badlogic.gdx.graphics.Color; import com.redditandroiddevelopers.tamagotchi.dao.CreatureDao; import com.redditandroiddevelopers.tamagotchi.dao.CreatureEvolutionDao; import com.redditandroiddevelopers.tamagotchi.dao.CreatureRaiseTypeDao; import com.redditandroiddevelopers.tamagotchi.dao.CreatureStateDao; import com.redditandroiddevelopers.tamagotchi.dao.ExperienceActionDao; import com.redditandroiddevelopers.tamagotchi.dao.MedicineDao; import com.redditandroiddevelopers.tamagotchi.dao.SicknessDao;
package com.redditandroiddevelopers.tamagotchi; /** * A place to store runtime configuration for use throughout the lifetime of a * {@link TamagotchiGame} object. Not to be confused with a store for game * settings. * * @author Santoso Wijaya */ public class TamagotchiConfiguration { public boolean debug = true; public boolean logFps = true; public int logLevel = Application.LOG_DEBUG; public float stageWidth = 800; public float stageHeight = 480; public Color defaultBackgroundColor = new Color(226f / 255f, 232f / 255f, 254f / 255f, 1f); public Color creatureCreationBackgroundColor = new Color(42f / 255f, 42f / 255f, 42f / 255f, 1f); // Persistence public CreatureDao creatureDao; public CreatureEvolutionDao creatureEvolutionDao; public CreatureRaiseTypeDao creatureRaiseTypeDao; public CreatureStateDao creatureStateDao; public ExperienceActionDao experienceActionDao; public MedicineDao medicineDao;
public SicknessDao sicknessDao;
6
kennylbj/concurrent-java
src/main/java/producerconsumer/Main.java
[ "public class BlockingQueueConsumer implements Consumer<Item>, Runnable {\n private final BlockingQueue<Item> buffer;\n private final Random random = new Random(System.nanoTime());\n\n public BlockingQueueConsumer(BlockingQueue<Item> buffer) {\n this.buffer = buffer;\n }\n\n @Override\n public void run() {\n try {\n while (!Thread.currentThread().isInterrupted()) {\n Item item = buffer.take();\n consume(item);\n }\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n }\n\n @Override\n public void consume(Item item) {\n try {\n Thread.sleep(random.nextInt(3) * 1000);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n System.out.println(\"[BlockingQueue] Consumer consumes item \" + item.toString()\n + \" by thread \" + Thread.currentThread().getId());\n }\n}", "public class BlockingQueueProducer implements Producer<Item>, Runnable {\n private final BlockingQueue<Item> buffer;\n private final Random random = new Random(System.nanoTime());\n\n public BlockingQueueProducer(BlockingQueue<Item> buffer) {\n this.buffer = buffer;\n }\n\n @Override\n public void run() {\n try {\n while (!Thread.currentThread().isInterrupted()) {\n Item item = produce();\n buffer.put(item);\n }\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n }\n\n @Override\n public Item produce() {\n try {\n Thread.sleep(random.nextInt(3) * 1000);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n Item item = Item.generate();\n System.out.println(\"[BlockingQueue] Producer produces item \" + item.toString()\n + \" by thread \" + Thread.currentThread().getId());\n return item;\n }\n}", "public class ConditionConsumer implements Consumer<Item>, Runnable {\n @GuardedBy(\"lock\")\n private final Buffer<Item> buffer;\n private final Lock lock;\n private final Condition full;\n private final Condition empty;\n private final Random random = new Random(System.nanoTime());\n\n public ConditionConsumer(Buffer<Item> buffer, Lock lock, Condition full, Condition empty) {\n this.buffer = buffer;\n this.lock = lock;\n this.full = full;\n this.empty = empty;\n }\n\n @Override\n public void consume(Item item) {\n try {\n Thread.sleep(random.nextInt(3) * 1000);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n System.out.println(\"[Condition] Consumer consumes item \" + item.toString()\n + \" by thread \" + Thread.currentThread().getId());\n }\n\n @Override\n public void run() {\n try {\n while (!Thread.currentThread().isInterrupted()) {\n Item item;\n lock.lock();\n try {\n //buffer empty, so wait until no empty\n while (buffer.getSize() == 0) {\n empty.await();\n }\n item = buffer.popItem();\n\n if (buffer.getSize() == buffer.getCapacity() - 1) {\n full.signal();\n }\n } finally {\n lock.unlock();\n }\n //outside critical section\n consume(item);\n }\n } catch (InterruptedException e) {\n System.out.println(\"failed to consume items\");\n Thread.currentThread().interrupt();\n }\n }\n\n}", "public class ConditionProducer implements Producer<Item>, Runnable {\n @GuardedBy(\"lock\")\n private final Buffer<Item> buffer;\n private final Lock lock;\n private final Condition full;\n private final Condition empty;\n private final Random random = new Random(System.nanoTime());\n\n public ConditionProducer(Buffer<Item> buffer, Lock lock, Condition full, Condition empty) {\n this.buffer = buffer;\n this.lock = lock;\n this.full = full;\n this.empty = empty;\n }\n\n @Override\n public Item produce() {\n try {\n Thread.sleep(random.nextInt(3) * 1000);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n Item item = Item.generate();\n System.out.println(\"[Condition] Producer produces item \" + item.toString()\n + \" by thread \" + Thread.currentThread().getId());\n return item;\n }\n\n @Override\n public void run() {\n try {\n while (!Thread.currentThread().isInterrupted()) {\n //outside critical section\n Item item = produce();\n\n lock.lock();\n try {\n //buffer is full, so wait until no full\n while (buffer.getSize() == buffer.getCapacity()) {\n full.await();\n }\n buffer.putItem(item);\n //signal consumers when buffer size is one\n //to avoid herd effect\n if (buffer.getSize() == 1) {\n empty.signal();\n }\n } finally {\n lock.unlock();\n }\n }\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n }\n}", "public class SemaphoreConsumer implements Consumer<Item>, Runnable {\n @GuardedBy(\"buffer\")\n private final Buffer<Item> buffer;\n private final Semaphore fullCount;\n private final Semaphore emptyCount;\n private final Random random = new Random(System.nanoTime());\n\n public SemaphoreConsumer(Buffer<Item> buffer, Semaphore fullCount, Semaphore emptyCount) {\n this.buffer = buffer;\n this.fullCount = fullCount;\n this.emptyCount = emptyCount;\n }\n\n @Override\n public void consume(Item item) {\n try {\n Thread.sleep(random.nextInt(3) * 1000);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n System.out.println(\"[Semaphore] Consumer consumes item \" + item.toString()\n + \" by thread \" + Thread.currentThread().getId());\n }\n\n @Override\n public void run() {\n try {\n while (!Thread.currentThread().isInterrupted()) {\n fullCount.acquire();\n Item item;\n synchronized (buffer) {\n item = buffer.popItem();\n }\n emptyCount.release();\n consume(item);\n }\n } catch (InterruptedException e) {\n System.out.println(\"failed to consume\");\n Thread.currentThread().interrupt();\n }\n }\n}", "public class SemaphoreProducer implements Producer<Item>, Runnable {\n @GuardedBy(\"buffer\")\n private final Buffer<Item> buffer;\n private final Semaphore fullCount;\n private final Semaphore emptyCount;\n private final Random random = new Random(System.nanoTime());\n\n public SemaphoreProducer(Buffer<Item> buffer, Semaphore fullCount, Semaphore emptyCount) {\n this.buffer = buffer;\n this.fullCount = fullCount;\n this.emptyCount = emptyCount;\n }\n\n //produce operation may be time-consuming\n @Override\n public Item produce() {\n try {\n Thread.sleep(random.nextInt(3) * 1000);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n Item item = Item.generate();\n System.out.println(\"[Semaphore] Producer produces item \" + item.toString()\n + \" by thread \" + Thread.currentThread().getId());\n return item;\n }\n\n @Override\n public void run() {\n try {\n while (!Thread.currentThread().isInterrupted()) {\n Item item = produce();\n emptyCount.acquire();\n synchronized (buffer) {\n buffer.putItem(item);\n }\n fullCount.release();\n\n }\n } catch (InterruptedException e) {\n System.out.println(\"failed to produce\");\n Thread.currentThread().interrupt();\n }\n\n }\n}" ]
import producerconsumer.blockingqueue.BlockingQueueConsumer; import producerconsumer.blockingqueue.BlockingQueueProducer; import producerconsumer.condition.ConditionConsumer; import producerconsumer.condition.ConditionProducer; import producerconsumer.semaphore.SemaphoreConsumer; import producerconsumer.semaphore.SemaphoreProducer; import java.util.concurrent.*; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock;
package producerconsumer; /** * Created by kennylbj on 16/9/10. * Implement 3 versions of P/C * 1) use Semaphore * 2) use Condition * 3) use BlockingQueue * All versions support multiple producers and consumers */ public class Main { private static final int BUFFER_SIZE = 100; private static final int PRODUCER_NUM = 3; private static final int CONSUMER_NUM = 2; public static void main(String[] args) throws InterruptedException { ExecutorService pool = Executors.newCachedThreadPool(); // Buffers of all P/C Buffer<Item> semaphoreBuffer = new LinkListBuffer(BUFFER_SIZE); Buffer<Item> conditionBuffer = new LinkListBuffer(BUFFER_SIZE); BlockingQueue<Item> blockingQueueBuffer = new LinkedBlockingQueue<>(BUFFER_SIZE); // Semaphores for Semaphore version of P/C Semaphore fullCount = new Semaphore(0); Semaphore emptyCount = new Semaphore(BUFFER_SIZE); // Lock and conditions for Condition version of P/C Lock lock = new ReentrantLock(); Condition full = lock.newCondition(); Condition empty = lock.newCondition(); for (int i = 0; i < PRODUCER_NUM; i++) { pool.execute(new SemaphoreProducer(semaphoreBuffer, fullCount, emptyCount)); pool.execute(new ConditionProducer(conditionBuffer, lock, full, empty)); pool.execute(new BlockingQueueProducer(blockingQueueBuffer)); } for (int i = 0; i < CONSUMER_NUM; i++) {
pool.execute(new SemaphoreConsumer(semaphoreBuffer, fullCount, emptyCount));
4
codelibs/fess-suggest
src/main/java/org/codelibs/fess/suggest/index/contents/DefaultContentsParser.java
[ "public interface SuggestAnalyzer {\n List<AnalyzeToken> analyze(String text, String field, String lang);\n\n List<AnalyzeToken> analyzeAndReading(String text, String field, String lang);\n}", "public interface ReadingConverter {\n default int getMaxReadingNum() {\n return 10;\n }\n\n void init() throws IOException;\n\n List<String> convert(String text, final String field, String... langs) throws IOException;\n}", "public class SuggestItem {\n\n public enum Kind {\n DOCUMENT(\"document\"), QUERY(\"query\"), USER(\"user\");\n\n private final String kind;\n\n Kind(final String kind) {\n this.kind = kind;\n }\n\n @Override\n public String toString() {\n return kind;\n }\n }\n\n private String text;\n\n private ZonedDateTime timestamp;\n\n private long queryFreq;\n\n private long docFreq;\n\n private float userBoost;\n\n private String[][] readings;\n\n private String[] fields;\n\n private String[] tags;\n\n private String[] roles;\n\n private String[] languages;\n\n private Kind[] kinds;\n\n private Map<String, Object> emptySource;\n\n private String id;\n\n private SuggestItem() {\n }\n\n public SuggestItem(final String[] text, final String[][] readings, final String[] fields, final long docFreq, final long queryFreq,\n final float userBoost, @Nullable final String[] tags, @Nullable final String[] roles, @Nullable final String[] languages,\n final Kind kind) {\n this.text = String.join(SuggestConstants.TEXT_SEPARATOR, text);\n this.readings = readings;\n this.fields = fields != null ? fields : new String[] {};\n this.tags = tags != null ? tags : new String[] {};\n\n if (roles == null || roles.length == 0) {\n this.roles = new String[] { SuggestConstants.DEFAULT_ROLE };\n } else {\n this.roles = new String[roles.length];\n System.arraycopy(roles, 0, this.roles, 0, roles.length);\n }\n\n this.languages = languages != null ? languages : new String[] {};\n\n this.kinds = new Kind[] { kind };\n if (userBoost > 1) {\n this.userBoost = userBoost;\n } else {\n this.userBoost = 1;\n }\n this.docFreq = docFreq;\n this.queryFreq = queryFreq;\n this.timestamp = ZonedDateTime.now();\n this.emptySource = createEmptyMap();\n this.id = SuggestUtil.createSuggestTextId(this.text);\n }\n\n public String getText() {\n return text;\n }\n\n public String[][] getReadings() {\n return readings;\n }\n\n public String[] getTags() {\n return tags;\n }\n\n public String[] getRoles() {\n return roles;\n }\n\n public String[] getLanguages() {\n return languages;\n }\n\n public String[] getFields() {\n return fields;\n }\n\n public Kind[] getKinds() {\n return kinds;\n }\n\n public long getQueryFreq() {\n return queryFreq;\n }\n\n public long getDocFreq() {\n return docFreq;\n }\n\n public float getUserBoost() {\n return userBoost;\n }\n\n public ZonedDateTime getTimestamp() {\n return timestamp;\n }\n\n public void setText(final String text) {\n this.text = text;\n }\n\n public void setTimestamp(final ZonedDateTime timestamp) {\n this.timestamp = timestamp;\n }\n\n public void setQueryFreq(final long queryFreq) {\n this.queryFreq = queryFreq;\n }\n\n public void setDocFreq(final long docFreq) {\n this.docFreq = docFreq;\n }\n\n public void setUserBoost(final float userBoost) {\n this.userBoost = userBoost;\n }\n\n public void setReadings(final String[][] readings) {\n this.readings = readings;\n }\n\n public void setFields(final String[] fields) {\n this.fields = fields;\n }\n\n public void setTags(final String[] tags) {\n this.tags = tags;\n }\n\n public void setRoles(final String[] roles) {\n this.roles = roles;\n }\n\n public void setLanguages(final String[] languages) {\n this.languages = languages;\n }\n\n public void setKinds(final Kind[] kinds) {\n this.kinds = kinds;\n }\n\n public void setEmptySource(final Map<String, Object> emptySource) {\n this.emptySource = emptySource;\n }\n\n public void setId(final String id) {\n this.id = id;\n }\n\n public Map<String, Object> toEmptyMap() {\n return emptySource;\n }\n\n protected Map<String, Object> createEmptyMap() {\n final Map<String, Object> map = new HashMap<>();\n map.put(FieldNames.TEXT, StringUtil.EMPTY);\n\n for (int i = 0; i < readings.length; i++) {\n map.put(FieldNames.READING_PREFIX + i, new String[] {});\n }\n\n map.put(FieldNames.FIELDS, new String[] {});\n map.put(FieldNames.TAGS, new String[] {});\n map.put(FieldNames.ROLES, new String[] {});\n map.put(FieldNames.LANGUAGES, new String[] {});\n map.put(FieldNames.KINDS, new String[] {});\n map.put(FieldNames.SCORE, 1.0F);\n map.put(FieldNames.QUERY_FREQ, 0L);\n map.put(FieldNames.DOC_FREQ, 0L);\n map.put(FieldNames.USER_BOOST, 1.0F);\n map.put(FieldNames.TIMESTAMP, DateTimeFormatter.ISO_INSTANT.format(ZonedDateTime.now()));\n return map;\n }\n\n public String getId() {\n return id;\n }\n\n public Map<String, Object> getSource() {\n final Map<String, Object> map = new HashMap<>();\n map.put(FieldNames.TEXT, text);\n\n for (int i = 0; i < readings.length; i++) {\n map.put(FieldNames.READING_PREFIX + i, readings[i]);\n }\n\n map.put(FieldNames.FIELDS, fields);\n map.put(FieldNames.TAGS, tags);\n map.put(FieldNames.ROLES, roles);\n map.put(FieldNames.LANGUAGES, languages);\n map.put(FieldNames.KINDS, Stream.of(kinds).map(Kind::toString).toArray());\n map.put(FieldNames.QUERY_FREQ, queryFreq);\n map.put(FieldNames.DOC_FREQ, docFreq);\n map.put(FieldNames.USER_BOOST, userBoost);\n map.put(FieldNames.SCORE, (queryFreq + docFreq) * userBoost);\n map.put(FieldNames.TIMESTAMP, timestamp.toInstant().toEpochMilli());\n return map;\n }\n\n public static SuggestItem parseSource(final Map<String, Object> source) {\n final String text = source.get(FieldNames.TEXT).toString();\n final List<String[]> readings = new ArrayList<>();\n for (int i = 0;; i++) {\n final Object readingObj = source.get(FieldNames.READING_PREFIX + i);\n if (!(readingObj instanceof List)) {\n break;\n }\n @SuppressWarnings(\"unchecked\")\n final List<String> list = (List<String>) readingObj;\n readings.add(list.toArray(new String[list.size()]));\n }\n final List<String> fields = SuggestUtil.getAsList(source.get(FieldNames.FIELDS));\n final long docFreq = Long.parseLong(source.get(FieldNames.DOC_FREQ).toString());\n final long queryFreq = Long.parseLong(source.get(FieldNames.QUERY_FREQ).toString());\n final float userBoost = Float.parseFloat(source.get(FieldNames.USER_BOOST).toString());\n final List<String> tags = SuggestUtil.getAsList(source.get(FieldNames.TAGS));\n final List<String> roles = SuggestUtil.getAsList(source.get(FieldNames.ROLES));\n final List<String> languages = SuggestUtil.getAsList(source.get(FieldNames.LANGUAGES));\n final List<String> kinds = SuggestUtil.getAsList(source.get(FieldNames.KINDS));\n final long timestamp = Long.parseLong(source.get(FieldNames.TIMESTAMP).toString());\n\n final SuggestItem item = new SuggestItem();\n item.text = text;\n item.readings = readings.toArray(new String[readings.size()][]);\n item.fields = fields.toArray(new String[fields.size()]);\n item.docFreq = docFreq;\n item.queryFreq = queryFreq;\n item.userBoost = userBoost;\n item.tags = tags.toArray(new String[tags.size()]);\n item.roles = roles.toArray(new String[roles.size()]);\n item.languages = languages.toArray(new String[languages.size()]);\n\n item.kinds = new Kind[kinds.size()];\n for (int i = 0; i < kinds.size(); i++) {\n final String kind = kinds.get(i);\n if (kind.equals(Kind.DOCUMENT.toString())) {\n item.kinds[i] = Kind.DOCUMENT;\n } else if (kind.equals(Kind.QUERY.toString())) {\n item.kinds[i] = Kind.QUERY;\n } else if (kind.equals(Kind.USER.toString())) {\n item.kinds[i] = Kind.USER;\n }\n }\n\n item.id = SuggestUtil.createSuggestTextId(item.text);\n item.timestamp = ZonedDateTime.ofInstant(Instant.ofEpochMilli(timestamp), Clock.systemDefaultZone().getZone());\n return item;\n }\n\n public Map<String, Object> getUpdatedSource(final Map<String, Object> existingSource) {\n final Map<String, Object> map = new HashMap<>();\n map.put(FieldNames.TEXT, text);\n\n for (int i = 0; i < readings.length; i++) {\n final Object readingObj = existingSource.get(FieldNames.READING_PREFIX + i);\n if (readingObj instanceof List) {\n @SuppressWarnings(\"unchecked\")\n final List<String> existingValues = (List<String>) readingObj;\n concatValues(existingValues, readings[i]);\n map.put(FieldNames.READING_PREFIX + i, existingValues);\n } else {\n map.put(FieldNames.READING_PREFIX + i, readings[i]);\n }\n }\n\n final Object fieldsObj = existingSource.get(FieldNames.FIELDS);\n if (fieldsObj instanceof List) {\n @SuppressWarnings(\"unchecked\")\n final List<String> existingValues = (List<String>) fieldsObj;\n concatValues(existingValues, fields);\n map.put(FieldNames.FIELDS, existingValues);\n } else {\n map.put(FieldNames.FIELDS, fields);\n }\n\n final Object tagsObj = existingSource.get(FieldNames.TAGS);\n if (tagsObj instanceof List) {\n @SuppressWarnings(\"unchecked\")\n final List<String> existingValues = (List<String>) tagsObj;\n concatValues(existingValues, tags);\n map.put(FieldNames.TAGS, existingValues);\n } else {\n map.put(FieldNames.TAGS, tags);\n }\n\n final Object rolesObj = existingSource.get(FieldNames.ROLES);\n if (rolesObj instanceof List) {\n @SuppressWarnings(\"unchecked\")\n final List<String> existingValues = (List<String>) rolesObj;\n concatValues(existingValues, roles);\n map.put(FieldNames.ROLES, existingValues);\n } else {\n map.put(FieldNames.ROLES, roles);\n }\n\n final Object langsObj = existingSource.get(FieldNames.LANGUAGES);\n if (langsObj instanceof List) {\n @SuppressWarnings(\"unchecked\")\n final List<String> existingValues = (List<String>) langsObj;\n concatValues(existingValues, languages);\n map.put(FieldNames.LANGUAGES, existingValues);\n } else {\n map.put(FieldNames.LANGUAGES, languages);\n }\n\n final Object kindsObj = existingSource.get(FieldNames.KINDS);\n if (kindsObj instanceof List) {\n @SuppressWarnings(\"unchecked\")\n final List<String> existingFields = (List<String>) kindsObj;\n concatValues(existingFields, Stream.of(kinds).map(Kind::toString).toArray(count -> new String[count]));\n map.put(FieldNames.KINDS, existingFields);\n } else {\n map.put(FieldNames.KINDS, Stream.of(kinds).map(Kind::toString).toArray());\n }\n\n final long updatedQueryFreq;\n final Object queryFreqObj = existingSource.get(FieldNames.QUERY_FREQ);\n if (queryFreqObj == null) {\n updatedQueryFreq = queryFreq;\n } else {\n final Long existingValue = Long.parseLong(queryFreqObj.toString());\n updatedQueryFreq = queryFreq + existingValue;\n }\n map.put(FieldNames.QUERY_FREQ, updatedQueryFreq);\n\n final long updatedDocFreq;\n final Object docFreqObj = existingSource.get(FieldNames.DOC_FREQ);\n if (docFreqObj == null) {\n updatedDocFreq = docFreq;\n } else {\n final Long existingValue = Long.parseLong(docFreqObj.toString());\n updatedDocFreq = docFreq + existingValue;\n }\n map.put(FieldNames.DOC_FREQ, updatedDocFreq);\n\n map.put(FieldNames.USER_BOOST, userBoost);\n map.put(FieldNames.SCORE, (updatedQueryFreq + updatedDocFreq) * userBoost);\n map.put(FieldNames.TIMESTAMP, timestamp.toInstant().toEpochMilli());\n return map;\n }\n\n protected static <T> void concatValues(final List<T> dest, final T... newValues) {\n for (final T value : newValues) {\n if (!dest.contains(value)) {\n dest.add(value);\n }\n }\n }\n\n protected static Kind[] concatKinds(final Kind[] kinds, final Kind... newKinds) {\n if (kinds == null) {\n return newKinds;\n }\n if (newKinds == null) {\n return kinds;\n }\n\n final List<Kind> list = new ArrayList<>(kinds.length + newKinds.length);\n list.addAll(Arrays.asList(kinds));\n for (final Kind kind : newKinds) {\n if (!list.contains(kind)) {\n list.add(kind);\n }\n }\n return list.toArray(new Kind[list.size()]);\n }\n\n public static SuggestItem merge(final SuggestItem item1, final SuggestItem item2) {\n if (!item1.getId().equals(item2.getId())) {\n throw new IllegalArgumentException(\"Item id is mismatch.\");\n }\n\n final SuggestItem mergedItem = new SuggestItem();\n\n mergedItem.id = item1.getId();\n mergedItem.text = item1.getText();\n\n mergedItem.readings = new String[mergedItem.text.split(SuggestConstants.TEXT_SEPARATOR).length][];\n for (int i = 0; i < mergedItem.readings.length; i++) {\n final List<String> list = new ArrayList<>();\n if (item1.getReadings().length > i) {\n Collections.addAll(list, item1.getReadings()[i]);\n }\n if (item2.getReadings().length > i) {\n for (final String reading : item2.getReadings()[i]) {\n if (!list.contains(reading)) {\n list.add(reading);\n }\n }\n }\n mergedItem.readings[i] = list.toArray(new String[list.size()]);\n }\n\n final List<String> fieldList = new ArrayList<>(item1.getFields().length + item2.getFields().length);\n Collections.addAll(fieldList, item1.getFields());\n for (final String field : item2.getFields()) {\n if (!fieldList.contains(field)) {\n fieldList.add(field);\n }\n }\n mergedItem.fields = fieldList.toArray(new String[fieldList.size()]);\n\n final List<String> tagList = new ArrayList<>(item1.getTags().length + item2.getTags().length);\n Collections.addAll(tagList, item1.getTags());\n for (final String tag : item2.getTags()) {\n if (!tagList.contains(tag)) {\n tagList.add(tag);\n }\n }\n mergedItem.tags = tagList.toArray(new String[tagList.size()]);\n\n final List<String> langList = new ArrayList<>(item1.getLanguages().length + item2.getLanguages().length);\n Collections.addAll(langList, item1.getLanguages());\n for (final String lang : item2.getLanguages()) {\n if (!langList.contains(lang)) {\n langList.add(lang);\n }\n }\n mergedItem.languages = langList.toArray(new String[langList.size()]);\n\n final List<String> roleList = new ArrayList<>(item1.getRoles().length + item2.getRoles().length);\n Collections.addAll(roleList, item1.getRoles());\n for (final String role : item2.getRoles()) {\n if (!roleList.contains(role)) {\n roleList.add(role);\n }\n }\n mergedItem.roles = roleList.toArray(new String[roleList.size()]);\n\n mergedItem.kinds = concatKinds(item1.kinds, item2.kinds);\n mergedItem.timestamp = item2.timestamp;\n mergedItem.queryFreq = item1.queryFreq + item2.queryFreq;\n mergedItem.docFreq = item1.docFreq + item2.docFreq;\n mergedItem.userBoost = item2.userBoost;\n mergedItem.emptySource = item2.emptySource;\n\n return mergedItem;\n }\n\n public boolean isBadWord(final String[] badWords) {\n for (final String badWord : badWords) {\n if (text.contains(badWord)) {\n return true;\n }\n }\n return false;\n }\n\n @Override\n public String toString() {\n return \"SuggestItem [text=\" + text + \", timestamp=\" + timestamp + \", queryFreq=\" + queryFreq + \", docFreq=\" + docFreq\n + \", userBoost=\" + userBoost + \", readings=\" + Arrays.toString(readings) + \", fields=\" + Arrays.toString(fields) + \", tags=\"\n + Arrays.toString(tags) + \", roles=\" + Arrays.toString(roles) + \", languages=\" + Arrays.toString(languages) + \", kinds=\"\n + Arrays.toString(kinds) + \", emptySource=\" + emptySource + \", id=\" + id + \"]\";\n }\n}", "public class SuggesterException extends RuntimeException {\n\n private static final long serialVersionUID = 1L;\n\n public SuggesterException(final String msg) {\n super(msg);\n }\n\n public SuggesterException(final Throwable cause) {\n super(cause);\n }\n\n public SuggesterException(final String msg, final Throwable cause) {\n super(msg, cause);\n }\n}", "public class QueryLog {\n private final String q;\n private final String fq;\n\n public QueryLog(final String queryString, @Nullable final String filterQueryString) {\n this.q = queryString;\n this.fq = filterQueryString;\n }\n\n public String getQueryString() {\n return q;\n }\n\n public String getFilterQueryString() {\n return fq;\n }\n}", "public interface Normalizer {\n String normalize(String text, String field, String... langs);\n}", "public final class SuggestUtil {\n private static final int MAX_QUERY_TERM_NUM = 5;\n private static final int MAX_QUERY_TERM_LENGTH = 48;\n\n private static final Base64.Encoder encoder = Base64.getEncoder();\n\n private static final int ID_MAX_LENGTH = 445;\n\n private SuggestUtil() {\n }\n\n public static String createSuggestTextId(final String text) {\n final String id = encoder.encodeToString(text.getBytes(CoreLibConstants.CHARSET_UTF_8));\n if (id.length() > 445) {\n return id.substring(0, ID_MAX_LENGTH);\n }\n return id;\n }\n\n public static String[] parseQuery(final String q, final String field) {\n final List<String> keywords = getKeywords(q, new String[] { field });\n if (MAX_QUERY_TERM_NUM < keywords.size()) {\n return new String[0];\n }\n for (final String k : keywords) {\n if (MAX_QUERY_TERM_LENGTH < k.length()) {\n return new String[0];\n }\n }\n return keywords.toArray(new String[keywords.size()]);\n }\n\n public static List<String> getKeywords(final String q, final String[] fields) {\n final List<String> keywords = new ArrayList<>();\n final List<TermQuery> termQueryList;\n try {\n final StandardQueryParser parser = new StandardQueryParser();\n parser.setDefaultOperator(StandardQueryConfigHandler.Operator.AND);\n\n termQueryList = getTermQueryList(parser.parse(q, \"default\"), fields);\n } catch (final Exception e) {\n return keywords;\n }\n for (final TermQuery tq : termQueryList) {\n final String text = tq.getTerm().text();\n if ((0 == text.length()) || keywords.contains(text)) {\n continue;\n }\n keywords.add(text);\n }\n return keywords;\n }\n\n public static List<TermQuery> getTermQueryList(final Query query, final String[] fields) {\n if (query instanceof BooleanQuery booleanQuery) {\n final List<BooleanClause> clauses = booleanQuery.clauses();\n final List<TermQuery> queryList = new ArrayList<>();\n for (final BooleanClause clause : clauses) {\n final Query q = clause.getQuery();\n if (q instanceof BooleanQuery) {\n queryList.addAll(getTermQueryList(q, fields));\n } else if (q instanceof TermQuery termQuery) {\n for (final String field : fields) {\n if (field.equals(termQuery.getTerm().field())) {\n queryList.add(termQuery);\n }\n }\n }\n }\n return queryList;\n }\n if (query instanceof TermQuery termQuery) {\n for (final String field : fields) {\n if (field.equals(termQuery.getTerm().field())) {\n final List<TermQuery> queryList = new ArrayList<>(1);\n queryList.add(termQuery);\n return queryList;\n }\n }\n }\n return Collections.emptyList();\n }\n\n public static String createBulkLine(final String index, final String type, final SuggestItem item) {\n final Map<String, Object> firstLineMap = new HashMap<>();\n final Map<String, Object> firstLineInnerMap = new HashMap<>();\n firstLineInnerMap.put(\"_index\", index);\n firstLineInnerMap.put(\"_type\", type);\n firstLineInnerMap.put(\"_id\", item.getId());\n firstLineMap.put(\"index\", firstLineInnerMap);\n\n final Map<String, Object> secondLine = new HashMap<>();\n\n secondLine.put(\"text\", item.getText());\n\n // reading\n final String[][] readings = item.getReadings();\n for (int i = 0; i < readings.length; i++) {\n secondLine.put(\"reading_\" + i, readings[i]);\n }\n\n secondLine.put(\"fields\", item.getFields());\n secondLine.put(\"queryFreq\", item.getQueryFreq());\n secondLine.put(\"docFreq\", item.getDocFreq());\n secondLine.put(\"userBoost\", item.getUserBoost());\n secondLine.put(\"score\", (item.getQueryFreq() + item.getDocFreq()) * item.getUserBoost());\n secondLine.put(\"tags\", item.getTags());\n secondLine.put(\"roles\", item.getRoles());\n secondLine.put(\"kinds\", Arrays.toString(item.getKinds()));\n secondLine.put(\"@timestamp\", item.getTimestamp());\n\n try (OutputStream out1 = getXContentOutputStream(firstLineMap); OutputStream out2 = getXContentOutputStream(secondLine)) {\n return ((ByteArrayOutputStream) out1).toString(CoreLibConstants.UTF_8) + '\\n'\n + ((ByteArrayOutputStream) out2).toString(CoreLibConstants.UTF_8);\n } catch (final IOException e) {\n throw new SuggesterException(e);\n }\n }\n\n private static OutputStream getXContentOutputStream(final Map<String, Object> firstLineMap) throws IOException {\n try (XContentBuilder builder = JsonXContent.contentBuilder().map(firstLineMap)) {\n builder.flush();\n return builder.getOutputStream();\n }\n }\n\n public static ReadingConverter createDefaultReadingConverter(final Client client, final SuggestSettings settings) {\n final ReadingConverterChain chain = new ReadingConverterChain();\n chain.addConverter(new AnalyzerConverter(client, settings));\n chain.addConverter(new KatakanaToAlphabetConverter());\n return chain;\n }\n\n public static ReadingConverter createDefaultContentsReadingConverter(final Client client, final SuggestSettings settings) {\n final ReadingConverterChain chain = new ReadingConverterChain();\n chain.addConverter(new KatakanaToAlphabetConverter());\n return chain;\n }\n\n public static Normalizer createDefaultNormalizer(final Client client, final SuggestSettings settings) {\n final NormalizerChain normalizerChain = new NormalizerChain();\n normalizerChain.add(new AnalyzerNormalizer(client, settings));\n /*\n * normalizerChain.add(new HankakuKanaToZenkakuKana()); normalizerChain.add(new\n * FullWidthToHalfWidthAlphabetNormalizer()); normalizerChain.add(new ICUNormalizer(\"Any-Lower\"));\n */\n return normalizerChain;\n }\n\n public static AnalyzerSettings.DefaultContentsAnalyzer createDefaultAnalyzer(final Client client, final SuggestSettings settings) {\n final AnalyzerSettings analyzerSettings = settings.analyzer();\n return analyzerSettings.new DefaultContentsAnalyzer();\n }\n\n public static List<String> getAsList(final Object value) {\n if (value == null) {\n return new ArrayList<>();\n }\n\n if (value instanceof String) {\n final List<String> list = new ArrayList<>();\n list.add(value.toString());\n return list;\n }\n if (value instanceof List) {\n return (List<String>) value;\n }\n throw new IllegalArgumentException(\"The value should be String or List, but \" + value.getClass());\n }\n\n public static boolean deleteByQuery(final Client client, final SuggestSettings settings, final String index,\n final QueryBuilder queryBuilder) {\n try {\n SearchResponse response = client.prepareSearch(index).setQuery(queryBuilder).setSize(500).setScroll(settings.getScrollTimeout())\n .execute().actionGet(settings.getSearchTimeout());\n String scrollId = response.getScrollId();\n try {\n while (scrollId != null) {\n final SearchHit[] hits = response.getHits().getHits();\n if (hits.length == 0) {\n break;\n }\n\n final BulkRequestBuilder bulkRequestBuiler = client.prepareBulk();\n Stream.of(hits).map(SearchHit::getId).forEach(id -> bulkRequestBuiler.add(new DeleteRequest(index, id)));\n\n final BulkResponse bulkResponse = bulkRequestBuiler.execute().actionGet(settings.getBulkTimeout());\n if (bulkResponse.hasFailures()) {\n throw new SuggesterException(bulkResponse.buildFailureMessage());\n }\n response = client.prepareSearchScroll(scrollId).setScroll(settings.getScrollTimeout()).execute()\n .actionGet(settings.getSearchTimeout());\n if (!scrollId.equals(response.getScrollId())) {\n SuggestUtil.deleteScrollContext(client, scrollId);\n }\n scrollId = response.getScrollId();\n }\n } finally {\n SuggestUtil.deleteScrollContext(client, scrollId);\n }\n client.admin().indices().prepareRefresh(index).execute().actionGet(settings.getIndicesTimeout());\n } catch (final Exception e) {\n throw new SuggesterException(\"Failed to exec delete by query.\", e);\n }\n\n return true;\n }\n\n public static void deleteScrollContext(final Client client, final String scrollId) {\n if (scrollId != null) {\n client.prepareClearScroll().addScrollId(scrollId).execute(ActionListener.wrap(res -> {}, e -> {}));\n }\n }\n\n public static String escapeWildcardQuery(final String query) {\n return query.replace(\"*\", \"\\\\*\").replace(\"?\", \"\\\\?\");\n }\n}" ]
import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import org.codelibs.core.lang.StringUtil; import org.codelibs.fess.suggest.analysis.SuggestAnalyzer; import org.codelibs.fess.suggest.converter.ReadingConverter; import org.codelibs.fess.suggest.entity.SuggestItem; import org.codelibs.fess.suggest.exception.SuggesterException; import org.codelibs.fess.suggest.index.contents.querylog.QueryLog; import org.codelibs.fess.suggest.normalizer.Normalizer; import org.codelibs.fess.suggest.util.SuggestUtil; import org.opensearch.action.admin.indices.analyze.AnalyzeAction.AnalyzeToken;
/* * Copyright 2012-2022 CodeLibs Project and the Others. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.codelibs.fess.suggest.index.contents; public class DefaultContentsParser implements ContentsParser { @Override
public SuggestItem parseSearchWords(final String[] words, final String[][] readings, final String[] fields, final String[] tags,
2