repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
Piasy/decaf-mind-compiler
decaf_PA4/src/decaf/scope/Scope.java
// Path: decaf_PA4/src/decaf/symbol/Symbol.java // public abstract class Symbol { // protected String name; // // protected Scope definedIn; // // protected Type type; // // protected int order; // // protected Location location; // // public static final Comparator<Symbol> LOCATION_COMPARATOR = new Comparator<Symbol>() { // // @Override // public int compare(Symbol o1, Symbol o2) { // return o1.location.compareTo(o2.location); // } // // }; // // public static final Comparator<Symbol> ORDER_COMPARATOR = new Comparator<Symbol>() { // // @Override // public int compare(Symbol o1, Symbol o2) { // return o1.order > o2.order ? 1 : o1.order == o2.order ? 0 : -1; // } // // }; // // public Scope getScope() { // return definedIn; // } // // public void setScope(Scope definedIn) { // this.definedIn = definedIn; // } // // public int getOrder() { // return order; // } // // public void setOrder(int order) { // this.order = order; // } // // public Location getLocation() { // return location; // } // // public void setLocation(Location location) { // this.location = location; // } // // public Type getType() { // return type; // } // // public String getName() { // return name; // } // // public abstract boolean isVariable(); // // public abstract boolean isClass(); // // public abstract boolean isFunction(); // // public abstract String toString(); // }
import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import decaf.symbol.Symbol; import decaf.utils.IndentPrintWriter;
package decaf.scope; public abstract class Scope { public enum Kind { GLOBAL, CLASS, FORMAL, LOCAL }
// Path: decaf_PA4/src/decaf/symbol/Symbol.java // public abstract class Symbol { // protected String name; // // protected Scope definedIn; // // protected Type type; // // protected int order; // // protected Location location; // // public static final Comparator<Symbol> LOCATION_COMPARATOR = new Comparator<Symbol>() { // // @Override // public int compare(Symbol o1, Symbol o2) { // return o1.location.compareTo(o2.location); // } // // }; // // public static final Comparator<Symbol> ORDER_COMPARATOR = new Comparator<Symbol>() { // // @Override // public int compare(Symbol o1, Symbol o2) { // return o1.order > o2.order ? 1 : o1.order == o2.order ? 0 : -1; // } // // }; // // public Scope getScope() { // return definedIn; // } // // public void setScope(Scope definedIn) { // this.definedIn = definedIn; // } // // public int getOrder() { // return order; // } // // public void setOrder(int order) { // this.order = order; // } // // public Location getLocation() { // return location; // } // // public void setLocation(Location location) { // this.location = location; // } // // public Type getType() { // return type; // } // // public String getName() { // return name; // } // // public abstract boolean isVariable(); // // public abstract boolean isClass(); // // public abstract boolean isFunction(); // // public abstract String toString(); // } // Path: decaf_PA4/src/decaf/scope/Scope.java import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import decaf.symbol.Symbol; import decaf.utils.IndentPrintWriter; package decaf.scope; public abstract class Scope { public enum Kind { GLOBAL, CLASS, FORMAL, LOCAL }
protected Map<String, Symbol> symbols = new LinkedHashMap<String, Symbol>();
Piasy/decaf-mind-compiler
decaf_PA3/src/decaf/tac/Temp.java
// Path: decaf_PA4/src/decaf/machdesc/Register.java // public abstract class Register { // // public Temp var; // // public abstract String toString(); // } // // Path: decaf_PA2/src/decaf/symbol/Variable.java // public class Variable extends Symbol { // // private int offset; // // public int getOffset() { // return offset; // } // // public void setOffset(int offset) { // this.offset = offset; // } // // public Variable(String name, Type type, Location location) { // this.name = name; // this.type = type; // this.location = location; // } // // public boolean isLocalVar() { // return definedIn.isLocalScope(); // } // // public boolean isMemberVar() { // return definedIn.isClassScope(); // } // // @Override // public boolean isVariable() { // return true; // } // // @Override // public String toString() { // return location + " -> variable " + (isParam() ? "@" : "") + name // + " : " + type; // } // // public boolean isParam() { // return definedIn.isFormalScope(); // } // // @Override // public boolean isClass() { // return false; // } // // @Override // public boolean isFunction() { // return false; // } // // }
import java.util.Comparator; import java.util.HashMap; import java.util.Map; import decaf.machdesc.Register; import decaf.symbol.Variable;
package decaf.tac; public class Temp { public int id; public String name; public int offset = Integer.MAX_VALUE; public int size;
// Path: decaf_PA4/src/decaf/machdesc/Register.java // public abstract class Register { // // public Temp var; // // public abstract String toString(); // } // // Path: decaf_PA2/src/decaf/symbol/Variable.java // public class Variable extends Symbol { // // private int offset; // // public int getOffset() { // return offset; // } // // public void setOffset(int offset) { // this.offset = offset; // } // // public Variable(String name, Type type, Location location) { // this.name = name; // this.type = type; // this.location = location; // } // // public boolean isLocalVar() { // return definedIn.isLocalScope(); // } // // public boolean isMemberVar() { // return definedIn.isClassScope(); // } // // @Override // public boolean isVariable() { // return true; // } // // @Override // public String toString() { // return location + " -> variable " + (isParam() ? "@" : "") + name // + " : " + type; // } // // public boolean isParam() { // return definedIn.isFormalScope(); // } // // @Override // public boolean isClass() { // return false; // } // // @Override // public boolean isFunction() { // return false; // } // // } // Path: decaf_PA3/src/decaf/tac/Temp.java import java.util.Comparator; import java.util.HashMap; import java.util.Map; import decaf.machdesc.Register; import decaf.symbol.Variable; package decaf.tac; public class Temp { public int id; public String name; public int offset = Integer.MAX_VALUE; public int size;
public Variable sym;
Piasy/decaf-mind-compiler
decaf_PA3/src/decaf/tac/Temp.java
// Path: decaf_PA4/src/decaf/machdesc/Register.java // public abstract class Register { // // public Temp var; // // public abstract String toString(); // } // // Path: decaf_PA2/src/decaf/symbol/Variable.java // public class Variable extends Symbol { // // private int offset; // // public int getOffset() { // return offset; // } // // public void setOffset(int offset) { // this.offset = offset; // } // // public Variable(String name, Type type, Location location) { // this.name = name; // this.type = type; // this.location = location; // } // // public boolean isLocalVar() { // return definedIn.isLocalScope(); // } // // public boolean isMemberVar() { // return definedIn.isClassScope(); // } // // @Override // public boolean isVariable() { // return true; // } // // @Override // public String toString() { // return location + " -> variable " + (isParam() ? "@" : "") + name // + " : " + type; // } // // public boolean isParam() { // return definedIn.isFormalScope(); // } // // @Override // public boolean isClass() { // return false; // } // // @Override // public boolean isFunction() { // return false; // } // // }
import java.util.Comparator; import java.util.HashMap; import java.util.Map; import decaf.machdesc.Register; import decaf.symbol.Variable;
package decaf.tac; public class Temp { public int id; public String name; public int offset = Integer.MAX_VALUE; public int size; public Variable sym; public boolean isConst; public int value; public boolean isParam; public boolean isLoaded;
// Path: decaf_PA4/src/decaf/machdesc/Register.java // public abstract class Register { // // public Temp var; // // public abstract String toString(); // } // // Path: decaf_PA2/src/decaf/symbol/Variable.java // public class Variable extends Symbol { // // private int offset; // // public int getOffset() { // return offset; // } // // public void setOffset(int offset) { // this.offset = offset; // } // // public Variable(String name, Type type, Location location) { // this.name = name; // this.type = type; // this.location = location; // } // // public boolean isLocalVar() { // return definedIn.isLocalScope(); // } // // public boolean isMemberVar() { // return definedIn.isClassScope(); // } // // @Override // public boolean isVariable() { // return true; // } // // @Override // public String toString() { // return location + " -> variable " + (isParam() ? "@" : "") + name // + " : " + type; // } // // public boolean isParam() { // return definedIn.isFormalScope(); // } // // @Override // public boolean isClass() { // return false; // } // // @Override // public boolean isFunction() { // return false; // } // // } // Path: decaf_PA3/src/decaf/tac/Temp.java import java.util.Comparator; import java.util.HashMap; import java.util.Map; import decaf.machdesc.Register; import decaf.symbol.Variable; package decaf.tac; public class Temp { public int id; public String name; public int offset = Integer.MAX_VALUE; public int size; public Variable sym; public boolean isConst; public int value; public boolean isParam; public boolean isLoaded;
public Register reg;
Piasy/decaf-mind-compiler
decaf_PA2/src/decaf/symbol/Class.java
// Path: decaf_PA1/Compiler/src/decaf/Driver.java // public final class Driver { // // private static Driver driver; // // private Option option; // // private List<DecafError> errors; // // private Lexer lexer; // // private Parser parser; // // public static Driver getDriver() { // return driver; // } // // public void issueError(DecafError error) { // errors.add(error); // } // // public void checkPoint() { // if (errors.size() > 0) { // Collections.sort(errors, new Comparator<DecafError>() { // // @Override // public int compare(DecafError o1, DecafError o2) { // return o1.getLocation().compareTo(o2.getLocation()); // } // // }); // for (DecafError error : errors) { // option.getErr().println(error); // } // System.exit(1); // } // } // // private void init() { // lexer = new Lexer(option.getInput()); // parser = new Parser(); // lexer.setParser(parser); // parser.setLexer(lexer); // errors = new ArrayList<DecafError>(); // } // // private void compile() { // // Tree.TopLevel tree = parser.parseFile(); // // checkPoint(); // if (option.getLevel() == Option.Level.LEVEL0) { // IndentPrintWriter pw = new IndentPrintWriter(option.getOutput(), 4); // tree.printTo(pw); // pw.close(); // return; // } // } // // public static void main(String[] args) throws IOException { // driver = new Driver(); // driver.option = new Option(args); // driver.init(); // driver.compile(); // } // // public Option getOption() { // return option; // } // } // // Path: decaf_PA2/src/decaf/type/ClassType.java // public class ClassType extends Type { // // private Class symbol; // // private ClassType parent; // // public ClassType(Class symbol, ClassType parent) { // this.symbol = symbol; // this.parent = parent; // } // // @Override // public boolean compatible(Type type) { // if (type.equal(BaseType.ERROR)) { // return true; // } // //////////////////////////////////////////////////////////////////////////////////////////////// // // if (type.equal(BaseType.NULL)) { // // return true; // // } // //////////////////////////////////////////////////////////////////////////////////////////////// // if (!type.isClassType()) { // return false; // } // for (ClassType t = this; t != null; t = t.parent) { // if (t.equal(type)) { // return true; // } // } // return false; // // } // // @Override // public boolean equal(Type type) { // return type.isClassType() && symbol == ((ClassType) type).symbol; // } // // @Override // public boolean isClassType() { // return true; // } // // @Override // public String toString() { // return "class : " + symbol.getName(); // } // // public Class getSymbol() { // return symbol; // } // // public ClassType getParentType() { // return parent; // } // // public ClassScope getClassScope() { // return symbol.getAssociatedScope(); // } // // }
import decaf.Driver; import decaf.Location; import decaf.scope.ClassScope; import decaf.scope.GlobalScope; import decaf.type.ClassType;
public int getNumNonStaticFunc() { return numNonStaticFunc; } public void setNumNonStaticFunc(int numNonStaticFunc) { this.numNonStaticFunc = numNonStaticFunc; } public int getNumVar() { return numVar; } public void setNumVar(int numVar) { this.numVar = numVar; } public Class(String name, String parentName, Location location) { this.name = name; this.parentName = parentName; this.location = location; this.order = -1; this.check = false; this.numNonStaticFunc = -1; this.numVar = -1; this.associatedScope = new ClassScope(this); } public void createType() { Class p = getParent(); if (p == null) {
// Path: decaf_PA1/Compiler/src/decaf/Driver.java // public final class Driver { // // private static Driver driver; // // private Option option; // // private List<DecafError> errors; // // private Lexer lexer; // // private Parser parser; // // public static Driver getDriver() { // return driver; // } // // public void issueError(DecafError error) { // errors.add(error); // } // // public void checkPoint() { // if (errors.size() > 0) { // Collections.sort(errors, new Comparator<DecafError>() { // // @Override // public int compare(DecafError o1, DecafError o2) { // return o1.getLocation().compareTo(o2.getLocation()); // } // // }); // for (DecafError error : errors) { // option.getErr().println(error); // } // System.exit(1); // } // } // // private void init() { // lexer = new Lexer(option.getInput()); // parser = new Parser(); // lexer.setParser(parser); // parser.setLexer(lexer); // errors = new ArrayList<DecafError>(); // } // // private void compile() { // // Tree.TopLevel tree = parser.parseFile(); // // checkPoint(); // if (option.getLevel() == Option.Level.LEVEL0) { // IndentPrintWriter pw = new IndentPrintWriter(option.getOutput(), 4); // tree.printTo(pw); // pw.close(); // return; // } // } // // public static void main(String[] args) throws IOException { // driver = new Driver(); // driver.option = new Option(args); // driver.init(); // driver.compile(); // } // // public Option getOption() { // return option; // } // } // // Path: decaf_PA2/src/decaf/type/ClassType.java // public class ClassType extends Type { // // private Class symbol; // // private ClassType parent; // // public ClassType(Class symbol, ClassType parent) { // this.symbol = symbol; // this.parent = parent; // } // // @Override // public boolean compatible(Type type) { // if (type.equal(BaseType.ERROR)) { // return true; // } // //////////////////////////////////////////////////////////////////////////////////////////////// // // if (type.equal(BaseType.NULL)) { // // return true; // // } // //////////////////////////////////////////////////////////////////////////////////////////////// // if (!type.isClassType()) { // return false; // } // for (ClassType t = this; t != null; t = t.parent) { // if (t.equal(type)) { // return true; // } // } // return false; // // } // // @Override // public boolean equal(Type type) { // return type.isClassType() && symbol == ((ClassType) type).symbol; // } // // @Override // public boolean isClassType() { // return true; // } // // @Override // public String toString() { // return "class : " + symbol.getName(); // } // // public Class getSymbol() { // return symbol; // } // // public ClassType getParentType() { // return parent; // } // // public ClassScope getClassScope() { // return symbol.getAssociatedScope(); // } // // } // Path: decaf_PA2/src/decaf/symbol/Class.java import decaf.Driver; import decaf.Location; import decaf.scope.ClassScope; import decaf.scope.GlobalScope; import decaf.type.ClassType; public int getNumNonStaticFunc() { return numNonStaticFunc; } public void setNumNonStaticFunc(int numNonStaticFunc) { this.numNonStaticFunc = numNonStaticFunc; } public int getNumVar() { return numVar; } public void setNumVar(int numVar) { this.numVar = numVar; } public Class(String name, String parentName, Location location) { this.name = name; this.parentName = parentName; this.location = location; this.order = -1; this.check = false; this.numNonStaticFunc = -1; this.numVar = -1; this.associatedScope = new ClassScope(this); } public void createType() { Class p = getParent(); if (p == null) {
type = new ClassType(this, null);
Piasy/decaf-mind-compiler
decaf_PA2/src/decaf/symbol/Class.java
// Path: decaf_PA1/Compiler/src/decaf/Driver.java // public final class Driver { // // private static Driver driver; // // private Option option; // // private List<DecafError> errors; // // private Lexer lexer; // // private Parser parser; // // public static Driver getDriver() { // return driver; // } // // public void issueError(DecafError error) { // errors.add(error); // } // // public void checkPoint() { // if (errors.size() > 0) { // Collections.sort(errors, new Comparator<DecafError>() { // // @Override // public int compare(DecafError o1, DecafError o2) { // return o1.getLocation().compareTo(o2.getLocation()); // } // // }); // for (DecafError error : errors) { // option.getErr().println(error); // } // System.exit(1); // } // } // // private void init() { // lexer = new Lexer(option.getInput()); // parser = new Parser(); // lexer.setParser(parser); // parser.setLexer(lexer); // errors = new ArrayList<DecafError>(); // } // // private void compile() { // // Tree.TopLevel tree = parser.parseFile(); // // checkPoint(); // if (option.getLevel() == Option.Level.LEVEL0) { // IndentPrintWriter pw = new IndentPrintWriter(option.getOutput(), 4); // tree.printTo(pw); // pw.close(); // return; // } // } // // public static void main(String[] args) throws IOException { // driver = new Driver(); // driver.option = new Option(args); // driver.init(); // driver.compile(); // } // // public Option getOption() { // return option; // } // } // // Path: decaf_PA2/src/decaf/type/ClassType.java // public class ClassType extends Type { // // private Class symbol; // // private ClassType parent; // // public ClassType(Class symbol, ClassType parent) { // this.symbol = symbol; // this.parent = parent; // } // // @Override // public boolean compatible(Type type) { // if (type.equal(BaseType.ERROR)) { // return true; // } // //////////////////////////////////////////////////////////////////////////////////////////////// // // if (type.equal(BaseType.NULL)) { // // return true; // // } // //////////////////////////////////////////////////////////////////////////////////////////////// // if (!type.isClassType()) { // return false; // } // for (ClassType t = this; t != null; t = t.parent) { // if (t.equal(type)) { // return true; // } // } // return false; // // } // // @Override // public boolean equal(Type type) { // return type.isClassType() && symbol == ((ClassType) type).symbol; // } // // @Override // public boolean isClassType() { // return true; // } // // @Override // public String toString() { // return "class : " + symbol.getName(); // } // // public Class getSymbol() { // return symbol; // } // // public ClassType getParentType() { // return parent; // } // // public ClassScope getClassScope() { // return symbol.getAssociatedScope(); // } // // }
import decaf.Driver; import decaf.Location; import decaf.scope.ClassScope; import decaf.scope.GlobalScope; import decaf.type.ClassType;
} else { if (p.getType() == null) { p.createType(); } type = new ClassType(this, (ClassType) p.getType()); } } @Override public ClassType getType() { if (type == null) { createType(); } return (ClassType) type; } @Override public String toString() { StringBuilder sb = new StringBuilder(location + " -> class " + name); if (parentName != null) { sb.append(" : " + parentName); } return sb.toString(); } public ClassScope getAssociatedScope() { return associatedScope; } public Class getParent() {
// Path: decaf_PA1/Compiler/src/decaf/Driver.java // public final class Driver { // // private static Driver driver; // // private Option option; // // private List<DecafError> errors; // // private Lexer lexer; // // private Parser parser; // // public static Driver getDriver() { // return driver; // } // // public void issueError(DecafError error) { // errors.add(error); // } // // public void checkPoint() { // if (errors.size() > 0) { // Collections.sort(errors, new Comparator<DecafError>() { // // @Override // public int compare(DecafError o1, DecafError o2) { // return o1.getLocation().compareTo(o2.getLocation()); // } // // }); // for (DecafError error : errors) { // option.getErr().println(error); // } // System.exit(1); // } // } // // private void init() { // lexer = new Lexer(option.getInput()); // parser = new Parser(); // lexer.setParser(parser); // parser.setLexer(lexer); // errors = new ArrayList<DecafError>(); // } // // private void compile() { // // Tree.TopLevel tree = parser.parseFile(); // // checkPoint(); // if (option.getLevel() == Option.Level.LEVEL0) { // IndentPrintWriter pw = new IndentPrintWriter(option.getOutput(), 4); // tree.printTo(pw); // pw.close(); // return; // } // } // // public static void main(String[] args) throws IOException { // driver = new Driver(); // driver.option = new Option(args); // driver.init(); // driver.compile(); // } // // public Option getOption() { // return option; // } // } // // Path: decaf_PA2/src/decaf/type/ClassType.java // public class ClassType extends Type { // // private Class symbol; // // private ClassType parent; // // public ClassType(Class symbol, ClassType parent) { // this.symbol = symbol; // this.parent = parent; // } // // @Override // public boolean compatible(Type type) { // if (type.equal(BaseType.ERROR)) { // return true; // } // //////////////////////////////////////////////////////////////////////////////////////////////// // // if (type.equal(BaseType.NULL)) { // // return true; // // } // //////////////////////////////////////////////////////////////////////////////////////////////// // if (!type.isClassType()) { // return false; // } // for (ClassType t = this; t != null; t = t.parent) { // if (t.equal(type)) { // return true; // } // } // return false; // // } // // @Override // public boolean equal(Type type) { // return type.isClassType() && symbol == ((ClassType) type).symbol; // } // // @Override // public boolean isClassType() { // return true; // } // // @Override // public String toString() { // return "class : " + symbol.getName(); // } // // public Class getSymbol() { // return symbol; // } // // public ClassType getParentType() { // return parent; // } // // public ClassScope getClassScope() { // return symbol.getAssociatedScope(); // } // // } // Path: decaf_PA2/src/decaf/symbol/Class.java import decaf.Driver; import decaf.Location; import decaf.scope.ClassScope; import decaf.scope.GlobalScope; import decaf.type.ClassType; } else { if (p.getType() == null) { p.createType(); } type = new ClassType(this, (ClassType) p.getType()); } } @Override public ClassType getType() { if (type == null) { createType(); } return (ClassType) type; } @Override public String toString() { StringBuilder sb = new StringBuilder(location + " -> class " + name); if (parentName != null) { sb.append(" : " + parentName); } return sb.toString(); } public ClassScope getAssociatedScope() { return associatedScope; } public Class getParent() {
return Driver.getDriver().getTable().lookupClass(parentName);
Piasy/decaf-mind-compiler
decaf_PA2/src/decaf/tree/Tree.java
// Path: decaf_PA2/src/decaf/symbol/Class.java // public class Class extends Symbol { // // private String parentName; // // private ClassScope associatedScope; // // private int order; // // private boolean check; // // private int numNonStaticFunc; // // private int numVar; // // private int size; // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public int getNumNonStaticFunc() { // return numNonStaticFunc; // } // // public void setNumNonStaticFunc(int numNonStaticFunc) { // this.numNonStaticFunc = numNonStaticFunc; // } // // public int getNumVar() { // return numVar; // } // // public void setNumVar(int numVar) { // this.numVar = numVar; // } // // public Class(String name, String parentName, Location location) { // this.name = name; // this.parentName = parentName; // this.location = location; // this.order = -1; // this.check = false; // this.numNonStaticFunc = -1; // this.numVar = -1; // this.associatedScope = new ClassScope(this); // } // // public void createType() { // Class p = getParent(); // if (p == null) { // type = new ClassType(this, null); // } else { // if (p.getType() == null) { // p.createType(); // } // type = new ClassType(this, (ClassType) p.getType()); // } // } // // @Override // public ClassType getType() { // if (type == null) { // createType(); // } // return (ClassType) type; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(location + " -> class " + name); // if (parentName != null) { // sb.append(" : " + parentName); // } // return sb.toString(); // } // // public ClassScope getAssociatedScope() { // return associatedScope; // } // // public Class getParent() { // return Driver.getDriver().getTable().lookupClass(parentName); // } // // @Override // public boolean isClass() { // return true; // } // // @Override // public GlobalScope getScope() { // return (GlobalScope) definedIn; // } // // public int getOrder() { // return order; // } // // public void setOrder(int order) { // this.order = order; // } // // public void dettachParent() { // parentName = null; // } // // public boolean isCheck() { // return check; // } // // public void setCheck(boolean check) { // this.check = check; // } // // @Override // public boolean isFunction() { // return false; // } // // @Override // public boolean isVariable() { // return false; // } // }
import java.util.List; import decaf.*; import decaf.type.*; import decaf.scope.*; import decaf.symbol.*; import decaf.symbol.Class; import decaf.utils.IndentPrintWriter; import decaf.utils.MiscUtils;
public Tree(int tag, Location loc) { super(); this.tag = tag; this.loc = loc; } public Location getLocation() { return loc; } /** * Set type field and return this tree. */ public Tree setType(Type type) { this.type = type; return this; } /** * Visit this tree with a given visitor. */ public void accept(Visitor v) { v.visitTree(this); } public abstract void printTo(IndentPrintWriter pw); public static class TopLevel extends Tree { public List<ClassDef> classes;
// Path: decaf_PA2/src/decaf/symbol/Class.java // public class Class extends Symbol { // // private String parentName; // // private ClassScope associatedScope; // // private int order; // // private boolean check; // // private int numNonStaticFunc; // // private int numVar; // // private int size; // // public int getSize() { // return size; // } // // public void setSize(int size) { // this.size = size; // } // // public int getNumNonStaticFunc() { // return numNonStaticFunc; // } // // public void setNumNonStaticFunc(int numNonStaticFunc) { // this.numNonStaticFunc = numNonStaticFunc; // } // // public int getNumVar() { // return numVar; // } // // public void setNumVar(int numVar) { // this.numVar = numVar; // } // // public Class(String name, String parentName, Location location) { // this.name = name; // this.parentName = parentName; // this.location = location; // this.order = -1; // this.check = false; // this.numNonStaticFunc = -1; // this.numVar = -1; // this.associatedScope = new ClassScope(this); // } // // public void createType() { // Class p = getParent(); // if (p == null) { // type = new ClassType(this, null); // } else { // if (p.getType() == null) { // p.createType(); // } // type = new ClassType(this, (ClassType) p.getType()); // } // } // // @Override // public ClassType getType() { // if (type == null) { // createType(); // } // return (ClassType) type; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(location + " -> class " + name); // if (parentName != null) { // sb.append(" : " + parentName); // } // return sb.toString(); // } // // public ClassScope getAssociatedScope() { // return associatedScope; // } // // public Class getParent() { // return Driver.getDriver().getTable().lookupClass(parentName); // } // // @Override // public boolean isClass() { // return true; // } // // @Override // public GlobalScope getScope() { // return (GlobalScope) definedIn; // } // // public int getOrder() { // return order; // } // // public void setOrder(int order) { // this.order = order; // } // // public void dettachParent() { // parentName = null; // } // // public boolean isCheck() { // return check; // } // // public void setCheck(boolean check) { // this.check = check; // } // // @Override // public boolean isFunction() { // return false; // } // // @Override // public boolean isVariable() { // return false; // } // } // Path: decaf_PA2/src/decaf/tree/Tree.java import java.util.List; import decaf.*; import decaf.type.*; import decaf.scope.*; import decaf.symbol.*; import decaf.symbol.Class; import decaf.utils.IndentPrintWriter; import decaf.utils.MiscUtils; public Tree(int tag, Location loc) { super(); this.tag = tag; this.loc = loc; } public Location getLocation() { return loc; } /** * Set type field and return this tree. */ public Tree setType(Type type) { this.type = type; return this; } /** * Visit this tree with a given visitor. */ public void accept(Visitor v) { v.visitTree(this); } public abstract void printTo(IndentPrintWriter pw); public static class TopLevel extends Tree { public List<ClassDef> classes;
public Class main;
infinispan/infinispan-spark
src/test/java/org/infinispan/spark/JavaProtobufTest.java
// Path: src/test/java/org/infinispan/spark/domain/Runner.java // @ProtoName("runner") // @SerializeWith(Runner.RunnerExternalizer.class) // public class Runner implements Serializable { // // private String name; // // private Boolean finished; // // private int finishTimeSeconds; // // private int age; // // public Runner() { // } // // public Runner(String name, Boolean finished, int finishTimeSeconds, int age) { // this.name = name; // this.finished = finished; // this.finishTimeSeconds = finishTimeSeconds; // this.age = age; // } // // @ProtoField(number = 1, required = true) // public String getName() { // return name; // } // // @ProtoField(number = 2, required = true) // public Boolean getFinished() { // return finished; // } // // @ProtoField(number = 3, required = true) // public int getFinishTimeSeconds() { // return finishTimeSeconds; // } // // @ProtoField(number = 4, required = true) // public int getAge() { // return age; // } // // public void setName(String name) { // this.name = name; // } // // public void setFinished(Boolean finished) { // this.finished = finished; // } // // public void setFinishTimeSeconds(int finishTimeSeconds) { // this.finishTimeSeconds = finishTimeSeconds; // } // // public void setAge(int age) { // this.age = age; // } // // @Override // public String toString() { // return "Runner{" + // "name='" + name + '\'' + // ", finished=" + finished + // ", finishTimeSeconds=" + finishTimeSeconds + // ", age=" + age + // '}'; // } // // public static class RunnerExternalizer implements Externalizer<Runner> { // @Override // public void writeObject(ObjectOutput output, Runner object) throws IOException { // output.writeUTF(object.name); // output.writeBoolean(object.finished); // output.writeInt(object.finishTimeSeconds); // output.writeInt(object.age); // } // // @Override // public Runner readObject(ObjectInput input) throws IOException { // String name = input.readUTF(); // boolean finished = input.readBoolean(); // int finishedSeconds = input.readInt(); // int age = input.readInt(); // return new Runner(name, finished, finishedSeconds, age); // } // } // }
import org.apache.spark.api.java.JavaPairRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.apache.spark.sql.SparkSession; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.Search; import org.infinispan.query.dsl.Query; import org.infinispan.spark.config.ConnectorConfiguration; import org.infinispan.spark.domain.Runner; import org.infinispan.spark.rdd.InfinispanJavaRDD; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue;
package org.infinispan.spark; /** * @author gustavonalle */ public class JavaProtobufTest { private final SparkSession sparkSession;
// Path: src/test/java/org/infinispan/spark/domain/Runner.java // @ProtoName("runner") // @SerializeWith(Runner.RunnerExternalizer.class) // public class Runner implements Serializable { // // private String name; // // private Boolean finished; // // private int finishTimeSeconds; // // private int age; // // public Runner() { // } // // public Runner(String name, Boolean finished, int finishTimeSeconds, int age) { // this.name = name; // this.finished = finished; // this.finishTimeSeconds = finishTimeSeconds; // this.age = age; // } // // @ProtoField(number = 1, required = true) // public String getName() { // return name; // } // // @ProtoField(number = 2, required = true) // public Boolean getFinished() { // return finished; // } // // @ProtoField(number = 3, required = true) // public int getFinishTimeSeconds() { // return finishTimeSeconds; // } // // @ProtoField(number = 4, required = true) // public int getAge() { // return age; // } // // public void setName(String name) { // this.name = name; // } // // public void setFinished(Boolean finished) { // this.finished = finished; // } // // public void setFinishTimeSeconds(int finishTimeSeconds) { // this.finishTimeSeconds = finishTimeSeconds; // } // // public void setAge(int age) { // this.age = age; // } // // @Override // public String toString() { // return "Runner{" + // "name='" + name + '\'' + // ", finished=" + finished + // ", finishTimeSeconds=" + finishTimeSeconds + // ", age=" + age + // '}'; // } // // public static class RunnerExternalizer implements Externalizer<Runner> { // @Override // public void writeObject(ObjectOutput output, Runner object) throws IOException { // output.writeUTF(object.name); // output.writeBoolean(object.finished); // output.writeInt(object.finishTimeSeconds); // output.writeInt(object.age); // } // // @Override // public Runner readObject(ObjectInput input) throws IOException { // String name = input.readUTF(); // boolean finished = input.readBoolean(); // int finishedSeconds = input.readInt(); // int age = input.readInt(); // return new Runner(name, finished, finishedSeconds, age); // } // } // } // Path: src/test/java/org/infinispan/spark/JavaProtobufTest.java import org.apache.spark.api.java.JavaPairRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.apache.spark.sql.SparkSession; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.Search; import org.infinispan.query.dsl.Query; import org.infinispan.spark.config.ConnectorConfiguration; import org.infinispan.spark.domain.Runner; import org.infinispan.spark.rdd.InfinispanJavaRDD; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; package org.infinispan.spark; /** * @author gustavonalle */ public class JavaProtobufTest { private final SparkSession sparkSession;
private final RemoteCache<Integer, Runner> cache;
gamblore/AndroidPunk
src/net/androidpunk/tweens/misc/VarTween.java
// Path: src/net/androidpunk/Tween.java // public class Tween { // // /** // * Persistent Tween type, will stop when it finishes. // */ // public static final int PERSIST = 0; // // /** // * Looping Tween type, will restart immediately when it finishes. // */ // public static final int LOOPING = 1; // // /** // * Oneshot Tween type, will stop and remove itself from its core container when it finishes. // */ // public static final int ONESHOT = 2; // // /** // * If the tween should update. // */ // public boolean active = false; // // /** // * Tween completion callback. // */ // public OnCompleteCallback complete; // // // Tween information. // private int mType; // protected OnEaseCallback mEase; // protected float mT = 0; // // // Timing information. // protected float mTime; // protected float mTarget; // // // List information. // protected boolean mFinish; // protected Tweener mParent; // protected Tween mPrev; // protected Tween mNext; // // /** // * Constructor. Specify basic information about the Tween. // * @param duration Duration of the tween (in seconds or frames). // * @param type Tween type, one of Tween.PERSIST (default), Tween.LOOPING, or Tween.ONESHOT. // * @param complete Optional callback for when the Tween completes. // * @param ease Optional easer function to apply to the Tweened value. // */ // public Tween(float duration) { // this(duration, 0, null, null); // } // // public Tween(float duration, int type) { // this(duration, type, null, null); // } // // public Tween(float duration, int type, OnCompleteCallback completeFunction) { // this(duration, type, completeFunction, null); // } // // public Tween(float duration, int type, OnCompleteCallback completeFunction, OnEaseCallback easeFunction) { // mTarget = duration; // mType = type; // complete = completeFunction; // mEase = easeFunction; // } // // /** // * Updates the Tween, called by World. // */ // public void update() { // mTime += FP.fixed ? 1 : FP.elapsed; // // mT = mTime / mTarget; // if (mEase != null && mT > 0 && mT < 1) // mT = mEase.ease(mT); // if (mTime >= mTarget) { // mT = 1; // mFinish = true; // } // } // // /** // * Starts the Tween, or restarts it if it's currently running. // */ // public void start() { // mTime = 0; // if (mTarget == 0) { // active = false; // return; // } // active = true; // } // // /** @private Called when the Tween completes. */ // protected void finish() { // switch (mType) { // case PERSIST: // mTime = mTarget; // active = false; // break; // case LOOPING: // mTime %= mTarget; // mT = mTime / mTarget; // if (mEase != null && mT > 0 && mT < 1) // mT = mEase.ease(mT); // start(); // break; // case ONESHOT: // mTime = mTarget; // active = false; // mParent.removeTween(this); // break; // } // mFinish = false; // if (complete != null) // complete.completed(); // } // // public float getPercent() { // return mTime / mTarget; // } // // public void setPercent(float value) { // mTime = mTarget * value; // } // // public float getScale() { // return mT; // } // } // // Path: src/net/androidpunk/flashcompat/OnCompleteCallback.java // public abstract class OnCompleteCallback { // public abstract void completed(); // } // // Path: src/net/androidpunk/flashcompat/OnEaseCallback.java // public abstract class OnEaseCallback { // public abstract float ease(float t); // }
import java.lang.reflect.Field; import java.lang.reflect.Type; import net.androidpunk.Tween; import net.androidpunk.flashcompat.OnCompleteCallback; import net.androidpunk.flashcompat.OnEaseCallback; import android.util.Log;
package net.androidpunk.tweens.misc; /** * Tweens a numeric public property of an Object. */ public class VarTween extends Tween { private static final String TAG = "VarTween"; private static final int TYPE_CHAR = 0; private static final int TYPE_SHORT = 1; private static final int TYPE_INT = 2; private static final int TYPE_FLOAT = 3; private static final int TYPE_DOUBLE = 4; // Tween information. private Object mObject; private String mProperty; private Field mField; private int mType; private float mStart; private float mRange; /** * Constructor. * @param complete Optional completion callback. * @param type Tween type. */ public VarTween() { this(null, 0); } /** * Constructor. * @param complete Optional completion callback. * @param type Tween type. */
// Path: src/net/androidpunk/Tween.java // public class Tween { // // /** // * Persistent Tween type, will stop when it finishes. // */ // public static final int PERSIST = 0; // // /** // * Looping Tween type, will restart immediately when it finishes. // */ // public static final int LOOPING = 1; // // /** // * Oneshot Tween type, will stop and remove itself from its core container when it finishes. // */ // public static final int ONESHOT = 2; // // /** // * If the tween should update. // */ // public boolean active = false; // // /** // * Tween completion callback. // */ // public OnCompleteCallback complete; // // // Tween information. // private int mType; // protected OnEaseCallback mEase; // protected float mT = 0; // // // Timing information. // protected float mTime; // protected float mTarget; // // // List information. // protected boolean mFinish; // protected Tweener mParent; // protected Tween mPrev; // protected Tween mNext; // // /** // * Constructor. Specify basic information about the Tween. // * @param duration Duration of the tween (in seconds or frames). // * @param type Tween type, one of Tween.PERSIST (default), Tween.LOOPING, or Tween.ONESHOT. // * @param complete Optional callback for when the Tween completes. // * @param ease Optional easer function to apply to the Tweened value. // */ // public Tween(float duration) { // this(duration, 0, null, null); // } // // public Tween(float duration, int type) { // this(duration, type, null, null); // } // // public Tween(float duration, int type, OnCompleteCallback completeFunction) { // this(duration, type, completeFunction, null); // } // // public Tween(float duration, int type, OnCompleteCallback completeFunction, OnEaseCallback easeFunction) { // mTarget = duration; // mType = type; // complete = completeFunction; // mEase = easeFunction; // } // // /** // * Updates the Tween, called by World. // */ // public void update() { // mTime += FP.fixed ? 1 : FP.elapsed; // // mT = mTime / mTarget; // if (mEase != null && mT > 0 && mT < 1) // mT = mEase.ease(mT); // if (mTime >= mTarget) { // mT = 1; // mFinish = true; // } // } // // /** // * Starts the Tween, or restarts it if it's currently running. // */ // public void start() { // mTime = 0; // if (mTarget == 0) { // active = false; // return; // } // active = true; // } // // /** @private Called when the Tween completes. */ // protected void finish() { // switch (mType) { // case PERSIST: // mTime = mTarget; // active = false; // break; // case LOOPING: // mTime %= mTarget; // mT = mTime / mTarget; // if (mEase != null && mT > 0 && mT < 1) // mT = mEase.ease(mT); // start(); // break; // case ONESHOT: // mTime = mTarget; // active = false; // mParent.removeTween(this); // break; // } // mFinish = false; // if (complete != null) // complete.completed(); // } // // public float getPercent() { // return mTime / mTarget; // } // // public void setPercent(float value) { // mTime = mTarget * value; // } // // public float getScale() { // return mT; // } // } // // Path: src/net/androidpunk/flashcompat/OnCompleteCallback.java // public abstract class OnCompleteCallback { // public abstract void completed(); // } // // Path: src/net/androidpunk/flashcompat/OnEaseCallback.java // public abstract class OnEaseCallback { // public abstract float ease(float t); // } // Path: src/net/androidpunk/tweens/misc/VarTween.java import java.lang.reflect.Field; import java.lang.reflect.Type; import net.androidpunk.Tween; import net.androidpunk.flashcompat.OnCompleteCallback; import net.androidpunk.flashcompat.OnEaseCallback; import android.util.Log; package net.androidpunk.tweens.misc; /** * Tweens a numeric public property of an Object. */ public class VarTween extends Tween { private static final String TAG = "VarTween"; private static final int TYPE_CHAR = 0; private static final int TYPE_SHORT = 1; private static final int TYPE_INT = 2; private static final int TYPE_FLOAT = 3; private static final int TYPE_DOUBLE = 4; // Tween information. private Object mObject; private String mProperty; private Field mField; private int mType; private float mStart; private float mRange; /** * Constructor. * @param complete Optional completion callback. * @param type Tween type. */ public VarTween() { this(null, 0); } /** * Constructor. * @param complete Optional completion callback. * @param type Tween type. */
public VarTween(OnCompleteCallback completeFunction) {
gamblore/AndroidPunk
src/net/androidpunk/tweens/motion/LinearPath.java
// Path: src/net/androidpunk/flashcompat/OnCompleteCallback.java // public abstract class OnCompleteCallback { // public abstract void completed(); // } // // Path: src/net/androidpunk/flashcompat/OnEaseCallback.java // public abstract class OnEaseCallback { // public abstract float ease(float t); // }
import java.util.Vector; import net.androidpunk.flashcompat.OnCompleteCallback; import net.androidpunk.flashcompat.OnEaseCallback; import android.graphics.Point; import android.util.Log;
package net.androidpunk.tweens.motion; /** * Determines linear motion along a set of points. */ public class LinearPath extends Motion { private static final String TAG = "LinearPath"; // Path information. private Vector<Point> mPoints = new Vector<Point>(); private Vector<Float> mPointD = new Vector<Float>(); private Vector<Float> mPointT = new Vector<Float>(); private float mDistance = 0; private float mSpeed = 0; private int mIndex = 0; // Line information. private Point mLast; private Point mPrev; private Point mNext; /** * Constructor. * @param complete Optional completion callback. * @param type Tween type. */ public LinearPath() { this(null, 0); } /** * Constructor. * @param complete Optional completion callback. * @param type Tween type. */
// Path: src/net/androidpunk/flashcompat/OnCompleteCallback.java // public abstract class OnCompleteCallback { // public abstract void completed(); // } // // Path: src/net/androidpunk/flashcompat/OnEaseCallback.java // public abstract class OnEaseCallback { // public abstract float ease(float t); // } // Path: src/net/androidpunk/tweens/motion/LinearPath.java import java.util.Vector; import net.androidpunk.flashcompat.OnCompleteCallback; import net.androidpunk.flashcompat.OnEaseCallback; import android.graphics.Point; import android.util.Log; package net.androidpunk.tweens.motion; /** * Determines linear motion along a set of points. */ public class LinearPath extends Motion { private static final String TAG = "LinearPath"; // Path information. private Vector<Point> mPoints = new Vector<Point>(); private Vector<Float> mPointD = new Vector<Float>(); private Vector<Float> mPointT = new Vector<Float>(); private float mDistance = 0; private float mSpeed = 0; private int mIndex = 0; // Line information. private Point mLast; private Point mPrev; private Point mNext; /** * Constructor. * @param complete Optional completion callback. * @param type Tween type. */ public LinearPath() { this(null, 0); } /** * Constructor. * @param complete Optional completion callback. * @param type Tween type. */
public LinearPath(OnCompleteCallback completeFunction) {
gamblore/AndroidPunk
src/net/androidpunk/tweens/motion/LinearPath.java
// Path: src/net/androidpunk/flashcompat/OnCompleteCallback.java // public abstract class OnCompleteCallback { // public abstract void completed(); // } // // Path: src/net/androidpunk/flashcompat/OnEaseCallback.java // public abstract class OnEaseCallback { // public abstract float ease(float t); // }
import java.util.Vector; import net.androidpunk.flashcompat.OnCompleteCallback; import net.androidpunk.flashcompat.OnEaseCallback; import android.graphics.Point; import android.util.Log;
package net.androidpunk.tweens.motion; /** * Determines linear motion along a set of points. */ public class LinearPath extends Motion { private static final String TAG = "LinearPath"; // Path information. private Vector<Point> mPoints = new Vector<Point>(); private Vector<Float> mPointD = new Vector<Float>(); private Vector<Float> mPointT = new Vector<Float>(); private float mDistance = 0; private float mSpeed = 0; private int mIndex = 0; // Line information. private Point mLast; private Point mPrev; private Point mNext; /** * Constructor. * @param complete Optional completion callback. * @param type Tween type. */ public LinearPath() { this(null, 0); } /** * Constructor. * @param complete Optional completion callback. * @param type Tween type. */ public LinearPath(OnCompleteCallback completeFunction) { this(completeFunction, 0); } /** * Constructor. * @param complete Optional completion callback. * @param type Tween type. */ public LinearPath(OnCompleteCallback completeFunction, int type) { super(0, completeFunction, type, null); mPointD.add(0f); mPointT.add(0f); } /** * Starts moving along the path. * @param duration Duration of the movement. */ public void setMotion(float duration) { setMotion(duration, null); } /** * Starts moving along the path. * @param duration Duration of the movement. * @param ease Optional easer function. */
// Path: src/net/androidpunk/flashcompat/OnCompleteCallback.java // public abstract class OnCompleteCallback { // public abstract void completed(); // } // // Path: src/net/androidpunk/flashcompat/OnEaseCallback.java // public abstract class OnEaseCallback { // public abstract float ease(float t); // } // Path: src/net/androidpunk/tweens/motion/LinearPath.java import java.util.Vector; import net.androidpunk.flashcompat.OnCompleteCallback; import net.androidpunk.flashcompat.OnEaseCallback; import android.graphics.Point; import android.util.Log; package net.androidpunk.tweens.motion; /** * Determines linear motion along a set of points. */ public class LinearPath extends Motion { private static final String TAG = "LinearPath"; // Path information. private Vector<Point> mPoints = new Vector<Point>(); private Vector<Float> mPointD = new Vector<Float>(); private Vector<Float> mPointT = new Vector<Float>(); private float mDistance = 0; private float mSpeed = 0; private int mIndex = 0; // Line information. private Point mLast; private Point mPrev; private Point mNext; /** * Constructor. * @param complete Optional completion callback. * @param type Tween type. */ public LinearPath() { this(null, 0); } /** * Constructor. * @param complete Optional completion callback. * @param type Tween type. */ public LinearPath(OnCompleteCallback completeFunction) { this(completeFunction, 0); } /** * Constructor. * @param complete Optional completion callback. * @param type Tween type. */ public LinearPath(OnCompleteCallback completeFunction, int type) { super(0, completeFunction, type, null); mPointD.add(0f); mPointT.add(0f); } /** * Starts moving along the path. * @param duration Duration of the movement. */ public void setMotion(float duration) { setMotion(duration, null); } /** * Starts moving along the path. * @param duration Duration of the movement. * @param ease Optional easer function. */
public void setMotion(float duration, OnEaseCallback ease) {
gamblore/AndroidPunk
src/net/androidpunk/tweens/misc/Alarm.java
// Path: src/net/androidpunk/Tween.java // public class Tween { // // /** // * Persistent Tween type, will stop when it finishes. // */ // public static final int PERSIST = 0; // // /** // * Looping Tween type, will restart immediately when it finishes. // */ // public static final int LOOPING = 1; // // /** // * Oneshot Tween type, will stop and remove itself from its core container when it finishes. // */ // public static final int ONESHOT = 2; // // /** // * If the tween should update. // */ // public boolean active = false; // // /** // * Tween completion callback. // */ // public OnCompleteCallback complete; // // // Tween information. // private int mType; // protected OnEaseCallback mEase; // protected float mT = 0; // // // Timing information. // protected float mTime; // protected float mTarget; // // // List information. // protected boolean mFinish; // protected Tweener mParent; // protected Tween mPrev; // protected Tween mNext; // // /** // * Constructor. Specify basic information about the Tween. // * @param duration Duration of the tween (in seconds or frames). // * @param type Tween type, one of Tween.PERSIST (default), Tween.LOOPING, or Tween.ONESHOT. // * @param complete Optional callback for when the Tween completes. // * @param ease Optional easer function to apply to the Tweened value. // */ // public Tween(float duration) { // this(duration, 0, null, null); // } // // public Tween(float duration, int type) { // this(duration, type, null, null); // } // // public Tween(float duration, int type, OnCompleteCallback completeFunction) { // this(duration, type, completeFunction, null); // } // // public Tween(float duration, int type, OnCompleteCallback completeFunction, OnEaseCallback easeFunction) { // mTarget = duration; // mType = type; // complete = completeFunction; // mEase = easeFunction; // } // // /** // * Updates the Tween, called by World. // */ // public void update() { // mTime += FP.fixed ? 1 : FP.elapsed; // // mT = mTime / mTarget; // if (mEase != null && mT > 0 && mT < 1) // mT = mEase.ease(mT); // if (mTime >= mTarget) { // mT = 1; // mFinish = true; // } // } // // /** // * Starts the Tween, or restarts it if it's currently running. // */ // public void start() { // mTime = 0; // if (mTarget == 0) { // active = false; // return; // } // active = true; // } // // /** @private Called when the Tween completes. */ // protected void finish() { // switch (mType) { // case PERSIST: // mTime = mTarget; // active = false; // break; // case LOOPING: // mTime %= mTarget; // mT = mTime / mTarget; // if (mEase != null && mT > 0 && mT < 1) // mT = mEase.ease(mT); // start(); // break; // case ONESHOT: // mTime = mTarget; // active = false; // mParent.removeTween(this); // break; // } // mFinish = false; // if (complete != null) // complete.completed(); // } // // public float getPercent() { // return mTime / mTarget; // } // // public void setPercent(float value) { // mTime = mTarget * value; // } // // public float getScale() { // return mT; // } // } // // Path: src/net/androidpunk/flashcompat/OnCompleteCallback.java // public abstract class OnCompleteCallback { // public abstract void completed(); // }
import net.androidpunk.Tween; import net.androidpunk.flashcompat.OnCompleteCallback;
package net.androidpunk.tweens.misc; /** * A simple alarm, useful for timed events, etc. */ public class Alarm extends Tween { /** * Constructor. * @param duration Duration of the alarm. */ public Alarm(float duration) { super(duration, 0, null, null); } /** * Constructor. * @param duration Duration of the alarm. * @param complete Optional completion callback. */
// Path: src/net/androidpunk/Tween.java // public class Tween { // // /** // * Persistent Tween type, will stop when it finishes. // */ // public static final int PERSIST = 0; // // /** // * Looping Tween type, will restart immediately when it finishes. // */ // public static final int LOOPING = 1; // // /** // * Oneshot Tween type, will stop and remove itself from its core container when it finishes. // */ // public static final int ONESHOT = 2; // // /** // * If the tween should update. // */ // public boolean active = false; // // /** // * Tween completion callback. // */ // public OnCompleteCallback complete; // // // Tween information. // private int mType; // protected OnEaseCallback mEase; // protected float mT = 0; // // // Timing information. // protected float mTime; // protected float mTarget; // // // List information. // protected boolean mFinish; // protected Tweener mParent; // protected Tween mPrev; // protected Tween mNext; // // /** // * Constructor. Specify basic information about the Tween. // * @param duration Duration of the tween (in seconds or frames). // * @param type Tween type, one of Tween.PERSIST (default), Tween.LOOPING, or Tween.ONESHOT. // * @param complete Optional callback for when the Tween completes. // * @param ease Optional easer function to apply to the Tweened value. // */ // public Tween(float duration) { // this(duration, 0, null, null); // } // // public Tween(float duration, int type) { // this(duration, type, null, null); // } // // public Tween(float duration, int type, OnCompleteCallback completeFunction) { // this(duration, type, completeFunction, null); // } // // public Tween(float duration, int type, OnCompleteCallback completeFunction, OnEaseCallback easeFunction) { // mTarget = duration; // mType = type; // complete = completeFunction; // mEase = easeFunction; // } // // /** // * Updates the Tween, called by World. // */ // public void update() { // mTime += FP.fixed ? 1 : FP.elapsed; // // mT = mTime / mTarget; // if (mEase != null && mT > 0 && mT < 1) // mT = mEase.ease(mT); // if (mTime >= mTarget) { // mT = 1; // mFinish = true; // } // } // // /** // * Starts the Tween, or restarts it if it's currently running. // */ // public void start() { // mTime = 0; // if (mTarget == 0) { // active = false; // return; // } // active = true; // } // // /** @private Called when the Tween completes. */ // protected void finish() { // switch (mType) { // case PERSIST: // mTime = mTarget; // active = false; // break; // case LOOPING: // mTime %= mTarget; // mT = mTime / mTarget; // if (mEase != null && mT > 0 && mT < 1) // mT = mEase.ease(mT); // start(); // break; // case ONESHOT: // mTime = mTarget; // active = false; // mParent.removeTween(this); // break; // } // mFinish = false; // if (complete != null) // complete.completed(); // } // // public float getPercent() { // return mTime / mTarget; // } // // public void setPercent(float value) { // mTime = mTarget * value; // } // // public float getScale() { // return mT; // } // } // // Path: src/net/androidpunk/flashcompat/OnCompleteCallback.java // public abstract class OnCompleteCallback { // public abstract void completed(); // } // Path: src/net/androidpunk/tweens/misc/Alarm.java import net.androidpunk.Tween; import net.androidpunk.flashcompat.OnCompleteCallback; package net.androidpunk.tweens.misc; /** * A simple alarm, useful for timed events, etc. */ public class Alarm extends Tween { /** * Constructor. * @param duration Duration of the alarm. */ public Alarm(float duration) { super(duration, 0, null, null); } /** * Constructor. * @param duration Duration of the alarm. * @param complete Optional completion callback. */
public Alarm(float duration, OnCompleteCallback competeFunction) {
gamblore/AndroidPunk
src/net/androidpunk/tweens/misc/MultiVarTween.java
// Path: src/net/androidpunk/Tween.java // public class Tween { // // /** // * Persistent Tween type, will stop when it finishes. // */ // public static final int PERSIST = 0; // // /** // * Looping Tween type, will restart immediately when it finishes. // */ // public static final int LOOPING = 1; // // /** // * Oneshot Tween type, will stop and remove itself from its core container when it finishes. // */ // public static final int ONESHOT = 2; // // /** // * If the tween should update. // */ // public boolean active = false; // // /** // * Tween completion callback. // */ // public OnCompleteCallback complete; // // // Tween information. // private int mType; // protected OnEaseCallback mEase; // protected float mT = 0; // // // Timing information. // protected float mTime; // protected float mTarget; // // // List information. // protected boolean mFinish; // protected Tweener mParent; // protected Tween mPrev; // protected Tween mNext; // // /** // * Constructor. Specify basic information about the Tween. // * @param duration Duration of the tween (in seconds or frames). // * @param type Tween type, one of Tween.PERSIST (default), Tween.LOOPING, or Tween.ONESHOT. // * @param complete Optional callback for when the Tween completes. // * @param ease Optional easer function to apply to the Tweened value. // */ // public Tween(float duration) { // this(duration, 0, null, null); // } // // public Tween(float duration, int type) { // this(duration, type, null, null); // } // // public Tween(float duration, int type, OnCompleteCallback completeFunction) { // this(duration, type, completeFunction, null); // } // // public Tween(float duration, int type, OnCompleteCallback completeFunction, OnEaseCallback easeFunction) { // mTarget = duration; // mType = type; // complete = completeFunction; // mEase = easeFunction; // } // // /** // * Updates the Tween, called by World. // */ // public void update() { // mTime += FP.fixed ? 1 : FP.elapsed; // // mT = mTime / mTarget; // if (mEase != null && mT > 0 && mT < 1) // mT = mEase.ease(mT); // if (mTime >= mTarget) { // mT = 1; // mFinish = true; // } // } // // /** // * Starts the Tween, or restarts it if it's currently running. // */ // public void start() { // mTime = 0; // if (mTarget == 0) { // active = false; // return; // } // active = true; // } // // /** @private Called when the Tween completes. */ // protected void finish() { // switch (mType) { // case PERSIST: // mTime = mTarget; // active = false; // break; // case LOOPING: // mTime %= mTarget; // mT = mTime / mTarget; // if (mEase != null && mT > 0 && mT < 1) // mT = mEase.ease(mT); // start(); // break; // case ONESHOT: // mTime = mTarget; // active = false; // mParent.removeTween(this); // break; // } // mFinish = false; // if (complete != null) // complete.completed(); // } // // public float getPercent() { // return mTime / mTarget; // } // // public void setPercent(float value) { // mTime = mTarget * value; // } // // public float getScale() { // return mT; // } // } // // Path: src/net/androidpunk/flashcompat/OnCompleteCallback.java // public abstract class OnCompleteCallback { // public abstract void completed(); // } // // Path: src/net/androidpunk/flashcompat/OnEaseCallback.java // public abstract class OnEaseCallback { // public abstract float ease(float t); // }
import java.lang.reflect.Field; import java.util.Map; import java.util.Vector; import net.androidpunk.Tween; import net.androidpunk.flashcompat.OnCompleteCallback; import net.androidpunk.flashcompat.OnEaseCallback; import android.util.Log;
package net.androidpunk.tweens.misc; public class MultiVarTween extends Tween { private static final String TAG = "MultiVarTween"; private Object mObject; private Vector<String> mVars = new Vector<String>(); private Vector<Float> mStart = new Vector<Float>(); private Vector<Float> mRange = new Vector<Float>(); public MultiVarTween() { super(0, 0, null); }
// Path: src/net/androidpunk/Tween.java // public class Tween { // // /** // * Persistent Tween type, will stop when it finishes. // */ // public static final int PERSIST = 0; // // /** // * Looping Tween type, will restart immediately when it finishes. // */ // public static final int LOOPING = 1; // // /** // * Oneshot Tween type, will stop and remove itself from its core container when it finishes. // */ // public static final int ONESHOT = 2; // // /** // * If the tween should update. // */ // public boolean active = false; // // /** // * Tween completion callback. // */ // public OnCompleteCallback complete; // // // Tween information. // private int mType; // protected OnEaseCallback mEase; // protected float mT = 0; // // // Timing information. // protected float mTime; // protected float mTarget; // // // List information. // protected boolean mFinish; // protected Tweener mParent; // protected Tween mPrev; // protected Tween mNext; // // /** // * Constructor. Specify basic information about the Tween. // * @param duration Duration of the tween (in seconds or frames). // * @param type Tween type, one of Tween.PERSIST (default), Tween.LOOPING, or Tween.ONESHOT. // * @param complete Optional callback for when the Tween completes. // * @param ease Optional easer function to apply to the Tweened value. // */ // public Tween(float duration) { // this(duration, 0, null, null); // } // // public Tween(float duration, int type) { // this(duration, type, null, null); // } // // public Tween(float duration, int type, OnCompleteCallback completeFunction) { // this(duration, type, completeFunction, null); // } // // public Tween(float duration, int type, OnCompleteCallback completeFunction, OnEaseCallback easeFunction) { // mTarget = duration; // mType = type; // complete = completeFunction; // mEase = easeFunction; // } // // /** // * Updates the Tween, called by World. // */ // public void update() { // mTime += FP.fixed ? 1 : FP.elapsed; // // mT = mTime / mTarget; // if (mEase != null && mT > 0 && mT < 1) // mT = mEase.ease(mT); // if (mTime >= mTarget) { // mT = 1; // mFinish = true; // } // } // // /** // * Starts the Tween, or restarts it if it's currently running. // */ // public void start() { // mTime = 0; // if (mTarget == 0) { // active = false; // return; // } // active = true; // } // // /** @private Called when the Tween completes. */ // protected void finish() { // switch (mType) { // case PERSIST: // mTime = mTarget; // active = false; // break; // case LOOPING: // mTime %= mTarget; // mT = mTime / mTarget; // if (mEase != null && mT > 0 && mT < 1) // mT = mEase.ease(mT); // start(); // break; // case ONESHOT: // mTime = mTarget; // active = false; // mParent.removeTween(this); // break; // } // mFinish = false; // if (complete != null) // complete.completed(); // } // // public float getPercent() { // return mTime / mTarget; // } // // public void setPercent(float value) { // mTime = mTarget * value; // } // // public float getScale() { // return mT; // } // } // // Path: src/net/androidpunk/flashcompat/OnCompleteCallback.java // public abstract class OnCompleteCallback { // public abstract void completed(); // } // // Path: src/net/androidpunk/flashcompat/OnEaseCallback.java // public abstract class OnEaseCallback { // public abstract float ease(float t); // } // Path: src/net/androidpunk/tweens/misc/MultiVarTween.java import java.lang.reflect.Field; import java.util.Map; import java.util.Vector; import net.androidpunk.Tween; import net.androidpunk.flashcompat.OnCompleteCallback; import net.androidpunk.flashcompat.OnEaseCallback; import android.util.Log; package net.androidpunk.tweens.misc; public class MultiVarTween extends Tween { private static final String TAG = "MultiVarTween"; private Object mObject; private Vector<String> mVars = new Vector<String>(); private Vector<Float> mStart = new Vector<Float>(); private Vector<Float> mRange = new Vector<Float>(); public MultiVarTween() { super(0, 0, null); }
public MultiVarTween(OnCompleteCallback completeFunction) {
gamblore/AndroidPunk
src/net/androidpunk/graphics/atlas/Image.java
// Path: src/net/androidpunk/graphics/opengl/SubTexture.java // public class SubTexture { // // private final Rect mRect = new Rect(); // private Texture mTexture; // // /** // * Create a subtexture object to describe a texture in a texture. // * @param t The base Texture to use. // * @param x The start x coord of the subtexture (in pixels). // * @param y The start y coord of the subtexture (in pixels). // * @param width The width of the subtexture (in pixels). // * @param height The height of the subtexture (in pixels). // */ // public SubTexture(Texture t, int x, int y, int width, int height) { // mTexture = t; // mRect.set(x,y,x+width,y+height); // } // // /** // * Gets the texture this subtexture uses. // * @return The subtexture. // */ // public Texture getTexture() { // return mTexture; // } // // /** // * The bounds of the whole subtexture. // * @return // */ // public Rect getBounds() { // return mRect; // } // // /** // * The width of the subtexture. // * @return // */ // public int getWidth() { // return mRect.width(); // } // // /** // * The height of the subtexture. // * @return // */ // public int getHeight() { // return mRect.height(); // } // // /** // * Set a rect to the clip for that frame in the whole texture // * @param r the rect to set to the clip of the whole texture. // */ // public void getFrame(Rect r, int index, int frameWidth, int frameHeight) { // int x = index * frameWidth; // int y = (x / mRect.width()) * frameHeight; // x %= mRect.width(); // r.set(mRect.left + x, mRect.top + y, mRect.left + x + frameWidth, mRect.top + y + frameHeight); // } // // /** // * Set a rec to the clip based on a relative rect. // * @param clipRect the rect to set to the clip of the whole texture. // * @param relativeClipRect a relative rect of the subtexture. // */ // public void GetAbsoluteClipRect(Rect clipRect, Rect relativeClipRect) { // int width = relativeClipRect.width(); // int height = relativeClipRect.height(); // clipRect.left = relativeClipRect.left + mRect.left; // clipRect.top = relativeClipRect.top + mRect.top; // clipRect.right = clipRect.left + width; // clipRect.bottom = clipRect.top + height; // } // }
import java.nio.FloatBuffer; import javax.microedition.khronos.opengles.GL10; import net.androidpunk.graphics.opengl.SubTexture; import android.graphics.Point; import android.graphics.Rect;
package net.androidpunk.graphics.atlas; public class Image extends AtlasGraphic { protected Rect mClipRect = new Rect(); protected FloatBuffer mVertexBuffer = AtlasGraphic.getDirectFloatBuffer(8); protected FloatBuffer mTextureBuffer = AtlasGraphic.getDirectFloatBuffer(8);
// Path: src/net/androidpunk/graphics/opengl/SubTexture.java // public class SubTexture { // // private final Rect mRect = new Rect(); // private Texture mTexture; // // /** // * Create a subtexture object to describe a texture in a texture. // * @param t The base Texture to use. // * @param x The start x coord of the subtexture (in pixels). // * @param y The start y coord of the subtexture (in pixels). // * @param width The width of the subtexture (in pixels). // * @param height The height of the subtexture (in pixels). // */ // public SubTexture(Texture t, int x, int y, int width, int height) { // mTexture = t; // mRect.set(x,y,x+width,y+height); // } // // /** // * Gets the texture this subtexture uses. // * @return The subtexture. // */ // public Texture getTexture() { // return mTexture; // } // // /** // * The bounds of the whole subtexture. // * @return // */ // public Rect getBounds() { // return mRect; // } // // /** // * The width of the subtexture. // * @return // */ // public int getWidth() { // return mRect.width(); // } // // /** // * The height of the subtexture. // * @return // */ // public int getHeight() { // return mRect.height(); // } // // /** // * Set a rect to the clip for that frame in the whole texture // * @param r the rect to set to the clip of the whole texture. // */ // public void getFrame(Rect r, int index, int frameWidth, int frameHeight) { // int x = index * frameWidth; // int y = (x / mRect.width()) * frameHeight; // x %= mRect.width(); // r.set(mRect.left + x, mRect.top + y, mRect.left + x + frameWidth, mRect.top + y + frameHeight); // } // // /** // * Set a rec to the clip based on a relative rect. // * @param clipRect the rect to set to the clip of the whole texture. // * @param relativeClipRect a relative rect of the subtexture. // */ // public void GetAbsoluteClipRect(Rect clipRect, Rect relativeClipRect) { // int width = relativeClipRect.width(); // int height = relativeClipRect.height(); // clipRect.left = relativeClipRect.left + mRect.left; // clipRect.top = relativeClipRect.top + mRect.top; // clipRect.right = clipRect.left + width; // clipRect.bottom = clipRect.top + height; // } // } // Path: src/net/androidpunk/graphics/atlas/Image.java import java.nio.FloatBuffer; import javax.microedition.khronos.opengles.GL10; import net.androidpunk.graphics.opengl.SubTexture; import android.graphics.Point; import android.graphics.Rect; package net.androidpunk.graphics.atlas; public class Image extends AtlasGraphic { protected Rect mClipRect = new Rect(); protected FloatBuffer mVertexBuffer = AtlasGraphic.getDirectFloatBuffer(8); protected FloatBuffer mTextureBuffer = AtlasGraphic.getDirectFloatBuffer(8);
public Image(SubTexture subTexture) {
gamblore/AndroidPunk
src/net/androidpunk/tweens/motion/CublicMotion.java
// Path: src/net/androidpunk/flashcompat/OnCompleteCallback.java // public abstract class OnCompleteCallback { // public abstract void completed(); // } // // Path: src/net/androidpunk/flashcompat/OnEaseCallback.java // public abstract class OnEaseCallback { // public abstract float ease(float t); // }
import net.androidpunk.flashcompat.OnCompleteCallback; import net.androidpunk.flashcompat.OnEaseCallback;
package net.androidpunk.tweens.motion; /** * Determines motion along a cubic curve. */ public class CublicMotion extends Motion { // Curve information. private float mFromX = 0; private float mFromY = 0; private float mToX = 0; private float mToY = 0; private float mAX = 0; private float mAY = 0; private float mBX = 0; private float mBY = 0; private float mTTT; private float mTT; /** * Constructor. */ public CublicMotion() { super(0, null, 0, null); } /** * Constructor. * @param complete Optional completion callback. */
// Path: src/net/androidpunk/flashcompat/OnCompleteCallback.java // public abstract class OnCompleteCallback { // public abstract void completed(); // } // // Path: src/net/androidpunk/flashcompat/OnEaseCallback.java // public abstract class OnEaseCallback { // public abstract float ease(float t); // } // Path: src/net/androidpunk/tweens/motion/CublicMotion.java import net.androidpunk.flashcompat.OnCompleteCallback; import net.androidpunk.flashcompat.OnEaseCallback; package net.androidpunk.tweens.motion; /** * Determines motion along a cubic curve. */ public class CublicMotion extends Motion { // Curve information. private float mFromX = 0; private float mFromY = 0; private float mToX = 0; private float mToY = 0; private float mAX = 0; private float mAY = 0; private float mBX = 0; private float mBY = 0; private float mTTT; private float mTT; /** * Constructor. */ public CublicMotion() { super(0, null, 0, null); } /** * Constructor. * @param complete Optional completion callback. */
public CublicMotion(OnCompleteCallback completeFunction) {
gamblore/AndroidPunk
src/net/androidpunk/tweens/motion/CublicMotion.java
// Path: src/net/androidpunk/flashcompat/OnCompleteCallback.java // public abstract class OnCompleteCallback { // public abstract void completed(); // } // // Path: src/net/androidpunk/flashcompat/OnEaseCallback.java // public abstract class OnEaseCallback { // public abstract float ease(float t); // }
import net.androidpunk.flashcompat.OnCompleteCallback; import net.androidpunk.flashcompat.OnEaseCallback;
package net.androidpunk.tweens.motion; /** * Determines motion along a cubic curve. */ public class CublicMotion extends Motion { // Curve information. private float mFromX = 0; private float mFromY = 0; private float mToX = 0; private float mToY = 0; private float mAX = 0; private float mAY = 0; private float mBX = 0; private float mBY = 0; private float mTTT; private float mTT; /** * Constructor. */ public CublicMotion() { super(0, null, 0, null); } /** * Constructor. * @param complete Optional completion callback. */ public CublicMotion(OnCompleteCallback completeFunction) { super(0, completeFunction, 0, null); } /** * Constructor. * @param complete Optional completion callback. * @param type Tween type. */ public CublicMotion(OnCompleteCallback completeFunction, int type) { super(0, completeFunction, type, null); } /** * Starts moving along the curve. * @param fromX X start. * @param fromY Y start. * @param aX First control x. * @param aY First control y. * @param bX Second control x. * @param bY Second control y. * @param toX X finish. * @param toY Y finish. * @param duration Duration of the movement. */ public void setMotion(float fromX, float fromY, float aX, float aY, float bX, float bY, float toX, float toY, float duration) { setMotion(fromX, fromY, aX, aY, bX, bY, toX, toY, duration, null); } /** * Starts moving along the curve. * @param fromX X start. * @param fromY Y start. * @param aX First control x. * @param aY First control y. * @param bX Second control x. * @param bY Second control y. * @param toX X finish. * @param toY Y finish. * @param duration Duration of the movement. * @param ease Optional easer function. */
// Path: src/net/androidpunk/flashcompat/OnCompleteCallback.java // public abstract class OnCompleteCallback { // public abstract void completed(); // } // // Path: src/net/androidpunk/flashcompat/OnEaseCallback.java // public abstract class OnEaseCallback { // public abstract float ease(float t); // } // Path: src/net/androidpunk/tweens/motion/CublicMotion.java import net.androidpunk.flashcompat.OnCompleteCallback; import net.androidpunk.flashcompat.OnEaseCallback; package net.androidpunk.tweens.motion; /** * Determines motion along a cubic curve. */ public class CublicMotion extends Motion { // Curve information. private float mFromX = 0; private float mFromY = 0; private float mToX = 0; private float mToY = 0; private float mAX = 0; private float mAY = 0; private float mBX = 0; private float mBY = 0; private float mTTT; private float mTT; /** * Constructor. */ public CublicMotion() { super(0, null, 0, null); } /** * Constructor. * @param complete Optional completion callback. */ public CublicMotion(OnCompleteCallback completeFunction) { super(0, completeFunction, 0, null); } /** * Constructor. * @param complete Optional completion callback. * @param type Tween type. */ public CublicMotion(OnCompleteCallback completeFunction, int type) { super(0, completeFunction, type, null); } /** * Starts moving along the curve. * @param fromX X start. * @param fromY Y start. * @param aX First control x. * @param aY First control y. * @param bX Second control x. * @param bY Second control y. * @param toX X finish. * @param toY Y finish. * @param duration Duration of the movement. */ public void setMotion(float fromX, float fromY, float aX, float aY, float bX, float bY, float toX, float toY, float duration) { setMotion(fromX, fromY, aX, aY, bX, bY, toX, toY, duration, null); } /** * Starts moving along the curve. * @param fromX X start. * @param fromY Y start. * @param aX First control x. * @param aY First control y. * @param bX Second control x. * @param bY Second control y. * @param toX X finish. * @param toY Y finish. * @param duration Duration of the movement. * @param ease Optional easer function. */
public void setMotion(float fromX, float fromY, float aX, float aY, float bX, float bY, float toX, float toY, float duration, OnEaseCallback ease) {
gamblore/AndroidPunk
src/net/androidpunk/Mask.java
// Path: src/net/androidpunk/masks/CollideCallback.java // public abstract class CollideCallback { // // public abstract boolean collide(Mask m); // // } // // Path: src/net/androidpunk/masks/MaskList.java // public class MaskList extends Hitbox { // // private Vector<Mask> mMasks = new Vector<Mask>(); // // public MaskList(Mask... args) { // for(Mask m : args) { // add(m); // } // } // // /** @private Collide against a mask. */ // @Override // public boolean collide(Mask mask) { // for (Mask m : mMasks) { // if (m.collide(mask)) return true; // } // return false; // } // // /** @private Collide against a MaskList. */ // @Override // protected boolean collideMaskList(MaskList other) { // for (Mask a : mMasks) { // for (Mask b : other.mMasks) { // if (a.collide(b)) return true; // } // } // return false; // } // // /** // * Adds a Mask to the list. // * @param mask The Mask to add. // * @return The added Mask. // */ // public Mask add(Mask mask) { // mMasks.add(mask); // mask.list = this; // mask.parent = parent; // update(); // return mask; // } // // /** // * Removes the Mask from the list. // * @param mask The Mask to remove. // * @return The removed Mask. // */ // public Mask remove(Mask mask) { // mMasks.remove(mask); // return mask; // } // // /** // * Removes the Mask at the index. // * @param index The Mask index. // */ // public void removeAt(int index) { // mMasks.remove(index); // } // // /** // * Removes all Masks from the list. // */ // public void removeAll() { // for (Mask m : mMasks) { // m.list = null; // } // mMasks.clear(); // update(); // } // // /** // * Gets a Mask from the list. // * @param index The Mask index. // * @return The Mask at the index. // */ // public Mask getMask(int index) { // return mMasks.get(index % mMasks.size()); // } // // @Override // public void assignTo(Entity parent) { // for (Mask m : mMasks) { // m.parent = parent; // } // super.assignTo(parent); // } // // /** @private Updates the parent's bounds for this mask. */ // @Override // protected void update() { // // find bounds of the contained masks // int t = 0,l = 0, r = 0, b = 0; // boolean matchFound = false; // for (Mask m : mMasks) { // if (m instanceof Hitbox) { // Hitbox h = (Hitbox)m; // l = h.getX(); // t = h.getY(); // r = h.getX() + h.getWidth(); // b = h.getY() + h.getHeight(); // matchFound = true; // break; // } // } // if (!matchFound) { // super.update(); // return; // } // // int i = mMasks.size(); // for (Mask m : mMasks) { // if (m instanceof Hitbox) { // Hitbox h = (Hitbox)m; // if (h.getX() < l) // l = h.getX(); // if (h.getY() < t) // t = h.getY(); // if (h.getX() + h.getWidth() > r) // r = h.getX() + h.getWidth(); // if (h.getY() + h.getHeight() > b) // b = h.getY() + h.getHeight(); // } // } // // // update hitbox bounds // mX = l; // mY = t; // mWidth = r - l; // mHeight = b - t; // super.update(); // } // // /** Used to render debug information in console. */ // @Override // public void renderDebug(Canvas c) { // for (Mask m : mMasks) { // m.renderDebug(c); // } // } // // public int getCount() { // return mMasks.size(); // } // }
import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Point; import android.graphics.Rect; import net.androidpunk.masks.CollideCallback; import net.androidpunk.masks.MaskList; import java.util.HashMap; import java.util.Map;
package net.androidpunk; public class Mask { /** * The parent Entity of this mask. */ public Entity parent; /** * The parent Masklist of the mask. */
// Path: src/net/androidpunk/masks/CollideCallback.java // public abstract class CollideCallback { // // public abstract boolean collide(Mask m); // // } // // Path: src/net/androidpunk/masks/MaskList.java // public class MaskList extends Hitbox { // // private Vector<Mask> mMasks = new Vector<Mask>(); // // public MaskList(Mask... args) { // for(Mask m : args) { // add(m); // } // } // // /** @private Collide against a mask. */ // @Override // public boolean collide(Mask mask) { // for (Mask m : mMasks) { // if (m.collide(mask)) return true; // } // return false; // } // // /** @private Collide against a MaskList. */ // @Override // protected boolean collideMaskList(MaskList other) { // for (Mask a : mMasks) { // for (Mask b : other.mMasks) { // if (a.collide(b)) return true; // } // } // return false; // } // // /** // * Adds a Mask to the list. // * @param mask The Mask to add. // * @return The added Mask. // */ // public Mask add(Mask mask) { // mMasks.add(mask); // mask.list = this; // mask.parent = parent; // update(); // return mask; // } // // /** // * Removes the Mask from the list. // * @param mask The Mask to remove. // * @return The removed Mask. // */ // public Mask remove(Mask mask) { // mMasks.remove(mask); // return mask; // } // // /** // * Removes the Mask at the index. // * @param index The Mask index. // */ // public void removeAt(int index) { // mMasks.remove(index); // } // // /** // * Removes all Masks from the list. // */ // public void removeAll() { // for (Mask m : mMasks) { // m.list = null; // } // mMasks.clear(); // update(); // } // // /** // * Gets a Mask from the list. // * @param index The Mask index. // * @return The Mask at the index. // */ // public Mask getMask(int index) { // return mMasks.get(index % mMasks.size()); // } // // @Override // public void assignTo(Entity parent) { // for (Mask m : mMasks) { // m.parent = parent; // } // super.assignTo(parent); // } // // /** @private Updates the parent's bounds for this mask. */ // @Override // protected void update() { // // find bounds of the contained masks // int t = 0,l = 0, r = 0, b = 0; // boolean matchFound = false; // for (Mask m : mMasks) { // if (m instanceof Hitbox) { // Hitbox h = (Hitbox)m; // l = h.getX(); // t = h.getY(); // r = h.getX() + h.getWidth(); // b = h.getY() + h.getHeight(); // matchFound = true; // break; // } // } // if (!matchFound) { // super.update(); // return; // } // // int i = mMasks.size(); // for (Mask m : mMasks) { // if (m instanceof Hitbox) { // Hitbox h = (Hitbox)m; // if (h.getX() < l) // l = h.getX(); // if (h.getY() < t) // t = h.getY(); // if (h.getX() + h.getWidth() > r) // r = h.getX() + h.getWidth(); // if (h.getY() + h.getHeight() > b) // b = h.getY() + h.getHeight(); // } // } // // // update hitbox bounds // mX = l; // mY = t; // mWidth = r - l; // mHeight = b - t; // super.update(); // } // // /** Used to render debug information in console. */ // @Override // public void renderDebug(Canvas c) { // for (Mask m : mMasks) { // m.renderDebug(c); // } // } // // public int getCount() { // return mMasks.size(); // } // } // Path: src/net/androidpunk/Mask.java import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Point; import android.graphics.Rect; import net.androidpunk.masks.CollideCallback; import net.androidpunk.masks.MaskList; import java.util.HashMap; import java.util.Map; package net.androidpunk; public class Mask { /** * The parent Entity of this mask. */ public Entity parent; /** * The parent Masklist of the mask. */
public MaskList list;
gamblore/AndroidPunk
src/net/androidpunk/Mask.java
// Path: src/net/androidpunk/masks/CollideCallback.java // public abstract class CollideCallback { // // public abstract boolean collide(Mask m); // // } // // Path: src/net/androidpunk/masks/MaskList.java // public class MaskList extends Hitbox { // // private Vector<Mask> mMasks = new Vector<Mask>(); // // public MaskList(Mask... args) { // for(Mask m : args) { // add(m); // } // } // // /** @private Collide against a mask. */ // @Override // public boolean collide(Mask mask) { // for (Mask m : mMasks) { // if (m.collide(mask)) return true; // } // return false; // } // // /** @private Collide against a MaskList. */ // @Override // protected boolean collideMaskList(MaskList other) { // for (Mask a : mMasks) { // for (Mask b : other.mMasks) { // if (a.collide(b)) return true; // } // } // return false; // } // // /** // * Adds a Mask to the list. // * @param mask The Mask to add. // * @return The added Mask. // */ // public Mask add(Mask mask) { // mMasks.add(mask); // mask.list = this; // mask.parent = parent; // update(); // return mask; // } // // /** // * Removes the Mask from the list. // * @param mask The Mask to remove. // * @return The removed Mask. // */ // public Mask remove(Mask mask) { // mMasks.remove(mask); // return mask; // } // // /** // * Removes the Mask at the index. // * @param index The Mask index. // */ // public void removeAt(int index) { // mMasks.remove(index); // } // // /** // * Removes all Masks from the list. // */ // public void removeAll() { // for (Mask m : mMasks) { // m.list = null; // } // mMasks.clear(); // update(); // } // // /** // * Gets a Mask from the list. // * @param index The Mask index. // * @return The Mask at the index. // */ // public Mask getMask(int index) { // return mMasks.get(index % mMasks.size()); // } // // @Override // public void assignTo(Entity parent) { // for (Mask m : mMasks) { // m.parent = parent; // } // super.assignTo(parent); // } // // /** @private Updates the parent's bounds for this mask. */ // @Override // protected void update() { // // find bounds of the contained masks // int t = 0,l = 0, r = 0, b = 0; // boolean matchFound = false; // for (Mask m : mMasks) { // if (m instanceof Hitbox) { // Hitbox h = (Hitbox)m; // l = h.getX(); // t = h.getY(); // r = h.getX() + h.getWidth(); // b = h.getY() + h.getHeight(); // matchFound = true; // break; // } // } // if (!matchFound) { // super.update(); // return; // } // // int i = mMasks.size(); // for (Mask m : mMasks) { // if (m instanceof Hitbox) { // Hitbox h = (Hitbox)m; // if (h.getX() < l) // l = h.getX(); // if (h.getY() < t) // t = h.getY(); // if (h.getX() + h.getWidth() > r) // r = h.getX() + h.getWidth(); // if (h.getY() + h.getHeight() > b) // b = h.getY() + h.getHeight(); // } // } // // // update hitbox bounds // mX = l; // mY = t; // mWidth = r - l; // mHeight = b - t; // super.update(); // } // // /** Used to render debug information in console. */ // @Override // public void renderDebug(Canvas c) { // for (Mask m : mMasks) { // m.renderDebug(c); // } // } // // public int getCount() { // return mMasks.size(); // } // }
import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Point; import android.graphics.Rect; import net.androidpunk.masks.CollideCallback; import net.androidpunk.masks.MaskList; import java.util.HashMap; import java.util.Map;
package net.androidpunk; public class Mask { /** * The parent Entity of this mask. */ public Entity parent; /** * The parent Masklist of the mask. */ public MaskList list;
// Path: src/net/androidpunk/masks/CollideCallback.java // public abstract class CollideCallback { // // public abstract boolean collide(Mask m); // // } // // Path: src/net/androidpunk/masks/MaskList.java // public class MaskList extends Hitbox { // // private Vector<Mask> mMasks = new Vector<Mask>(); // // public MaskList(Mask... args) { // for(Mask m : args) { // add(m); // } // } // // /** @private Collide against a mask. */ // @Override // public boolean collide(Mask mask) { // for (Mask m : mMasks) { // if (m.collide(mask)) return true; // } // return false; // } // // /** @private Collide against a MaskList. */ // @Override // protected boolean collideMaskList(MaskList other) { // for (Mask a : mMasks) { // for (Mask b : other.mMasks) { // if (a.collide(b)) return true; // } // } // return false; // } // // /** // * Adds a Mask to the list. // * @param mask The Mask to add. // * @return The added Mask. // */ // public Mask add(Mask mask) { // mMasks.add(mask); // mask.list = this; // mask.parent = parent; // update(); // return mask; // } // // /** // * Removes the Mask from the list. // * @param mask The Mask to remove. // * @return The removed Mask. // */ // public Mask remove(Mask mask) { // mMasks.remove(mask); // return mask; // } // // /** // * Removes the Mask at the index. // * @param index The Mask index. // */ // public void removeAt(int index) { // mMasks.remove(index); // } // // /** // * Removes all Masks from the list. // */ // public void removeAll() { // for (Mask m : mMasks) { // m.list = null; // } // mMasks.clear(); // update(); // } // // /** // * Gets a Mask from the list. // * @param index The Mask index. // * @return The Mask at the index. // */ // public Mask getMask(int index) { // return mMasks.get(index % mMasks.size()); // } // // @Override // public void assignTo(Entity parent) { // for (Mask m : mMasks) { // m.parent = parent; // } // super.assignTo(parent); // } // // /** @private Updates the parent's bounds for this mask. */ // @Override // protected void update() { // // find bounds of the contained masks // int t = 0,l = 0, r = 0, b = 0; // boolean matchFound = false; // for (Mask m : mMasks) { // if (m instanceof Hitbox) { // Hitbox h = (Hitbox)m; // l = h.getX(); // t = h.getY(); // r = h.getX() + h.getWidth(); // b = h.getY() + h.getHeight(); // matchFound = true; // break; // } // } // if (!matchFound) { // super.update(); // return; // } // // int i = mMasks.size(); // for (Mask m : mMasks) { // if (m instanceof Hitbox) { // Hitbox h = (Hitbox)m; // if (h.getX() < l) // l = h.getX(); // if (h.getY() < t) // t = h.getY(); // if (h.getX() + h.getWidth() > r) // r = h.getX() + h.getWidth(); // if (h.getY() + h.getHeight() > b) // b = h.getY() + h.getHeight(); // } // } // // // update hitbox bounds // mX = l; // mY = t; // mWidth = r - l; // mHeight = b - t; // super.update(); // } // // /** Used to render debug information in console. */ // @Override // public void renderDebug(Canvas c) { // for (Mask m : mMasks) { // m.renderDebug(c); // } // } // // public int getCount() { // return mMasks.size(); // } // } // Path: src/net/androidpunk/Mask.java import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Point; import android.graphics.Rect; import net.androidpunk.masks.CollideCallback; import net.androidpunk.masks.MaskList; import java.util.HashMap; import java.util.Map; package net.androidpunk; public class Mask { /** * The parent Entity of this mask. */ public Entity parent; /** * The parent Masklist of the mask. */ public MaskList list;
public final Map<Class<?>, CollideCallback> mCheck = new HashMap<Class<?>, CollideCallback>();
gamblore/AndroidPunk
src/net/androidpunk/Sfx.java
// Path: src/net/androidpunk/flashcompat/OnCompleteCallback.java // public abstract class OnCompleteCallback { // public abstract void completed(); // }
import java.util.Vector; import android.content.res.AssetFileDescriptor; import android.media.AudioManager; import android.media.SoundPool; import net.androidpunk.flashcompat.OnCompleteCallback;
package net.androidpunk; /** * Sound effect object used to play embedded sounds. */ public class Sfx { private static final String TAG = "Sfx"; /** * Optional callback function for when the sound finishes playing. */
// Path: src/net/androidpunk/flashcompat/OnCompleteCallback.java // public abstract class OnCompleteCallback { // public abstract void completed(); // } // Path: src/net/androidpunk/Sfx.java import java.util.Vector; import android.content.res.AssetFileDescriptor; import android.media.AudioManager; import android.media.SoundPool; import net.androidpunk.flashcompat.OnCompleteCallback; package net.androidpunk; /** * Sound effect object used to play embedded sounds. */ public class Sfx { private static final String TAG = "Sfx"; /** * Optional callback function for when the sound finishes playing. */
public OnCompleteCallback complete;
gamblore/AndroidPunk
src/net/androidpunk/tweens/misc/ColorTween.java
// Path: src/net/androidpunk/Tween.java // public class Tween { // // /** // * Persistent Tween type, will stop when it finishes. // */ // public static final int PERSIST = 0; // // /** // * Looping Tween type, will restart immediately when it finishes. // */ // public static final int LOOPING = 1; // // /** // * Oneshot Tween type, will stop and remove itself from its core container when it finishes. // */ // public static final int ONESHOT = 2; // // /** // * If the tween should update. // */ // public boolean active = false; // // /** // * Tween completion callback. // */ // public OnCompleteCallback complete; // // // Tween information. // private int mType; // protected OnEaseCallback mEase; // protected float mT = 0; // // // Timing information. // protected float mTime; // protected float mTarget; // // // List information. // protected boolean mFinish; // protected Tweener mParent; // protected Tween mPrev; // protected Tween mNext; // // /** // * Constructor. Specify basic information about the Tween. // * @param duration Duration of the tween (in seconds or frames). // * @param type Tween type, one of Tween.PERSIST (default), Tween.LOOPING, or Tween.ONESHOT. // * @param complete Optional callback for when the Tween completes. // * @param ease Optional easer function to apply to the Tweened value. // */ // public Tween(float duration) { // this(duration, 0, null, null); // } // // public Tween(float duration, int type) { // this(duration, type, null, null); // } // // public Tween(float duration, int type, OnCompleteCallback completeFunction) { // this(duration, type, completeFunction, null); // } // // public Tween(float duration, int type, OnCompleteCallback completeFunction, OnEaseCallback easeFunction) { // mTarget = duration; // mType = type; // complete = completeFunction; // mEase = easeFunction; // } // // /** // * Updates the Tween, called by World. // */ // public void update() { // mTime += FP.fixed ? 1 : FP.elapsed; // // mT = mTime / mTarget; // if (mEase != null && mT > 0 && mT < 1) // mT = mEase.ease(mT); // if (mTime >= mTarget) { // mT = 1; // mFinish = true; // } // } // // /** // * Starts the Tween, or restarts it if it's currently running. // */ // public void start() { // mTime = 0; // if (mTarget == 0) { // active = false; // return; // } // active = true; // } // // /** @private Called when the Tween completes. */ // protected void finish() { // switch (mType) { // case PERSIST: // mTime = mTarget; // active = false; // break; // case LOOPING: // mTime %= mTarget; // mT = mTime / mTarget; // if (mEase != null && mT > 0 && mT < 1) // mT = mEase.ease(mT); // start(); // break; // case ONESHOT: // mTime = mTarget; // active = false; // mParent.removeTween(this); // break; // } // mFinish = false; // if (complete != null) // complete.completed(); // } // // public float getPercent() { // return mTime / mTarget; // } // // public void setPercent(float value) { // mTime = mTarget * value; // } // // public float getScale() { // return mT; // } // } // // Path: src/net/androidpunk/flashcompat/OnCompleteCallback.java // public abstract class OnCompleteCallback { // public abstract void completed(); // } // // Path: src/net/androidpunk/flashcompat/OnEaseCallback.java // public abstract class OnEaseCallback { // public abstract float ease(float t); // }
import android.graphics.Color; import net.androidpunk.Tween; import net.androidpunk.flashcompat.OnCompleteCallback; import net.androidpunk.flashcompat.OnEaseCallback;
package net.androidpunk.tweens.misc; /** * Tweens a color's red, green, and blue properties * independently. Can also tween an alpha value. */ public class ColorTween extends Tween { public int color; // Color information. private int mA; private int mR; private int mG; private int mB; private float mStartA, mStartR, mStartG, mStartB; private float mRangeA, mRangeR, mRangeG, mRangeB; /** * Constructor. * @param complete Optional completion callback. * @param type Tween type. */
// Path: src/net/androidpunk/Tween.java // public class Tween { // // /** // * Persistent Tween type, will stop when it finishes. // */ // public static final int PERSIST = 0; // // /** // * Looping Tween type, will restart immediately when it finishes. // */ // public static final int LOOPING = 1; // // /** // * Oneshot Tween type, will stop and remove itself from its core container when it finishes. // */ // public static final int ONESHOT = 2; // // /** // * If the tween should update. // */ // public boolean active = false; // // /** // * Tween completion callback. // */ // public OnCompleteCallback complete; // // // Tween information. // private int mType; // protected OnEaseCallback mEase; // protected float mT = 0; // // // Timing information. // protected float mTime; // protected float mTarget; // // // List information. // protected boolean mFinish; // protected Tweener mParent; // protected Tween mPrev; // protected Tween mNext; // // /** // * Constructor. Specify basic information about the Tween. // * @param duration Duration of the tween (in seconds or frames). // * @param type Tween type, one of Tween.PERSIST (default), Tween.LOOPING, or Tween.ONESHOT. // * @param complete Optional callback for when the Tween completes. // * @param ease Optional easer function to apply to the Tweened value. // */ // public Tween(float duration) { // this(duration, 0, null, null); // } // // public Tween(float duration, int type) { // this(duration, type, null, null); // } // // public Tween(float duration, int type, OnCompleteCallback completeFunction) { // this(duration, type, completeFunction, null); // } // // public Tween(float duration, int type, OnCompleteCallback completeFunction, OnEaseCallback easeFunction) { // mTarget = duration; // mType = type; // complete = completeFunction; // mEase = easeFunction; // } // // /** // * Updates the Tween, called by World. // */ // public void update() { // mTime += FP.fixed ? 1 : FP.elapsed; // // mT = mTime / mTarget; // if (mEase != null && mT > 0 && mT < 1) // mT = mEase.ease(mT); // if (mTime >= mTarget) { // mT = 1; // mFinish = true; // } // } // // /** // * Starts the Tween, or restarts it if it's currently running. // */ // public void start() { // mTime = 0; // if (mTarget == 0) { // active = false; // return; // } // active = true; // } // // /** @private Called when the Tween completes. */ // protected void finish() { // switch (mType) { // case PERSIST: // mTime = mTarget; // active = false; // break; // case LOOPING: // mTime %= mTarget; // mT = mTime / mTarget; // if (mEase != null && mT > 0 && mT < 1) // mT = mEase.ease(mT); // start(); // break; // case ONESHOT: // mTime = mTarget; // active = false; // mParent.removeTween(this); // break; // } // mFinish = false; // if (complete != null) // complete.completed(); // } // // public float getPercent() { // return mTime / mTarget; // } // // public void setPercent(float value) { // mTime = mTarget * value; // } // // public float getScale() { // return mT; // } // } // // Path: src/net/androidpunk/flashcompat/OnCompleteCallback.java // public abstract class OnCompleteCallback { // public abstract void completed(); // } // // Path: src/net/androidpunk/flashcompat/OnEaseCallback.java // public abstract class OnEaseCallback { // public abstract float ease(float t); // } // Path: src/net/androidpunk/tweens/misc/ColorTween.java import android.graphics.Color; import net.androidpunk.Tween; import net.androidpunk.flashcompat.OnCompleteCallback; import net.androidpunk.flashcompat.OnEaseCallback; package net.androidpunk.tweens.misc; /** * Tweens a color's red, green, and blue properties * independently. Can also tween an alpha value. */ public class ColorTween extends Tween { public int color; // Color information. private int mA; private int mR; private int mG; private int mB; private float mStartA, mStartR, mStartG, mStartB; private float mRangeA, mRangeR, mRangeG, mRangeB; /** * Constructor. * @param complete Optional completion callback. * @param type Tween type. */
public ColorTween(OnCompleteCallback completeFunction, int type) {
gamblore/AndroidPunk
src/net/androidpunk/tweens/misc/NumTween.java
// Path: src/net/androidpunk/Tween.java // public class Tween { // // /** // * Persistent Tween type, will stop when it finishes. // */ // public static final int PERSIST = 0; // // /** // * Looping Tween type, will restart immediately when it finishes. // */ // public static final int LOOPING = 1; // // /** // * Oneshot Tween type, will stop and remove itself from its core container when it finishes. // */ // public static final int ONESHOT = 2; // // /** // * If the tween should update. // */ // public boolean active = false; // // /** // * Tween completion callback. // */ // public OnCompleteCallback complete; // // // Tween information. // private int mType; // protected OnEaseCallback mEase; // protected float mT = 0; // // // Timing information. // protected float mTime; // protected float mTarget; // // // List information. // protected boolean mFinish; // protected Tweener mParent; // protected Tween mPrev; // protected Tween mNext; // // /** // * Constructor. Specify basic information about the Tween. // * @param duration Duration of the tween (in seconds or frames). // * @param type Tween type, one of Tween.PERSIST (default), Tween.LOOPING, or Tween.ONESHOT. // * @param complete Optional callback for when the Tween completes. // * @param ease Optional easer function to apply to the Tweened value. // */ // public Tween(float duration) { // this(duration, 0, null, null); // } // // public Tween(float duration, int type) { // this(duration, type, null, null); // } // // public Tween(float duration, int type, OnCompleteCallback completeFunction) { // this(duration, type, completeFunction, null); // } // // public Tween(float duration, int type, OnCompleteCallback completeFunction, OnEaseCallback easeFunction) { // mTarget = duration; // mType = type; // complete = completeFunction; // mEase = easeFunction; // } // // /** // * Updates the Tween, called by World. // */ // public void update() { // mTime += FP.fixed ? 1 : FP.elapsed; // // mT = mTime / mTarget; // if (mEase != null && mT > 0 && mT < 1) // mT = mEase.ease(mT); // if (mTime >= mTarget) { // mT = 1; // mFinish = true; // } // } // // /** // * Starts the Tween, or restarts it if it's currently running. // */ // public void start() { // mTime = 0; // if (mTarget == 0) { // active = false; // return; // } // active = true; // } // // /** @private Called when the Tween completes. */ // protected void finish() { // switch (mType) { // case PERSIST: // mTime = mTarget; // active = false; // break; // case LOOPING: // mTime %= mTarget; // mT = mTime / mTarget; // if (mEase != null && mT > 0 && mT < 1) // mT = mEase.ease(mT); // start(); // break; // case ONESHOT: // mTime = mTarget; // active = false; // mParent.removeTween(this); // break; // } // mFinish = false; // if (complete != null) // complete.completed(); // } // // public float getPercent() { // return mTime / mTarget; // } // // public void setPercent(float value) { // mTime = mTarget * value; // } // // public float getScale() { // return mT; // } // } // // Path: src/net/androidpunk/flashcompat/OnCompleteCallback.java // public abstract class OnCompleteCallback { // public abstract void completed(); // } // // Path: src/net/androidpunk/flashcompat/OnEaseCallback.java // public abstract class OnEaseCallback { // public abstract float ease(float t); // }
import net.androidpunk.Tween; import net.androidpunk.flashcompat.OnCompleteCallback; import net.androidpunk.flashcompat.OnEaseCallback;
package net.androidpunk.tweens.misc; /** * Tweens a numeric value. */ public class NumTween extends Tween { // Tween information. private float mStart; private float mRange; /** * The current value. */ public float value = 0; /** * Constructor. */ public NumTween() { this(null, 0); } /** * Constructor. * @param complete Optional completion callback. */
// Path: src/net/androidpunk/Tween.java // public class Tween { // // /** // * Persistent Tween type, will stop when it finishes. // */ // public static final int PERSIST = 0; // // /** // * Looping Tween type, will restart immediately when it finishes. // */ // public static final int LOOPING = 1; // // /** // * Oneshot Tween type, will stop and remove itself from its core container when it finishes. // */ // public static final int ONESHOT = 2; // // /** // * If the tween should update. // */ // public boolean active = false; // // /** // * Tween completion callback. // */ // public OnCompleteCallback complete; // // // Tween information. // private int mType; // protected OnEaseCallback mEase; // protected float mT = 0; // // // Timing information. // protected float mTime; // protected float mTarget; // // // List information. // protected boolean mFinish; // protected Tweener mParent; // protected Tween mPrev; // protected Tween mNext; // // /** // * Constructor. Specify basic information about the Tween. // * @param duration Duration of the tween (in seconds or frames). // * @param type Tween type, one of Tween.PERSIST (default), Tween.LOOPING, or Tween.ONESHOT. // * @param complete Optional callback for when the Tween completes. // * @param ease Optional easer function to apply to the Tweened value. // */ // public Tween(float duration) { // this(duration, 0, null, null); // } // // public Tween(float duration, int type) { // this(duration, type, null, null); // } // // public Tween(float duration, int type, OnCompleteCallback completeFunction) { // this(duration, type, completeFunction, null); // } // // public Tween(float duration, int type, OnCompleteCallback completeFunction, OnEaseCallback easeFunction) { // mTarget = duration; // mType = type; // complete = completeFunction; // mEase = easeFunction; // } // // /** // * Updates the Tween, called by World. // */ // public void update() { // mTime += FP.fixed ? 1 : FP.elapsed; // // mT = mTime / mTarget; // if (mEase != null && mT > 0 && mT < 1) // mT = mEase.ease(mT); // if (mTime >= mTarget) { // mT = 1; // mFinish = true; // } // } // // /** // * Starts the Tween, or restarts it if it's currently running. // */ // public void start() { // mTime = 0; // if (mTarget == 0) { // active = false; // return; // } // active = true; // } // // /** @private Called when the Tween completes. */ // protected void finish() { // switch (mType) { // case PERSIST: // mTime = mTarget; // active = false; // break; // case LOOPING: // mTime %= mTarget; // mT = mTime / mTarget; // if (mEase != null && mT > 0 && mT < 1) // mT = mEase.ease(mT); // start(); // break; // case ONESHOT: // mTime = mTarget; // active = false; // mParent.removeTween(this); // break; // } // mFinish = false; // if (complete != null) // complete.completed(); // } // // public float getPercent() { // return mTime / mTarget; // } // // public void setPercent(float value) { // mTime = mTarget * value; // } // // public float getScale() { // return mT; // } // } // // Path: src/net/androidpunk/flashcompat/OnCompleteCallback.java // public abstract class OnCompleteCallback { // public abstract void completed(); // } // // Path: src/net/androidpunk/flashcompat/OnEaseCallback.java // public abstract class OnEaseCallback { // public abstract float ease(float t); // } // Path: src/net/androidpunk/tweens/misc/NumTween.java import net.androidpunk.Tween; import net.androidpunk.flashcompat.OnCompleteCallback; import net.androidpunk.flashcompat.OnEaseCallback; package net.androidpunk.tweens.misc; /** * Tweens a numeric value. */ public class NumTween extends Tween { // Tween information. private float mStart; private float mRange; /** * The current value. */ public float value = 0; /** * Constructor. */ public NumTween() { this(null, 0); } /** * Constructor. * @param complete Optional completion callback. */
public NumTween(OnCompleteCallback completeFunction) {
gamblore/AndroidPunk
src/net/androidpunk/Tween.java
// Path: src/net/androidpunk/flashcompat/OnCompleteCallback.java // public abstract class OnCompleteCallback { // public abstract void completed(); // } // // Path: src/net/androidpunk/flashcompat/OnEaseCallback.java // public abstract class OnEaseCallback { // public abstract float ease(float t); // }
import net.androidpunk.flashcompat.OnCompleteCallback; import net.androidpunk.flashcompat.OnEaseCallback;
package net.androidpunk; public class Tween { /** * Persistent Tween type, will stop when it finishes. */ public static final int PERSIST = 0; /** * Looping Tween type, will restart immediately when it finishes. */ public static final int LOOPING = 1; /** * Oneshot Tween type, will stop and remove itself from its core container when it finishes. */ public static final int ONESHOT = 2; /** * If the tween should update. */ public boolean active = false; /** * Tween completion callback. */
// Path: src/net/androidpunk/flashcompat/OnCompleteCallback.java // public abstract class OnCompleteCallback { // public abstract void completed(); // } // // Path: src/net/androidpunk/flashcompat/OnEaseCallback.java // public abstract class OnEaseCallback { // public abstract float ease(float t); // } // Path: src/net/androidpunk/Tween.java import net.androidpunk.flashcompat.OnCompleteCallback; import net.androidpunk.flashcompat.OnEaseCallback; package net.androidpunk; public class Tween { /** * Persistent Tween type, will stop when it finishes. */ public static final int PERSIST = 0; /** * Looping Tween type, will restart immediately when it finishes. */ public static final int LOOPING = 1; /** * Oneshot Tween type, will stop and remove itself from its core container when it finishes. */ public static final int ONESHOT = 2; /** * If the tween should update. */ public boolean active = false; /** * Tween completion callback. */
public OnCompleteCallback complete;
gamblore/AndroidPunk
src/net/androidpunk/Tween.java
// Path: src/net/androidpunk/flashcompat/OnCompleteCallback.java // public abstract class OnCompleteCallback { // public abstract void completed(); // } // // Path: src/net/androidpunk/flashcompat/OnEaseCallback.java // public abstract class OnEaseCallback { // public abstract float ease(float t); // }
import net.androidpunk.flashcompat.OnCompleteCallback; import net.androidpunk.flashcompat.OnEaseCallback;
package net.androidpunk; public class Tween { /** * Persistent Tween type, will stop when it finishes. */ public static final int PERSIST = 0; /** * Looping Tween type, will restart immediately when it finishes. */ public static final int LOOPING = 1; /** * Oneshot Tween type, will stop and remove itself from its core container when it finishes. */ public static final int ONESHOT = 2; /** * If the tween should update. */ public boolean active = false; /** * Tween completion callback. */ public OnCompleteCallback complete; // Tween information. private int mType;
// Path: src/net/androidpunk/flashcompat/OnCompleteCallback.java // public abstract class OnCompleteCallback { // public abstract void completed(); // } // // Path: src/net/androidpunk/flashcompat/OnEaseCallback.java // public abstract class OnEaseCallback { // public abstract float ease(float t); // } // Path: src/net/androidpunk/Tween.java import net.androidpunk.flashcompat.OnCompleteCallback; import net.androidpunk.flashcompat.OnEaseCallback; package net.androidpunk; public class Tween { /** * Persistent Tween type, will stop when it finishes. */ public static final int PERSIST = 0; /** * Looping Tween type, will restart immediately when it finishes. */ public static final int LOOPING = 1; /** * Oneshot Tween type, will stop and remove itself from its core container when it finishes. */ public static final int ONESHOT = 2; /** * If the tween should update. */ public boolean active = false; /** * Tween completion callback. */ public OnCompleteCallback complete; // Tween information. private int mType;
protected OnEaseCallback mEase;
gamblore/AndroidPunk
src/net/androidpunk/tweens/motion/LinearMotion.java
// Path: src/net/androidpunk/flashcompat/OnCompleteCallback.java // public abstract class OnCompleteCallback { // public abstract void completed(); // } // // Path: src/net/androidpunk/flashcompat/OnEaseCallback.java // public abstract class OnEaseCallback { // public abstract float ease(float t); // }
import net.androidpunk.flashcompat.OnCompleteCallback; import net.androidpunk.flashcompat.OnEaseCallback;
package net.androidpunk.tweens.motion; /** * Determines motion along a line, from one point to another. */ public class LinearMotion extends Motion { // Line information. private float mFromX = 0; private float mFromY = 0; private float mMoveX = 0; private float mMoveY = 0; private float mDistance = -1; /** * Constructor. */ public LinearMotion() { super(0, null, 0, null); } /** * Constructor. * @param complete Optional completion callback. */
// Path: src/net/androidpunk/flashcompat/OnCompleteCallback.java // public abstract class OnCompleteCallback { // public abstract void completed(); // } // // Path: src/net/androidpunk/flashcompat/OnEaseCallback.java // public abstract class OnEaseCallback { // public abstract float ease(float t); // } // Path: src/net/androidpunk/tweens/motion/LinearMotion.java import net.androidpunk.flashcompat.OnCompleteCallback; import net.androidpunk.flashcompat.OnEaseCallback; package net.androidpunk.tweens.motion; /** * Determines motion along a line, from one point to another. */ public class LinearMotion extends Motion { // Line information. private float mFromX = 0; private float mFromY = 0; private float mMoveX = 0; private float mMoveY = 0; private float mDistance = -1; /** * Constructor. */ public LinearMotion() { super(0, null, 0, null); } /** * Constructor. * @param complete Optional completion callback. */
public LinearMotion(OnCompleteCallback completeFunction) {
gamblore/AndroidPunk
src/net/androidpunk/tweens/motion/LinearMotion.java
// Path: src/net/androidpunk/flashcompat/OnCompleteCallback.java // public abstract class OnCompleteCallback { // public abstract void completed(); // } // // Path: src/net/androidpunk/flashcompat/OnEaseCallback.java // public abstract class OnEaseCallback { // public abstract float ease(float t); // }
import net.androidpunk.flashcompat.OnCompleteCallback; import net.androidpunk.flashcompat.OnEaseCallback;
package net.androidpunk.tweens.motion; /** * Determines motion along a line, from one point to another. */ public class LinearMotion extends Motion { // Line information. private float mFromX = 0; private float mFromY = 0; private float mMoveX = 0; private float mMoveY = 0; private float mDistance = -1; /** * Constructor. */ public LinearMotion() { super(0, null, 0, null); } /** * Constructor. * @param complete Optional completion callback. */ public LinearMotion(OnCompleteCallback completeFunction) { super(0, completeFunction, 0, null); } /** * Constructor. * @param complete Optional completion callback. * @param type Tween type. */ public LinearMotion(OnCompleteCallback completeFunction, int type) { super(0, completeFunction, type, null); } /** * Starts moving along a line. * @param fromX X start. * @param fromY Y start. * @param toX X finish. * @param toY Y finish. * @param duration Duration of the movement. */ public void setMotion(float fromX, float fromY, float toX, float toY, float duration) { setMotion(fromX, fromY, toX, toY, duration, null); } /** * Starts moving along a line. * @param fromX X start. * @param fromY Y start. * @param toX X finish. * @param toY Y finish. * @param duration Duration of the movement. * @param ease Optional easer function. */
// Path: src/net/androidpunk/flashcompat/OnCompleteCallback.java // public abstract class OnCompleteCallback { // public abstract void completed(); // } // // Path: src/net/androidpunk/flashcompat/OnEaseCallback.java // public abstract class OnEaseCallback { // public abstract float ease(float t); // } // Path: src/net/androidpunk/tweens/motion/LinearMotion.java import net.androidpunk.flashcompat.OnCompleteCallback; import net.androidpunk.flashcompat.OnEaseCallback; package net.androidpunk.tweens.motion; /** * Determines motion along a line, from one point to another. */ public class LinearMotion extends Motion { // Line information. private float mFromX = 0; private float mFromY = 0; private float mMoveX = 0; private float mMoveY = 0; private float mDistance = -1; /** * Constructor. */ public LinearMotion() { super(0, null, 0, null); } /** * Constructor. * @param complete Optional completion callback. */ public LinearMotion(OnCompleteCallback completeFunction) { super(0, completeFunction, 0, null); } /** * Constructor. * @param complete Optional completion callback. * @param type Tween type. */ public LinearMotion(OnCompleteCallback completeFunction, int type) { super(0, completeFunction, type, null); } /** * Starts moving along a line. * @param fromX X start. * @param fromY Y start. * @param toX X finish. * @param toY Y finish. * @param duration Duration of the movement. */ public void setMotion(float fromX, float fromY, float toX, float toY, float duration) { setMotion(fromX, fromY, toX, toY, duration, null); } /** * Starts moving along a line. * @param fromX X start. * @param fromY Y start. * @param toX X finish. * @param toY Y finish. * @param duration Duration of the movement. * @param ease Optional easer function. */
public void setMotion(float fromX, float fromY, float toX, float toY, float duration, OnEaseCallback ease) {
gamblore/AndroidPunk
src/net/androidpunk/graphics/atlas/Stamp.java
// Path: src/net/androidpunk/graphics/opengl/SubTexture.java // public class SubTexture { // // private final Rect mRect = new Rect(); // private Texture mTexture; // // /** // * Create a subtexture object to describe a texture in a texture. // * @param t The base Texture to use. // * @param x The start x coord of the subtexture (in pixels). // * @param y The start y coord of the subtexture (in pixels). // * @param width The width of the subtexture (in pixels). // * @param height The height of the subtexture (in pixels). // */ // public SubTexture(Texture t, int x, int y, int width, int height) { // mTexture = t; // mRect.set(x,y,x+width,y+height); // } // // /** // * Gets the texture this subtexture uses. // * @return The subtexture. // */ // public Texture getTexture() { // return mTexture; // } // // /** // * The bounds of the whole subtexture. // * @return // */ // public Rect getBounds() { // return mRect; // } // // /** // * The width of the subtexture. // * @return // */ // public int getWidth() { // return mRect.width(); // } // // /** // * The height of the subtexture. // * @return // */ // public int getHeight() { // return mRect.height(); // } // // /** // * Set a rect to the clip for that frame in the whole texture // * @param r the rect to set to the clip of the whole texture. // */ // public void getFrame(Rect r, int index, int frameWidth, int frameHeight) { // int x = index * frameWidth; // int y = (x / mRect.width()) * frameHeight; // x %= mRect.width(); // r.set(mRect.left + x, mRect.top + y, mRect.left + x + frameWidth, mRect.top + y + frameHeight); // } // // /** // * Set a rec to the clip based on a relative rect. // * @param clipRect the rect to set to the clip of the whole texture. // * @param relativeClipRect a relative rect of the subtexture. // */ // public void GetAbsoluteClipRect(Rect clipRect, Rect relativeClipRect) { // int width = relativeClipRect.width(); // int height = relativeClipRect.height(); // clipRect.left = relativeClipRect.left + mRect.left; // clipRect.top = relativeClipRect.top + mRect.top; // clipRect.right = clipRect.left + width; // clipRect.bottom = clipRect.top + height; // } // }
import java.nio.FloatBuffer; import javax.microedition.khronos.opengles.GL10; import net.androidpunk.graphics.opengl.SubTexture; import android.graphics.Point;
package net.androidpunk.graphics.atlas; /** * A simple non-transformed, non-animated graphic. */ public class Stamp extends AtlasGraphic { // Stamp information. private FloatBuffer mTextureBuffer = getDirectFloatBuffer(8);
// Path: src/net/androidpunk/graphics/opengl/SubTexture.java // public class SubTexture { // // private final Rect mRect = new Rect(); // private Texture mTexture; // // /** // * Create a subtexture object to describe a texture in a texture. // * @param t The base Texture to use. // * @param x The start x coord of the subtexture (in pixels). // * @param y The start y coord of the subtexture (in pixels). // * @param width The width of the subtexture (in pixels). // * @param height The height of the subtexture (in pixels). // */ // public SubTexture(Texture t, int x, int y, int width, int height) { // mTexture = t; // mRect.set(x,y,x+width,y+height); // } // // /** // * Gets the texture this subtexture uses. // * @return The subtexture. // */ // public Texture getTexture() { // return mTexture; // } // // /** // * The bounds of the whole subtexture. // * @return // */ // public Rect getBounds() { // return mRect; // } // // /** // * The width of the subtexture. // * @return // */ // public int getWidth() { // return mRect.width(); // } // // /** // * The height of the subtexture. // * @return // */ // public int getHeight() { // return mRect.height(); // } // // /** // * Set a rect to the clip for that frame in the whole texture // * @param r the rect to set to the clip of the whole texture. // */ // public void getFrame(Rect r, int index, int frameWidth, int frameHeight) { // int x = index * frameWidth; // int y = (x / mRect.width()) * frameHeight; // x %= mRect.width(); // r.set(mRect.left + x, mRect.top + y, mRect.left + x + frameWidth, mRect.top + y + frameHeight); // } // // /** // * Set a rec to the clip based on a relative rect. // * @param clipRect the rect to set to the clip of the whole texture. // * @param relativeClipRect a relative rect of the subtexture. // */ // public void GetAbsoluteClipRect(Rect clipRect, Rect relativeClipRect) { // int width = relativeClipRect.width(); // int height = relativeClipRect.height(); // clipRect.left = relativeClipRect.left + mRect.left; // clipRect.top = relativeClipRect.top + mRect.top; // clipRect.right = clipRect.left + width; // clipRect.bottom = clipRect.top + height; // } // } // Path: src/net/androidpunk/graphics/atlas/Stamp.java import java.nio.FloatBuffer; import javax.microedition.khronos.opengles.GL10; import net.androidpunk.graphics.opengl.SubTexture; import android.graphics.Point; package net.androidpunk.graphics.atlas; /** * A simple non-transformed, non-animated graphic. */ public class Stamp extends AtlasGraphic { // Stamp information. private FloatBuffer mTextureBuffer = getDirectFloatBuffer(8);
public Stamp(SubTexture subTexture) {
gamblore/AndroidPunk
src/net/androidpunk/utils/Ease.java
// Path: src/net/androidpunk/flashcompat/OnEaseCallback.java // public abstract class OnEaseCallback { // public abstract float ease(float t); // }
import net.androidpunk.flashcompat.OnEaseCallback;
package net.androidpunk.utils; public class Ease { // Easing constants. private static final float PI = (float) Math.PI; private static final float PI2 = (float) Math.PI / 2; private static final float EL = 2 * PI / .45f; private static final float B1 = 1 / 2.75f; private static final float B2 = 2 / 2.75f; private static final float B3 = 1.5f / 2.75f; private static final float B4 = 2.5f / 2.75f; private static final float B5 = 2.25f / 2.75f; private static final float B6 = 2.625f / 2.75f;
// Path: src/net/androidpunk/flashcompat/OnEaseCallback.java // public abstract class OnEaseCallback { // public abstract float ease(float t); // } // Path: src/net/androidpunk/utils/Ease.java import net.androidpunk.flashcompat.OnEaseCallback; package net.androidpunk.utils; public class Ease { // Easing constants. private static final float PI = (float) Math.PI; private static final float PI2 = (float) Math.PI / 2; private static final float EL = 2 * PI / .45f; private static final float B1 = 1 / 2.75f; private static final float B2 = 2 / 2.75f; private static final float B3 = 1.5f / 2.75f; private static final float B4 = 2.5f / 2.75f; private static final float B5 = 2.25f / 2.75f; private static final float B6 = 2.625f / 2.75f;
public static final OnEaseCallback quadIn = new OnEaseCallback() {
gamblore/AndroidPunk
src/net/androidpunk/tweens/motion/Motion.java
// Path: src/net/androidpunk/Tween.java // public class Tween { // // /** // * Persistent Tween type, will stop when it finishes. // */ // public static final int PERSIST = 0; // // /** // * Looping Tween type, will restart immediately when it finishes. // */ // public static final int LOOPING = 1; // // /** // * Oneshot Tween type, will stop and remove itself from its core container when it finishes. // */ // public static final int ONESHOT = 2; // // /** // * If the tween should update. // */ // public boolean active = false; // // /** // * Tween completion callback. // */ // public OnCompleteCallback complete; // // // Tween information. // private int mType; // protected OnEaseCallback mEase; // protected float mT = 0; // // // Timing information. // protected float mTime; // protected float mTarget; // // // List information. // protected boolean mFinish; // protected Tweener mParent; // protected Tween mPrev; // protected Tween mNext; // // /** // * Constructor. Specify basic information about the Tween. // * @param duration Duration of the tween (in seconds or frames). // * @param type Tween type, one of Tween.PERSIST (default), Tween.LOOPING, or Tween.ONESHOT. // * @param complete Optional callback for when the Tween completes. // * @param ease Optional easer function to apply to the Tweened value. // */ // public Tween(float duration) { // this(duration, 0, null, null); // } // // public Tween(float duration, int type) { // this(duration, type, null, null); // } // // public Tween(float duration, int type, OnCompleteCallback completeFunction) { // this(duration, type, completeFunction, null); // } // // public Tween(float duration, int type, OnCompleteCallback completeFunction, OnEaseCallback easeFunction) { // mTarget = duration; // mType = type; // complete = completeFunction; // mEase = easeFunction; // } // // /** // * Updates the Tween, called by World. // */ // public void update() { // mTime += FP.fixed ? 1 : FP.elapsed; // // mT = mTime / mTarget; // if (mEase != null && mT > 0 && mT < 1) // mT = mEase.ease(mT); // if (mTime >= mTarget) { // mT = 1; // mFinish = true; // } // } // // /** // * Starts the Tween, or restarts it if it's currently running. // */ // public void start() { // mTime = 0; // if (mTarget == 0) { // active = false; // return; // } // active = true; // } // // /** @private Called when the Tween completes. */ // protected void finish() { // switch (mType) { // case PERSIST: // mTime = mTarget; // active = false; // break; // case LOOPING: // mTime %= mTarget; // mT = mTime / mTarget; // if (mEase != null && mT > 0 && mT < 1) // mT = mEase.ease(mT); // start(); // break; // case ONESHOT: // mTime = mTarget; // active = false; // mParent.removeTween(this); // break; // } // mFinish = false; // if (complete != null) // complete.completed(); // } // // public float getPercent() { // return mTime / mTarget; // } // // public void setPercent(float value) { // mTime = mTarget * value; // } // // public float getScale() { // return mT; // } // } // // Path: src/net/androidpunk/flashcompat/OnCompleteCallback.java // public abstract class OnCompleteCallback { // public abstract void completed(); // } // // Path: src/net/androidpunk/flashcompat/OnEaseCallback.java // public abstract class OnEaseCallback { // public abstract float ease(float t); // }
import net.androidpunk.Tween; import net.androidpunk.flashcompat.OnCompleteCallback; import net.androidpunk.flashcompat.OnEaseCallback;
package net.androidpunk.tweens.motion; /** * Base class for motion Tweens. */ public class Motion extends Tween { /** * Current x position of the Tween. */ public float x = 0; /** * Current y position of the Tween. */ public float y = 0; /** * Constructor. * @param duration Duration of the Tween. */ public Motion(float duration) { this(duration, null, 0, null); } /** * Constructor. * @param duration Duration of the Tween. * @param complete Optional completion callback. */
// Path: src/net/androidpunk/Tween.java // public class Tween { // // /** // * Persistent Tween type, will stop when it finishes. // */ // public static final int PERSIST = 0; // // /** // * Looping Tween type, will restart immediately when it finishes. // */ // public static final int LOOPING = 1; // // /** // * Oneshot Tween type, will stop and remove itself from its core container when it finishes. // */ // public static final int ONESHOT = 2; // // /** // * If the tween should update. // */ // public boolean active = false; // // /** // * Tween completion callback. // */ // public OnCompleteCallback complete; // // // Tween information. // private int mType; // protected OnEaseCallback mEase; // protected float mT = 0; // // // Timing information. // protected float mTime; // protected float mTarget; // // // List information. // protected boolean mFinish; // protected Tweener mParent; // protected Tween mPrev; // protected Tween mNext; // // /** // * Constructor. Specify basic information about the Tween. // * @param duration Duration of the tween (in seconds or frames). // * @param type Tween type, one of Tween.PERSIST (default), Tween.LOOPING, or Tween.ONESHOT. // * @param complete Optional callback for when the Tween completes. // * @param ease Optional easer function to apply to the Tweened value. // */ // public Tween(float duration) { // this(duration, 0, null, null); // } // // public Tween(float duration, int type) { // this(duration, type, null, null); // } // // public Tween(float duration, int type, OnCompleteCallback completeFunction) { // this(duration, type, completeFunction, null); // } // // public Tween(float duration, int type, OnCompleteCallback completeFunction, OnEaseCallback easeFunction) { // mTarget = duration; // mType = type; // complete = completeFunction; // mEase = easeFunction; // } // // /** // * Updates the Tween, called by World. // */ // public void update() { // mTime += FP.fixed ? 1 : FP.elapsed; // // mT = mTime / mTarget; // if (mEase != null && mT > 0 && mT < 1) // mT = mEase.ease(mT); // if (mTime >= mTarget) { // mT = 1; // mFinish = true; // } // } // // /** // * Starts the Tween, or restarts it if it's currently running. // */ // public void start() { // mTime = 0; // if (mTarget == 0) { // active = false; // return; // } // active = true; // } // // /** @private Called when the Tween completes. */ // protected void finish() { // switch (mType) { // case PERSIST: // mTime = mTarget; // active = false; // break; // case LOOPING: // mTime %= mTarget; // mT = mTime / mTarget; // if (mEase != null && mT > 0 && mT < 1) // mT = mEase.ease(mT); // start(); // break; // case ONESHOT: // mTime = mTarget; // active = false; // mParent.removeTween(this); // break; // } // mFinish = false; // if (complete != null) // complete.completed(); // } // // public float getPercent() { // return mTime / mTarget; // } // // public void setPercent(float value) { // mTime = mTarget * value; // } // // public float getScale() { // return mT; // } // } // // Path: src/net/androidpunk/flashcompat/OnCompleteCallback.java // public abstract class OnCompleteCallback { // public abstract void completed(); // } // // Path: src/net/androidpunk/flashcompat/OnEaseCallback.java // public abstract class OnEaseCallback { // public abstract float ease(float t); // } // Path: src/net/androidpunk/tweens/motion/Motion.java import net.androidpunk.Tween; import net.androidpunk.flashcompat.OnCompleteCallback; import net.androidpunk.flashcompat.OnEaseCallback; package net.androidpunk.tweens.motion; /** * Base class for motion Tweens. */ public class Motion extends Tween { /** * Current x position of the Tween. */ public float x = 0; /** * Current y position of the Tween. */ public float y = 0; /** * Constructor. * @param duration Duration of the Tween. */ public Motion(float duration) { this(duration, null, 0, null); } /** * Constructor. * @param duration Duration of the Tween. * @param complete Optional completion callback. */
public Motion(float duration, OnCompleteCallback completeFunction) {
cgrotz/kademlia
src/main/java/de/cgrotz/kademlia/client/KademliaClientHandler.java
// Path: src/main/java/de/cgrotz/kademlia/protocol/Codec.java // public class Codec { // private final Base64.Decoder decoder = Base64.getDecoder(); // private final Base64.Encoder encoder = Base64.getEncoder(); // // private final Gson gson = new GsonBuilder() // .registerTypeAdapter(Message.class, new MessageTypeAdapter()) // .registerTypeAdapter(Listener.class, new ListenerMessageTypeAdapter()) // //.registerTypeAdapter(UdpListener.class, new UdpListenerMessageTypeAdapter()) // .create(); // // public Message decode(byte[] buffer) throws UnsupportedEncodingException { // Message message = gson.fromJson(new String(buffer, StandardCharsets.UTF_8).trim(), Message.class); // return message; // } // // public byte[] encode(Message msg) { // return gson.toJson(msg).getBytes(); // } // } // // Path: src/main/java/de/cgrotz/kademlia/protocol/Message.java // @Data // public abstract class Message { // private final MessageType type; // private final long seqId; // // private final Node origin; // }
import de.cgrotz.kademlia.protocol.Codec; import de.cgrotz.kademlia.protocol.Message; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.DatagramPacket; import java.util.HashMap; import java.util.Map; import java.util.function.Consumer;
package de.cgrotz.kademlia.client; /** * Created by Christoph on 24.09.2016. */ public class KademliaClientHandler { private final static Logger LOGGER = LoggerFactory.getLogger(KademliaClientHandler.class);
// Path: src/main/java/de/cgrotz/kademlia/protocol/Codec.java // public class Codec { // private final Base64.Decoder decoder = Base64.getDecoder(); // private final Base64.Encoder encoder = Base64.getEncoder(); // // private final Gson gson = new GsonBuilder() // .registerTypeAdapter(Message.class, new MessageTypeAdapter()) // .registerTypeAdapter(Listener.class, new ListenerMessageTypeAdapter()) // //.registerTypeAdapter(UdpListener.class, new UdpListenerMessageTypeAdapter()) // .create(); // // public Message decode(byte[] buffer) throws UnsupportedEncodingException { // Message message = gson.fromJson(new String(buffer, StandardCharsets.UTF_8).trim(), Message.class); // return message; // } // // public byte[] encode(Message msg) { // return gson.toJson(msg).getBytes(); // } // } // // Path: src/main/java/de/cgrotz/kademlia/protocol/Message.java // @Data // public abstract class Message { // private final MessageType type; // private final long seqId; // // private final Node origin; // } // Path: src/main/java/de/cgrotz/kademlia/client/KademliaClientHandler.java import de.cgrotz.kademlia.protocol.Codec; import de.cgrotz.kademlia.protocol.Message; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.DatagramPacket; import java.util.HashMap; import java.util.Map; import java.util.function.Consumer; package de.cgrotz.kademlia.client; /** * Created by Christoph on 24.09.2016. */ public class KademliaClientHandler { private final static Logger LOGGER = LoggerFactory.getLogger(KademliaClientHandler.class);
private final Codec codec = new Codec();
cgrotz/kademlia
src/main/java/de/cgrotz/kademlia/client/KademliaClientHandler.java
// Path: src/main/java/de/cgrotz/kademlia/protocol/Codec.java // public class Codec { // private final Base64.Decoder decoder = Base64.getDecoder(); // private final Base64.Encoder encoder = Base64.getEncoder(); // // private final Gson gson = new GsonBuilder() // .registerTypeAdapter(Message.class, new MessageTypeAdapter()) // .registerTypeAdapter(Listener.class, new ListenerMessageTypeAdapter()) // //.registerTypeAdapter(UdpListener.class, new UdpListenerMessageTypeAdapter()) // .create(); // // public Message decode(byte[] buffer) throws UnsupportedEncodingException { // Message message = gson.fromJson(new String(buffer, StandardCharsets.UTF_8).trim(), Message.class); // return message; // } // // public byte[] encode(Message msg) { // return gson.toJson(msg).getBytes(); // } // } // // Path: src/main/java/de/cgrotz/kademlia/protocol/Message.java // @Data // public abstract class Message { // private final MessageType type; // private final long seqId; // // private final Node origin; // }
import de.cgrotz.kademlia.protocol.Codec; import de.cgrotz.kademlia.protocol.Message; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.DatagramPacket; import java.util.HashMap; import java.util.Map; import java.util.function.Consumer;
package de.cgrotz.kademlia.client; /** * Created by Christoph on 24.09.2016. */ public class KademliaClientHandler { private final static Logger LOGGER = LoggerFactory.getLogger(KademliaClientHandler.class); private final Codec codec = new Codec();
// Path: src/main/java/de/cgrotz/kademlia/protocol/Codec.java // public class Codec { // private final Base64.Decoder decoder = Base64.getDecoder(); // private final Base64.Encoder encoder = Base64.getEncoder(); // // private final Gson gson = new GsonBuilder() // .registerTypeAdapter(Message.class, new MessageTypeAdapter()) // .registerTypeAdapter(Listener.class, new ListenerMessageTypeAdapter()) // //.registerTypeAdapter(UdpListener.class, new UdpListenerMessageTypeAdapter()) // .create(); // // public Message decode(byte[] buffer) throws UnsupportedEncodingException { // Message message = gson.fromJson(new String(buffer, StandardCharsets.UTF_8).trim(), Message.class); // return message; // } // // public byte[] encode(Message msg) { // return gson.toJson(msg).getBytes(); // } // } // // Path: src/main/java/de/cgrotz/kademlia/protocol/Message.java // @Data // public abstract class Message { // private final MessageType type; // private final long seqId; // // private final Node origin; // } // Path: src/main/java/de/cgrotz/kademlia/client/KademliaClientHandler.java import de.cgrotz.kademlia.protocol.Codec; import de.cgrotz.kademlia.protocol.Message; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.DatagramPacket; import java.util.HashMap; import java.util.Map; import java.util.function.Consumer; package de.cgrotz.kademlia.client; /** * Created by Christoph on 24.09.2016. */ public class KademliaClientHandler { private final static Logger LOGGER = LoggerFactory.getLogger(KademliaClientHandler.class); private final Codec codec = new Codec();
private Map<Long, Consumer<Message>> handlers = new HashMap<>();
cgrotz/kademlia
src/main/java/de/cgrotz/kademlia/protocol/FindNode.java
// Path: src/main/java/de/cgrotz/kademlia/node/Key.java // @Data // @EqualsAndHashCode(of = "key") // public class Key { // public final static int ID_LENGTH = 160; // // private BigInteger key; // // public Key(byte[] result) { // if(result.length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = new BigInteger(result); // } // // public Key(BigInteger key) { // if( key.toByteArray().length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = key; // } // // public Key(int id) { // this.key = BigInteger.valueOf(id); // } // // public static Key random() { // byte[] bytes = new byte[ID_LENGTH / 8]; // SecureRandom sr1 = new SecureRandom(); // sr1.nextBytes(bytes); // return new Key(bytes); // } // // public static Key build(String key) { // return new Key(new BigInteger(key,16)); // } // // /** // * Checks the distance between this and another Key // * // * @param nid // * // * @return The distance of this Key from the given Key // */ // public Key xor(Key nid) // { // return new Key(nid.getKey().xor(this.key)); // } // // /** // * Generates a Key that is some distance away from this Key // * // * @param distance in number of bits // * // * @return Key The newly generated Key // */ // public Key generateNodeIdByDistance(int distance) // { // byte[] result = new byte[ID_LENGTH / 8]; // // /* Since distance = ID_LENGTH - prefixLength, we need to fill that amount with 0's */ // int numByteZeroes = (ID_LENGTH - distance) / 8; // int numBitZeroes = 8 - (distance % 8); // // /* Filling byte zeroes */ // for (int i = 0; i < numByteZeroes; i++) // { // result[i] = 0; // } // // /* Filling bit zeroes */ // BitSet bits = new BitSet(8); // bits.set(0, 8); // // for (int i = 0; i < numBitZeroes; i++) // { // /* Shift 1 zero into the start of the value */ // bits.clear(i); // } // bits.flip(0, 8); // Flip the bits since they're in reverse order // result[numByteZeroes] = (byte) bits.toByteArray()[0]; // // /* Set the remaining bytes to Maximum value */ // for (int i = numByteZeroes + 1; i < result.length; i++) // { // result[i] = Byte.MAX_VALUE; // } // // return this.xor(new Key(result)); // } // // /** // * Counts the number of leading 0's in this Key // * // * @return Integer The number of leading 0's // */ // public int getFirstSetBitIndex() // { // int prefixLength = 0; // // for (byte b : this.key.toByteArray()) // { // if (b == 0) // { // prefixLength += 8; // } // else // { // /* If the byte is not 0, we need to count how many MSBs are 0 */ // int count = 0; // for (int i = 7; i >= 0; i--) // { // boolean a = (b & (1 << i)) == 0; // if (a) // { // count++; // } // else // { // break; // Reset the count if we encounter a non-zero number // } // } // // /* Add the count of MSB 0s to the prefix length */ // prefixLength += count; // // /* Break here since we've now covered the MSB 0s */ // break; // } // } // return prefixLength; // } // // @Override // public String toString() // { // return this.key.toString(16); // } // // // /** // * Gets the distance from this Key to another Key // * // * @param to // * // * @return Integer The distance // */ // public int getDistance(Key to) // { // /** // * Compute the xor of this and to // * Get the index i of the first set bit of the xor returned Key // * The distance between them is ID_LENGTH - i // */ // return ID_LENGTH - this.xor(to).getFirstSetBitIndex(); // } // } // // Path: src/main/java/de/cgrotz/kademlia/node/Node.java // @Data // @EqualsAndHashCode(of={"id"}) // @Builder // public class Node implements Comparable<Node>{ // private Key id; // @Singular // private final List<Listener> advertisedListeners; // private long lastSeen = System.currentTimeMillis(); // // @Override // public int compareTo(Node o) { // if (this.equals(o)) // { // return 0; // } // // return (this.lastSeen > o.lastSeen) ? 1 : -1; // } // }
import de.cgrotz.kademlia.node.Key; import de.cgrotz.kademlia.node.Node; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString;
package de.cgrotz.kademlia.protocol; /** * * The recipient of the request will return the k nodes in his own buckets that are the closest ones to the requested key. * * Created by Christoph on 22.09.2016. */ @Data @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class FindNode extends Message {
// Path: src/main/java/de/cgrotz/kademlia/node/Key.java // @Data // @EqualsAndHashCode(of = "key") // public class Key { // public final static int ID_LENGTH = 160; // // private BigInteger key; // // public Key(byte[] result) { // if(result.length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = new BigInteger(result); // } // // public Key(BigInteger key) { // if( key.toByteArray().length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = key; // } // // public Key(int id) { // this.key = BigInteger.valueOf(id); // } // // public static Key random() { // byte[] bytes = new byte[ID_LENGTH / 8]; // SecureRandom sr1 = new SecureRandom(); // sr1.nextBytes(bytes); // return new Key(bytes); // } // // public static Key build(String key) { // return new Key(new BigInteger(key,16)); // } // // /** // * Checks the distance between this and another Key // * // * @param nid // * // * @return The distance of this Key from the given Key // */ // public Key xor(Key nid) // { // return new Key(nid.getKey().xor(this.key)); // } // // /** // * Generates a Key that is some distance away from this Key // * // * @param distance in number of bits // * // * @return Key The newly generated Key // */ // public Key generateNodeIdByDistance(int distance) // { // byte[] result = new byte[ID_LENGTH / 8]; // // /* Since distance = ID_LENGTH - prefixLength, we need to fill that amount with 0's */ // int numByteZeroes = (ID_LENGTH - distance) / 8; // int numBitZeroes = 8 - (distance % 8); // // /* Filling byte zeroes */ // for (int i = 0; i < numByteZeroes; i++) // { // result[i] = 0; // } // // /* Filling bit zeroes */ // BitSet bits = new BitSet(8); // bits.set(0, 8); // // for (int i = 0; i < numBitZeroes; i++) // { // /* Shift 1 zero into the start of the value */ // bits.clear(i); // } // bits.flip(0, 8); // Flip the bits since they're in reverse order // result[numByteZeroes] = (byte) bits.toByteArray()[0]; // // /* Set the remaining bytes to Maximum value */ // for (int i = numByteZeroes + 1; i < result.length; i++) // { // result[i] = Byte.MAX_VALUE; // } // // return this.xor(new Key(result)); // } // // /** // * Counts the number of leading 0's in this Key // * // * @return Integer The number of leading 0's // */ // public int getFirstSetBitIndex() // { // int prefixLength = 0; // // for (byte b : this.key.toByteArray()) // { // if (b == 0) // { // prefixLength += 8; // } // else // { // /* If the byte is not 0, we need to count how many MSBs are 0 */ // int count = 0; // for (int i = 7; i >= 0; i--) // { // boolean a = (b & (1 << i)) == 0; // if (a) // { // count++; // } // else // { // break; // Reset the count if we encounter a non-zero number // } // } // // /* Add the count of MSB 0s to the prefix length */ // prefixLength += count; // // /* Break here since we've now covered the MSB 0s */ // break; // } // } // return prefixLength; // } // // @Override // public String toString() // { // return this.key.toString(16); // } // // // /** // * Gets the distance from this Key to another Key // * // * @param to // * // * @return Integer The distance // */ // public int getDistance(Key to) // { // /** // * Compute the xor of this and to // * Get the index i of the first set bit of the xor returned Key // * The distance between them is ID_LENGTH - i // */ // return ID_LENGTH - this.xor(to).getFirstSetBitIndex(); // } // } // // Path: src/main/java/de/cgrotz/kademlia/node/Node.java // @Data // @EqualsAndHashCode(of={"id"}) // @Builder // public class Node implements Comparable<Node>{ // private Key id; // @Singular // private final List<Listener> advertisedListeners; // private long lastSeen = System.currentTimeMillis(); // // @Override // public int compareTo(Node o) { // if (this.equals(o)) // { // return 0; // } // // return (this.lastSeen > o.lastSeen) ? 1 : -1; // } // } // Path: src/main/java/de/cgrotz/kademlia/protocol/FindNode.java import de.cgrotz.kademlia.node.Key; import de.cgrotz.kademlia.node.Node; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; package de.cgrotz.kademlia.protocol; /** * * The recipient of the request will return the k nodes in his own buckets that are the closest ones to the requested key. * * Created by Christoph on 22.09.2016. */ @Data @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class FindNode extends Message {
private final Key lookupId;
cgrotz/kademlia
src/main/java/de/cgrotz/kademlia/protocol/FindNode.java
// Path: src/main/java/de/cgrotz/kademlia/node/Key.java // @Data // @EqualsAndHashCode(of = "key") // public class Key { // public final static int ID_LENGTH = 160; // // private BigInteger key; // // public Key(byte[] result) { // if(result.length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = new BigInteger(result); // } // // public Key(BigInteger key) { // if( key.toByteArray().length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = key; // } // // public Key(int id) { // this.key = BigInteger.valueOf(id); // } // // public static Key random() { // byte[] bytes = new byte[ID_LENGTH / 8]; // SecureRandom sr1 = new SecureRandom(); // sr1.nextBytes(bytes); // return new Key(bytes); // } // // public static Key build(String key) { // return new Key(new BigInteger(key,16)); // } // // /** // * Checks the distance between this and another Key // * // * @param nid // * // * @return The distance of this Key from the given Key // */ // public Key xor(Key nid) // { // return new Key(nid.getKey().xor(this.key)); // } // // /** // * Generates a Key that is some distance away from this Key // * // * @param distance in number of bits // * // * @return Key The newly generated Key // */ // public Key generateNodeIdByDistance(int distance) // { // byte[] result = new byte[ID_LENGTH / 8]; // // /* Since distance = ID_LENGTH - prefixLength, we need to fill that amount with 0's */ // int numByteZeroes = (ID_LENGTH - distance) / 8; // int numBitZeroes = 8 - (distance % 8); // // /* Filling byte zeroes */ // for (int i = 0; i < numByteZeroes; i++) // { // result[i] = 0; // } // // /* Filling bit zeroes */ // BitSet bits = new BitSet(8); // bits.set(0, 8); // // for (int i = 0; i < numBitZeroes; i++) // { // /* Shift 1 zero into the start of the value */ // bits.clear(i); // } // bits.flip(0, 8); // Flip the bits since they're in reverse order // result[numByteZeroes] = (byte) bits.toByteArray()[0]; // // /* Set the remaining bytes to Maximum value */ // for (int i = numByteZeroes + 1; i < result.length; i++) // { // result[i] = Byte.MAX_VALUE; // } // // return this.xor(new Key(result)); // } // // /** // * Counts the number of leading 0's in this Key // * // * @return Integer The number of leading 0's // */ // public int getFirstSetBitIndex() // { // int prefixLength = 0; // // for (byte b : this.key.toByteArray()) // { // if (b == 0) // { // prefixLength += 8; // } // else // { // /* If the byte is not 0, we need to count how many MSBs are 0 */ // int count = 0; // for (int i = 7; i >= 0; i--) // { // boolean a = (b & (1 << i)) == 0; // if (a) // { // count++; // } // else // { // break; // Reset the count if we encounter a non-zero number // } // } // // /* Add the count of MSB 0s to the prefix length */ // prefixLength += count; // // /* Break here since we've now covered the MSB 0s */ // break; // } // } // return prefixLength; // } // // @Override // public String toString() // { // return this.key.toString(16); // } // // // /** // * Gets the distance from this Key to another Key // * // * @param to // * // * @return Integer The distance // */ // public int getDistance(Key to) // { // /** // * Compute the xor of this and to // * Get the index i of the first set bit of the xor returned Key // * The distance between them is ID_LENGTH - i // */ // return ID_LENGTH - this.xor(to).getFirstSetBitIndex(); // } // } // // Path: src/main/java/de/cgrotz/kademlia/node/Node.java // @Data // @EqualsAndHashCode(of={"id"}) // @Builder // public class Node implements Comparable<Node>{ // private Key id; // @Singular // private final List<Listener> advertisedListeners; // private long lastSeen = System.currentTimeMillis(); // // @Override // public int compareTo(Node o) { // if (this.equals(o)) // { // return 0; // } // // return (this.lastSeen > o.lastSeen) ? 1 : -1; // } // }
import de.cgrotz.kademlia.node.Key; import de.cgrotz.kademlia.node.Node; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString;
package de.cgrotz.kademlia.protocol; /** * * The recipient of the request will return the k nodes in his own buckets that are the closest ones to the requested key. * * Created by Christoph on 22.09.2016. */ @Data @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class FindNode extends Message { private final Key lookupId;
// Path: src/main/java/de/cgrotz/kademlia/node/Key.java // @Data // @EqualsAndHashCode(of = "key") // public class Key { // public final static int ID_LENGTH = 160; // // private BigInteger key; // // public Key(byte[] result) { // if(result.length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = new BigInteger(result); // } // // public Key(BigInteger key) { // if( key.toByteArray().length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = key; // } // // public Key(int id) { // this.key = BigInteger.valueOf(id); // } // // public static Key random() { // byte[] bytes = new byte[ID_LENGTH / 8]; // SecureRandom sr1 = new SecureRandom(); // sr1.nextBytes(bytes); // return new Key(bytes); // } // // public static Key build(String key) { // return new Key(new BigInteger(key,16)); // } // // /** // * Checks the distance between this and another Key // * // * @param nid // * // * @return The distance of this Key from the given Key // */ // public Key xor(Key nid) // { // return new Key(nid.getKey().xor(this.key)); // } // // /** // * Generates a Key that is some distance away from this Key // * // * @param distance in number of bits // * // * @return Key The newly generated Key // */ // public Key generateNodeIdByDistance(int distance) // { // byte[] result = new byte[ID_LENGTH / 8]; // // /* Since distance = ID_LENGTH - prefixLength, we need to fill that amount with 0's */ // int numByteZeroes = (ID_LENGTH - distance) / 8; // int numBitZeroes = 8 - (distance % 8); // // /* Filling byte zeroes */ // for (int i = 0; i < numByteZeroes; i++) // { // result[i] = 0; // } // // /* Filling bit zeroes */ // BitSet bits = new BitSet(8); // bits.set(0, 8); // // for (int i = 0; i < numBitZeroes; i++) // { // /* Shift 1 zero into the start of the value */ // bits.clear(i); // } // bits.flip(0, 8); // Flip the bits since they're in reverse order // result[numByteZeroes] = (byte) bits.toByteArray()[0]; // // /* Set the remaining bytes to Maximum value */ // for (int i = numByteZeroes + 1; i < result.length; i++) // { // result[i] = Byte.MAX_VALUE; // } // // return this.xor(new Key(result)); // } // // /** // * Counts the number of leading 0's in this Key // * // * @return Integer The number of leading 0's // */ // public int getFirstSetBitIndex() // { // int prefixLength = 0; // // for (byte b : this.key.toByteArray()) // { // if (b == 0) // { // prefixLength += 8; // } // else // { // /* If the byte is not 0, we need to count how many MSBs are 0 */ // int count = 0; // for (int i = 7; i >= 0; i--) // { // boolean a = (b & (1 << i)) == 0; // if (a) // { // count++; // } // else // { // break; // Reset the count if we encounter a non-zero number // } // } // // /* Add the count of MSB 0s to the prefix length */ // prefixLength += count; // // /* Break here since we've now covered the MSB 0s */ // break; // } // } // return prefixLength; // } // // @Override // public String toString() // { // return this.key.toString(16); // } // // // /** // * Gets the distance from this Key to another Key // * // * @param to // * // * @return Integer The distance // */ // public int getDistance(Key to) // { // /** // * Compute the xor of this and to // * Get the index i of the first set bit of the xor returned Key // * The distance between them is ID_LENGTH - i // */ // return ID_LENGTH - this.xor(to).getFirstSetBitIndex(); // } // } // // Path: src/main/java/de/cgrotz/kademlia/node/Node.java // @Data // @EqualsAndHashCode(of={"id"}) // @Builder // public class Node implements Comparable<Node>{ // private Key id; // @Singular // private final List<Listener> advertisedListeners; // private long lastSeen = System.currentTimeMillis(); // // @Override // public int compareTo(Node o) { // if (this.equals(o)) // { // return 0; // } // // return (this.lastSeen > o.lastSeen) ? 1 : -1; // } // } // Path: src/main/java/de/cgrotz/kademlia/protocol/FindNode.java import de.cgrotz.kademlia.node.Key; import de.cgrotz.kademlia.node.Node; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; package de.cgrotz.kademlia.protocol; /** * * The recipient of the request will return the k nodes in his own buckets that are the closest ones to the requested key. * * Created by Christoph on 22.09.2016. */ @Data @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class FindNode extends Message { private final Key lookupId;
public FindNode(long seqId, Node origin, Key lookupId) {
cgrotz/kademlia
src/main/java/de/cgrotz/kademlia/protocol/Store.java
// Path: src/main/java/de/cgrotz/kademlia/node/Key.java // @Data // @EqualsAndHashCode(of = "key") // public class Key { // public final static int ID_LENGTH = 160; // // private BigInteger key; // // public Key(byte[] result) { // if(result.length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = new BigInteger(result); // } // // public Key(BigInteger key) { // if( key.toByteArray().length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = key; // } // // public Key(int id) { // this.key = BigInteger.valueOf(id); // } // // public static Key random() { // byte[] bytes = new byte[ID_LENGTH / 8]; // SecureRandom sr1 = new SecureRandom(); // sr1.nextBytes(bytes); // return new Key(bytes); // } // // public static Key build(String key) { // return new Key(new BigInteger(key,16)); // } // // /** // * Checks the distance between this and another Key // * // * @param nid // * // * @return The distance of this Key from the given Key // */ // public Key xor(Key nid) // { // return new Key(nid.getKey().xor(this.key)); // } // // /** // * Generates a Key that is some distance away from this Key // * // * @param distance in number of bits // * // * @return Key The newly generated Key // */ // public Key generateNodeIdByDistance(int distance) // { // byte[] result = new byte[ID_LENGTH / 8]; // // /* Since distance = ID_LENGTH - prefixLength, we need to fill that amount with 0's */ // int numByteZeroes = (ID_LENGTH - distance) / 8; // int numBitZeroes = 8 - (distance % 8); // // /* Filling byte zeroes */ // for (int i = 0; i < numByteZeroes; i++) // { // result[i] = 0; // } // // /* Filling bit zeroes */ // BitSet bits = new BitSet(8); // bits.set(0, 8); // // for (int i = 0; i < numBitZeroes; i++) // { // /* Shift 1 zero into the start of the value */ // bits.clear(i); // } // bits.flip(0, 8); // Flip the bits since they're in reverse order // result[numByteZeroes] = (byte) bits.toByteArray()[0]; // // /* Set the remaining bytes to Maximum value */ // for (int i = numByteZeroes + 1; i < result.length; i++) // { // result[i] = Byte.MAX_VALUE; // } // // return this.xor(new Key(result)); // } // // /** // * Counts the number of leading 0's in this Key // * // * @return Integer The number of leading 0's // */ // public int getFirstSetBitIndex() // { // int prefixLength = 0; // // for (byte b : this.key.toByteArray()) // { // if (b == 0) // { // prefixLength += 8; // } // else // { // /* If the byte is not 0, we need to count how many MSBs are 0 */ // int count = 0; // for (int i = 7; i >= 0; i--) // { // boolean a = (b & (1 << i)) == 0; // if (a) // { // count++; // } // else // { // break; // Reset the count if we encounter a non-zero number // } // } // // /* Add the count of MSB 0s to the prefix length */ // prefixLength += count; // // /* Break here since we've now covered the MSB 0s */ // break; // } // } // return prefixLength; // } // // @Override // public String toString() // { // return this.key.toString(16); // } // // // /** // * Gets the distance from this Key to another Key // * // * @param to // * // * @return Integer The distance // */ // public int getDistance(Key to) // { // /** // * Compute the xor of this and to // * Get the index i of the first set bit of the xor returned Key // * The distance between them is ID_LENGTH - i // */ // return ID_LENGTH - this.xor(to).getFirstSetBitIndex(); // } // } // // Path: src/main/java/de/cgrotz/kademlia/node/Node.java // @Data // @EqualsAndHashCode(of={"id"}) // @Builder // public class Node implements Comparable<Node>{ // private Key id; // @Singular // private final List<Listener> advertisedListeners; // private long lastSeen = System.currentTimeMillis(); // // @Override // public int compareTo(Node o) { // if (this.equals(o)) // { // return 0; // } // // return (this.lastSeen > o.lastSeen) ? 1 : -1; // } // }
import de.cgrotz.kademlia.node.Key; import de.cgrotz.kademlia.node.Node; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString;
package de.cgrotz.kademlia.protocol; /** * * Stores a (key, value) pair in one node. * * Created by Christoph on 22.09.2016. */ @Data @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class Store extends Message { private final String value;
// Path: src/main/java/de/cgrotz/kademlia/node/Key.java // @Data // @EqualsAndHashCode(of = "key") // public class Key { // public final static int ID_LENGTH = 160; // // private BigInteger key; // // public Key(byte[] result) { // if(result.length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = new BigInteger(result); // } // // public Key(BigInteger key) { // if( key.toByteArray().length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = key; // } // // public Key(int id) { // this.key = BigInteger.valueOf(id); // } // // public static Key random() { // byte[] bytes = new byte[ID_LENGTH / 8]; // SecureRandom sr1 = new SecureRandom(); // sr1.nextBytes(bytes); // return new Key(bytes); // } // // public static Key build(String key) { // return new Key(new BigInteger(key,16)); // } // // /** // * Checks the distance between this and another Key // * // * @param nid // * // * @return The distance of this Key from the given Key // */ // public Key xor(Key nid) // { // return new Key(nid.getKey().xor(this.key)); // } // // /** // * Generates a Key that is some distance away from this Key // * // * @param distance in number of bits // * // * @return Key The newly generated Key // */ // public Key generateNodeIdByDistance(int distance) // { // byte[] result = new byte[ID_LENGTH / 8]; // // /* Since distance = ID_LENGTH - prefixLength, we need to fill that amount with 0's */ // int numByteZeroes = (ID_LENGTH - distance) / 8; // int numBitZeroes = 8 - (distance % 8); // // /* Filling byte zeroes */ // for (int i = 0; i < numByteZeroes; i++) // { // result[i] = 0; // } // // /* Filling bit zeroes */ // BitSet bits = new BitSet(8); // bits.set(0, 8); // // for (int i = 0; i < numBitZeroes; i++) // { // /* Shift 1 zero into the start of the value */ // bits.clear(i); // } // bits.flip(0, 8); // Flip the bits since they're in reverse order // result[numByteZeroes] = (byte) bits.toByteArray()[0]; // // /* Set the remaining bytes to Maximum value */ // for (int i = numByteZeroes + 1; i < result.length; i++) // { // result[i] = Byte.MAX_VALUE; // } // // return this.xor(new Key(result)); // } // // /** // * Counts the number of leading 0's in this Key // * // * @return Integer The number of leading 0's // */ // public int getFirstSetBitIndex() // { // int prefixLength = 0; // // for (byte b : this.key.toByteArray()) // { // if (b == 0) // { // prefixLength += 8; // } // else // { // /* If the byte is not 0, we need to count how many MSBs are 0 */ // int count = 0; // for (int i = 7; i >= 0; i--) // { // boolean a = (b & (1 << i)) == 0; // if (a) // { // count++; // } // else // { // break; // Reset the count if we encounter a non-zero number // } // } // // /* Add the count of MSB 0s to the prefix length */ // prefixLength += count; // // /* Break here since we've now covered the MSB 0s */ // break; // } // } // return prefixLength; // } // // @Override // public String toString() // { // return this.key.toString(16); // } // // // /** // * Gets the distance from this Key to another Key // * // * @param to // * // * @return Integer The distance // */ // public int getDistance(Key to) // { // /** // * Compute the xor of this and to // * Get the index i of the first set bit of the xor returned Key // * The distance between them is ID_LENGTH - i // */ // return ID_LENGTH - this.xor(to).getFirstSetBitIndex(); // } // } // // Path: src/main/java/de/cgrotz/kademlia/node/Node.java // @Data // @EqualsAndHashCode(of={"id"}) // @Builder // public class Node implements Comparable<Node>{ // private Key id; // @Singular // private final List<Listener> advertisedListeners; // private long lastSeen = System.currentTimeMillis(); // // @Override // public int compareTo(Node o) { // if (this.equals(o)) // { // return 0; // } // // return (this.lastSeen > o.lastSeen) ? 1 : -1; // } // } // Path: src/main/java/de/cgrotz/kademlia/protocol/Store.java import de.cgrotz.kademlia.node.Key; import de.cgrotz.kademlia.node.Node; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; package de.cgrotz.kademlia.protocol; /** * * Stores a (key, value) pair in one node. * * Created by Christoph on 22.09.2016. */ @Data @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class Store extends Message { private final String value;
private final Key key;
cgrotz/kademlia
src/main/java/de/cgrotz/kademlia/protocol/Store.java
// Path: src/main/java/de/cgrotz/kademlia/node/Key.java // @Data // @EqualsAndHashCode(of = "key") // public class Key { // public final static int ID_LENGTH = 160; // // private BigInteger key; // // public Key(byte[] result) { // if(result.length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = new BigInteger(result); // } // // public Key(BigInteger key) { // if( key.toByteArray().length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = key; // } // // public Key(int id) { // this.key = BigInteger.valueOf(id); // } // // public static Key random() { // byte[] bytes = new byte[ID_LENGTH / 8]; // SecureRandom sr1 = new SecureRandom(); // sr1.nextBytes(bytes); // return new Key(bytes); // } // // public static Key build(String key) { // return new Key(new BigInteger(key,16)); // } // // /** // * Checks the distance between this and another Key // * // * @param nid // * // * @return The distance of this Key from the given Key // */ // public Key xor(Key nid) // { // return new Key(nid.getKey().xor(this.key)); // } // // /** // * Generates a Key that is some distance away from this Key // * // * @param distance in number of bits // * // * @return Key The newly generated Key // */ // public Key generateNodeIdByDistance(int distance) // { // byte[] result = new byte[ID_LENGTH / 8]; // // /* Since distance = ID_LENGTH - prefixLength, we need to fill that amount with 0's */ // int numByteZeroes = (ID_LENGTH - distance) / 8; // int numBitZeroes = 8 - (distance % 8); // // /* Filling byte zeroes */ // for (int i = 0; i < numByteZeroes; i++) // { // result[i] = 0; // } // // /* Filling bit zeroes */ // BitSet bits = new BitSet(8); // bits.set(0, 8); // // for (int i = 0; i < numBitZeroes; i++) // { // /* Shift 1 zero into the start of the value */ // bits.clear(i); // } // bits.flip(0, 8); // Flip the bits since they're in reverse order // result[numByteZeroes] = (byte) bits.toByteArray()[0]; // // /* Set the remaining bytes to Maximum value */ // for (int i = numByteZeroes + 1; i < result.length; i++) // { // result[i] = Byte.MAX_VALUE; // } // // return this.xor(new Key(result)); // } // // /** // * Counts the number of leading 0's in this Key // * // * @return Integer The number of leading 0's // */ // public int getFirstSetBitIndex() // { // int prefixLength = 0; // // for (byte b : this.key.toByteArray()) // { // if (b == 0) // { // prefixLength += 8; // } // else // { // /* If the byte is not 0, we need to count how many MSBs are 0 */ // int count = 0; // for (int i = 7; i >= 0; i--) // { // boolean a = (b & (1 << i)) == 0; // if (a) // { // count++; // } // else // { // break; // Reset the count if we encounter a non-zero number // } // } // // /* Add the count of MSB 0s to the prefix length */ // prefixLength += count; // // /* Break here since we've now covered the MSB 0s */ // break; // } // } // return prefixLength; // } // // @Override // public String toString() // { // return this.key.toString(16); // } // // // /** // * Gets the distance from this Key to another Key // * // * @param to // * // * @return Integer The distance // */ // public int getDistance(Key to) // { // /** // * Compute the xor of this and to // * Get the index i of the first set bit of the xor returned Key // * The distance between them is ID_LENGTH - i // */ // return ID_LENGTH - this.xor(to).getFirstSetBitIndex(); // } // } // // Path: src/main/java/de/cgrotz/kademlia/node/Node.java // @Data // @EqualsAndHashCode(of={"id"}) // @Builder // public class Node implements Comparable<Node>{ // private Key id; // @Singular // private final List<Listener> advertisedListeners; // private long lastSeen = System.currentTimeMillis(); // // @Override // public int compareTo(Node o) { // if (this.equals(o)) // { // return 0; // } // // return (this.lastSeen > o.lastSeen) ? 1 : -1; // } // }
import de.cgrotz.kademlia.node.Key; import de.cgrotz.kademlia.node.Node; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString;
package de.cgrotz.kademlia.protocol; /** * * Stores a (key, value) pair in one node. * * Created by Christoph on 22.09.2016. */ @Data @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class Store extends Message { private final String value; private final Key key;
// Path: src/main/java/de/cgrotz/kademlia/node/Key.java // @Data // @EqualsAndHashCode(of = "key") // public class Key { // public final static int ID_LENGTH = 160; // // private BigInteger key; // // public Key(byte[] result) { // if(result.length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = new BigInteger(result); // } // // public Key(BigInteger key) { // if( key.toByteArray().length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = key; // } // // public Key(int id) { // this.key = BigInteger.valueOf(id); // } // // public static Key random() { // byte[] bytes = new byte[ID_LENGTH / 8]; // SecureRandom sr1 = new SecureRandom(); // sr1.nextBytes(bytes); // return new Key(bytes); // } // // public static Key build(String key) { // return new Key(new BigInteger(key,16)); // } // // /** // * Checks the distance between this and another Key // * // * @param nid // * // * @return The distance of this Key from the given Key // */ // public Key xor(Key nid) // { // return new Key(nid.getKey().xor(this.key)); // } // // /** // * Generates a Key that is some distance away from this Key // * // * @param distance in number of bits // * // * @return Key The newly generated Key // */ // public Key generateNodeIdByDistance(int distance) // { // byte[] result = new byte[ID_LENGTH / 8]; // // /* Since distance = ID_LENGTH - prefixLength, we need to fill that amount with 0's */ // int numByteZeroes = (ID_LENGTH - distance) / 8; // int numBitZeroes = 8 - (distance % 8); // // /* Filling byte zeroes */ // for (int i = 0; i < numByteZeroes; i++) // { // result[i] = 0; // } // // /* Filling bit zeroes */ // BitSet bits = new BitSet(8); // bits.set(0, 8); // // for (int i = 0; i < numBitZeroes; i++) // { // /* Shift 1 zero into the start of the value */ // bits.clear(i); // } // bits.flip(0, 8); // Flip the bits since they're in reverse order // result[numByteZeroes] = (byte) bits.toByteArray()[0]; // // /* Set the remaining bytes to Maximum value */ // for (int i = numByteZeroes + 1; i < result.length; i++) // { // result[i] = Byte.MAX_VALUE; // } // // return this.xor(new Key(result)); // } // // /** // * Counts the number of leading 0's in this Key // * // * @return Integer The number of leading 0's // */ // public int getFirstSetBitIndex() // { // int prefixLength = 0; // // for (byte b : this.key.toByteArray()) // { // if (b == 0) // { // prefixLength += 8; // } // else // { // /* If the byte is not 0, we need to count how many MSBs are 0 */ // int count = 0; // for (int i = 7; i >= 0; i--) // { // boolean a = (b & (1 << i)) == 0; // if (a) // { // count++; // } // else // { // break; // Reset the count if we encounter a non-zero number // } // } // // /* Add the count of MSB 0s to the prefix length */ // prefixLength += count; // // /* Break here since we've now covered the MSB 0s */ // break; // } // } // return prefixLength; // } // // @Override // public String toString() // { // return this.key.toString(16); // } // // // /** // * Gets the distance from this Key to another Key // * // * @param to // * // * @return Integer The distance // */ // public int getDistance(Key to) // { // /** // * Compute the xor of this and to // * Get the index i of the first set bit of the xor returned Key // * The distance between them is ID_LENGTH - i // */ // return ID_LENGTH - this.xor(to).getFirstSetBitIndex(); // } // } // // Path: src/main/java/de/cgrotz/kademlia/node/Node.java // @Data // @EqualsAndHashCode(of={"id"}) // @Builder // public class Node implements Comparable<Node>{ // private Key id; // @Singular // private final List<Listener> advertisedListeners; // private long lastSeen = System.currentTimeMillis(); // // @Override // public int compareTo(Node o) { // if (this.equals(o)) // { // return 0; // } // // return (this.lastSeen > o.lastSeen) ? 1 : -1; // } // } // Path: src/main/java/de/cgrotz/kademlia/protocol/Store.java import de.cgrotz.kademlia.node.Key; import de.cgrotz.kademlia.node.Node; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; package de.cgrotz.kademlia.protocol; /** * * Stores a (key, value) pair in one node. * * Created by Christoph on 22.09.2016. */ @Data @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class Store extends Message { private final String value; private final Key key;
public Store(long seqId, Node origin, Key key, String value) {
cgrotz/kademlia
src/main/java/de/cgrotz/kademlia/protocol/Ping.java
// Path: src/main/java/de/cgrotz/kademlia/node/Node.java // @Data // @EqualsAndHashCode(of={"id"}) // @Builder // public class Node implements Comparable<Node>{ // private Key id; // @Singular // private final List<Listener> advertisedListeners; // private long lastSeen = System.currentTimeMillis(); // // @Override // public int compareTo(Node o) { // if (this.equals(o)) // { // return 0; // } // // return (this.lastSeen > o.lastSeen) ? 1 : -1; // } // }
import de.cgrotz.kademlia.node.Node; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString;
package de.cgrotz.kademlia.protocol; /** * * Used to verify that a node is still alive. * * Created by Christoph on 22.09.2016. */ @Data @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class Ping extends Message {
// Path: src/main/java/de/cgrotz/kademlia/node/Node.java // @Data // @EqualsAndHashCode(of={"id"}) // @Builder // public class Node implements Comparable<Node>{ // private Key id; // @Singular // private final List<Listener> advertisedListeners; // private long lastSeen = System.currentTimeMillis(); // // @Override // public int compareTo(Node o) { // if (this.equals(o)) // { // return 0; // } // // return (this.lastSeen > o.lastSeen) ? 1 : -1; // } // } // Path: src/main/java/de/cgrotz/kademlia/protocol/Ping.java import de.cgrotz.kademlia.node.Node; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; package de.cgrotz.kademlia.protocol; /** * * Used to verify that a node is still alive. * * Created by Christoph on 22.09.2016. */ @Data @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class Ping extends Message {
public Ping(long seqId, Node origin) {
cgrotz/kademlia
src/main/java/de/cgrotz/kademlia/Configuration.java
// Path: src/main/java/de/cgrotz/kademlia/config/Listener.java // @Data // @Builder // public class Listener { // private ListenerType type; // // public static Listener fromUrl(String url) { // if(url.startsWith(ListenerType.UDP.prefix())) { // return UdpListener.from(url); // } // else { // throw new UnknownListenerType(url); // } // } // } // // Path: src/main/java/de/cgrotz/kademlia/node/Key.java // @Data // @EqualsAndHashCode(of = "key") // public class Key { // public final static int ID_LENGTH = 160; // // private BigInteger key; // // public Key(byte[] result) { // if(result.length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = new BigInteger(result); // } // // public Key(BigInteger key) { // if( key.toByteArray().length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = key; // } // // public Key(int id) { // this.key = BigInteger.valueOf(id); // } // // public static Key random() { // byte[] bytes = new byte[ID_LENGTH / 8]; // SecureRandom sr1 = new SecureRandom(); // sr1.nextBytes(bytes); // return new Key(bytes); // } // // public static Key build(String key) { // return new Key(new BigInteger(key,16)); // } // // /** // * Checks the distance between this and another Key // * // * @param nid // * // * @return The distance of this Key from the given Key // */ // public Key xor(Key nid) // { // return new Key(nid.getKey().xor(this.key)); // } // // /** // * Generates a Key that is some distance away from this Key // * // * @param distance in number of bits // * // * @return Key The newly generated Key // */ // public Key generateNodeIdByDistance(int distance) // { // byte[] result = new byte[ID_LENGTH / 8]; // // /* Since distance = ID_LENGTH - prefixLength, we need to fill that amount with 0's */ // int numByteZeroes = (ID_LENGTH - distance) / 8; // int numBitZeroes = 8 - (distance % 8); // // /* Filling byte zeroes */ // for (int i = 0; i < numByteZeroes; i++) // { // result[i] = 0; // } // // /* Filling bit zeroes */ // BitSet bits = new BitSet(8); // bits.set(0, 8); // // for (int i = 0; i < numBitZeroes; i++) // { // /* Shift 1 zero into the start of the value */ // bits.clear(i); // } // bits.flip(0, 8); // Flip the bits since they're in reverse order // result[numByteZeroes] = (byte) bits.toByteArray()[0]; // // /* Set the remaining bytes to Maximum value */ // for (int i = numByteZeroes + 1; i < result.length; i++) // { // result[i] = Byte.MAX_VALUE; // } // // return this.xor(new Key(result)); // } // // /** // * Counts the number of leading 0's in this Key // * // * @return Integer The number of leading 0's // */ // public int getFirstSetBitIndex() // { // int prefixLength = 0; // // for (byte b : this.key.toByteArray()) // { // if (b == 0) // { // prefixLength += 8; // } // else // { // /* If the byte is not 0, we need to count how many MSBs are 0 */ // int count = 0; // for (int i = 7; i >= 0; i--) // { // boolean a = (b & (1 << i)) == 0; // if (a) // { // count++; // } // else // { // break; // Reset the count if we encounter a non-zero number // } // } // // /* Add the count of MSB 0s to the prefix length */ // prefixLength += count; // // /* Break here since we've now covered the MSB 0s */ // break; // } // } // return prefixLength; // } // // @Override // public String toString() // { // return this.key.toString(16); // } // // // /** // * Gets the distance from this Key to another Key // * // * @param to // * // * @return Integer The distance // */ // public int getDistance(Key to) // { // /** // * Compute the xor of this and to // * Get the index i of the first set bit of the xor returned Key // * The distance between them is ID_LENGTH - i // */ // return ID_LENGTH - this.xor(to).getFirstSetBitIndex(); // } // }
import de.cgrotz.kademlia.config.Listener; import de.cgrotz.kademlia.node.Key; import lombok.Builder; import lombok.Data; import lombok.Singular; import java.util.List;
package de.cgrotz.kademlia; /** * Created by Christoph on 28.09.2016. */ @Data @Builder public class Configuration {
// Path: src/main/java/de/cgrotz/kademlia/config/Listener.java // @Data // @Builder // public class Listener { // private ListenerType type; // // public static Listener fromUrl(String url) { // if(url.startsWith(ListenerType.UDP.prefix())) { // return UdpListener.from(url); // } // else { // throw new UnknownListenerType(url); // } // } // } // // Path: src/main/java/de/cgrotz/kademlia/node/Key.java // @Data // @EqualsAndHashCode(of = "key") // public class Key { // public final static int ID_LENGTH = 160; // // private BigInteger key; // // public Key(byte[] result) { // if(result.length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = new BigInteger(result); // } // // public Key(BigInteger key) { // if( key.toByteArray().length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = key; // } // // public Key(int id) { // this.key = BigInteger.valueOf(id); // } // // public static Key random() { // byte[] bytes = new byte[ID_LENGTH / 8]; // SecureRandom sr1 = new SecureRandom(); // sr1.nextBytes(bytes); // return new Key(bytes); // } // // public static Key build(String key) { // return new Key(new BigInteger(key,16)); // } // // /** // * Checks the distance between this and another Key // * // * @param nid // * // * @return The distance of this Key from the given Key // */ // public Key xor(Key nid) // { // return new Key(nid.getKey().xor(this.key)); // } // // /** // * Generates a Key that is some distance away from this Key // * // * @param distance in number of bits // * // * @return Key The newly generated Key // */ // public Key generateNodeIdByDistance(int distance) // { // byte[] result = new byte[ID_LENGTH / 8]; // // /* Since distance = ID_LENGTH - prefixLength, we need to fill that amount with 0's */ // int numByteZeroes = (ID_LENGTH - distance) / 8; // int numBitZeroes = 8 - (distance % 8); // // /* Filling byte zeroes */ // for (int i = 0; i < numByteZeroes; i++) // { // result[i] = 0; // } // // /* Filling bit zeroes */ // BitSet bits = new BitSet(8); // bits.set(0, 8); // // for (int i = 0; i < numBitZeroes; i++) // { // /* Shift 1 zero into the start of the value */ // bits.clear(i); // } // bits.flip(0, 8); // Flip the bits since they're in reverse order // result[numByteZeroes] = (byte) bits.toByteArray()[0]; // // /* Set the remaining bytes to Maximum value */ // for (int i = numByteZeroes + 1; i < result.length; i++) // { // result[i] = Byte.MAX_VALUE; // } // // return this.xor(new Key(result)); // } // // /** // * Counts the number of leading 0's in this Key // * // * @return Integer The number of leading 0's // */ // public int getFirstSetBitIndex() // { // int prefixLength = 0; // // for (byte b : this.key.toByteArray()) // { // if (b == 0) // { // prefixLength += 8; // } // else // { // /* If the byte is not 0, we need to count how many MSBs are 0 */ // int count = 0; // for (int i = 7; i >= 0; i--) // { // boolean a = (b & (1 << i)) == 0; // if (a) // { // count++; // } // else // { // break; // Reset the count if we encounter a non-zero number // } // } // // /* Add the count of MSB 0s to the prefix length */ // prefixLength += count; // // /* Break here since we've now covered the MSB 0s */ // break; // } // } // return prefixLength; // } // // @Override // public String toString() // { // return this.key.toString(16); // } // // // /** // * Gets the distance from this Key to another Key // * // * @param to // * // * @return Integer The distance // */ // public int getDistance(Key to) // { // /** // * Compute the xor of this and to // * Get the index i of the first set bit of the xor returned Key // * The distance between them is ID_LENGTH - i // */ // return ID_LENGTH - this.xor(to).getFirstSetBitIndex(); // } // } // Path: src/main/java/de/cgrotz/kademlia/Configuration.java import de.cgrotz.kademlia.config.Listener; import de.cgrotz.kademlia.node.Key; import lombok.Builder; import lombok.Data; import lombok.Singular; import java.util.List; package de.cgrotz.kademlia; /** * Created by Christoph on 28.09.2016. */ @Data @Builder public class Configuration {
private final Key nodeId;
cgrotz/kademlia
src/main/java/de/cgrotz/kademlia/Configuration.java
// Path: src/main/java/de/cgrotz/kademlia/config/Listener.java // @Data // @Builder // public class Listener { // private ListenerType type; // // public static Listener fromUrl(String url) { // if(url.startsWith(ListenerType.UDP.prefix())) { // return UdpListener.from(url); // } // else { // throw new UnknownListenerType(url); // } // } // } // // Path: src/main/java/de/cgrotz/kademlia/node/Key.java // @Data // @EqualsAndHashCode(of = "key") // public class Key { // public final static int ID_LENGTH = 160; // // private BigInteger key; // // public Key(byte[] result) { // if(result.length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = new BigInteger(result); // } // // public Key(BigInteger key) { // if( key.toByteArray().length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = key; // } // // public Key(int id) { // this.key = BigInteger.valueOf(id); // } // // public static Key random() { // byte[] bytes = new byte[ID_LENGTH / 8]; // SecureRandom sr1 = new SecureRandom(); // sr1.nextBytes(bytes); // return new Key(bytes); // } // // public static Key build(String key) { // return new Key(new BigInteger(key,16)); // } // // /** // * Checks the distance between this and another Key // * // * @param nid // * // * @return The distance of this Key from the given Key // */ // public Key xor(Key nid) // { // return new Key(nid.getKey().xor(this.key)); // } // // /** // * Generates a Key that is some distance away from this Key // * // * @param distance in number of bits // * // * @return Key The newly generated Key // */ // public Key generateNodeIdByDistance(int distance) // { // byte[] result = new byte[ID_LENGTH / 8]; // // /* Since distance = ID_LENGTH - prefixLength, we need to fill that amount with 0's */ // int numByteZeroes = (ID_LENGTH - distance) / 8; // int numBitZeroes = 8 - (distance % 8); // // /* Filling byte zeroes */ // for (int i = 0; i < numByteZeroes; i++) // { // result[i] = 0; // } // // /* Filling bit zeroes */ // BitSet bits = new BitSet(8); // bits.set(0, 8); // // for (int i = 0; i < numBitZeroes; i++) // { // /* Shift 1 zero into the start of the value */ // bits.clear(i); // } // bits.flip(0, 8); // Flip the bits since they're in reverse order // result[numByteZeroes] = (byte) bits.toByteArray()[0]; // // /* Set the remaining bytes to Maximum value */ // for (int i = numByteZeroes + 1; i < result.length; i++) // { // result[i] = Byte.MAX_VALUE; // } // // return this.xor(new Key(result)); // } // // /** // * Counts the number of leading 0's in this Key // * // * @return Integer The number of leading 0's // */ // public int getFirstSetBitIndex() // { // int prefixLength = 0; // // for (byte b : this.key.toByteArray()) // { // if (b == 0) // { // prefixLength += 8; // } // else // { // /* If the byte is not 0, we need to count how many MSBs are 0 */ // int count = 0; // for (int i = 7; i >= 0; i--) // { // boolean a = (b & (1 << i)) == 0; // if (a) // { // count++; // } // else // { // break; // Reset the count if we encounter a non-zero number // } // } // // /* Add the count of MSB 0s to the prefix length */ // prefixLength += count; // // /* Break here since we've now covered the MSB 0s */ // break; // } // } // return prefixLength; // } // // @Override // public String toString() // { // return this.key.toString(16); // } // // // /** // * Gets the distance from this Key to another Key // * // * @param to // * // * @return Integer The distance // */ // public int getDistance(Key to) // { // /** // * Compute the xor of this and to // * Get the index i of the first set bit of the xor returned Key // * The distance between them is ID_LENGTH - i // */ // return ID_LENGTH - this.xor(to).getFirstSetBitIndex(); // } // }
import de.cgrotz.kademlia.config.Listener; import de.cgrotz.kademlia.node.Key; import lombok.Builder; import lombok.Data; import lombok.Singular; import java.util.List;
package de.cgrotz.kademlia; /** * Created by Christoph on 28.09.2016. */ @Data @Builder public class Configuration { private final Key nodeId; private final long getTimeoutMs; private final long networkTimeoutMs; private final int kValue; @Singular
// Path: src/main/java/de/cgrotz/kademlia/config/Listener.java // @Data // @Builder // public class Listener { // private ListenerType type; // // public static Listener fromUrl(String url) { // if(url.startsWith(ListenerType.UDP.prefix())) { // return UdpListener.from(url); // } // else { // throw new UnknownListenerType(url); // } // } // } // // Path: src/main/java/de/cgrotz/kademlia/node/Key.java // @Data // @EqualsAndHashCode(of = "key") // public class Key { // public final static int ID_LENGTH = 160; // // private BigInteger key; // // public Key(byte[] result) { // if(result.length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = new BigInteger(result); // } // // public Key(BigInteger key) { // if( key.toByteArray().length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = key; // } // // public Key(int id) { // this.key = BigInteger.valueOf(id); // } // // public static Key random() { // byte[] bytes = new byte[ID_LENGTH / 8]; // SecureRandom sr1 = new SecureRandom(); // sr1.nextBytes(bytes); // return new Key(bytes); // } // // public static Key build(String key) { // return new Key(new BigInteger(key,16)); // } // // /** // * Checks the distance between this and another Key // * // * @param nid // * // * @return The distance of this Key from the given Key // */ // public Key xor(Key nid) // { // return new Key(nid.getKey().xor(this.key)); // } // // /** // * Generates a Key that is some distance away from this Key // * // * @param distance in number of bits // * // * @return Key The newly generated Key // */ // public Key generateNodeIdByDistance(int distance) // { // byte[] result = new byte[ID_LENGTH / 8]; // // /* Since distance = ID_LENGTH - prefixLength, we need to fill that amount with 0's */ // int numByteZeroes = (ID_LENGTH - distance) / 8; // int numBitZeroes = 8 - (distance % 8); // // /* Filling byte zeroes */ // for (int i = 0; i < numByteZeroes; i++) // { // result[i] = 0; // } // // /* Filling bit zeroes */ // BitSet bits = new BitSet(8); // bits.set(0, 8); // // for (int i = 0; i < numBitZeroes; i++) // { // /* Shift 1 zero into the start of the value */ // bits.clear(i); // } // bits.flip(0, 8); // Flip the bits since they're in reverse order // result[numByteZeroes] = (byte) bits.toByteArray()[0]; // // /* Set the remaining bytes to Maximum value */ // for (int i = numByteZeroes + 1; i < result.length; i++) // { // result[i] = Byte.MAX_VALUE; // } // // return this.xor(new Key(result)); // } // // /** // * Counts the number of leading 0's in this Key // * // * @return Integer The number of leading 0's // */ // public int getFirstSetBitIndex() // { // int prefixLength = 0; // // for (byte b : this.key.toByteArray()) // { // if (b == 0) // { // prefixLength += 8; // } // else // { // /* If the byte is not 0, we need to count how many MSBs are 0 */ // int count = 0; // for (int i = 7; i >= 0; i--) // { // boolean a = (b & (1 << i)) == 0; // if (a) // { // count++; // } // else // { // break; // Reset the count if we encounter a non-zero number // } // } // // /* Add the count of MSB 0s to the prefix length */ // prefixLength += count; // // /* Break here since we've now covered the MSB 0s */ // break; // } // } // return prefixLength; // } // // @Override // public String toString() // { // return this.key.toString(16); // } // // // /** // * Gets the distance from this Key to another Key // * // * @param to // * // * @return Integer The distance // */ // public int getDistance(Key to) // { // /** // * Compute the xor of this and to // * Get the index i of the first set bit of the xor returned Key // * The distance between them is ID_LENGTH - i // */ // return ID_LENGTH - this.xor(to).getFirstSetBitIndex(); // } // } // Path: src/main/java/de/cgrotz/kademlia/Configuration.java import de.cgrotz.kademlia.config.Listener; import de.cgrotz.kademlia.node.Key; import lombok.Builder; import lombok.Data; import lombok.Singular; import java.util.List; package de.cgrotz.kademlia; /** * Created by Christoph on 28.09.2016. */ @Data @Builder public class Configuration { private final Key nodeId; private final long getTimeoutMs; private final long networkTimeoutMs; private final int kValue; @Singular
private final List<Listener> listeners;
cgrotz/kademlia
src/main/java/de/cgrotz/kademlia/protocol/ListenerMessageTypeAdapter.java
// Path: src/main/java/de/cgrotz/kademlia/config/Listener.java // @Data // @Builder // public class Listener { // private ListenerType type; // // public static Listener fromUrl(String url) { // if(url.startsWith(ListenerType.UDP.prefix())) { // return UdpListener.from(url); // } // else { // throw new UnknownListenerType(url); // } // } // } // // Path: src/main/java/de/cgrotz/kademlia/config/ListenerType.java // public enum ListenerType { // UDP("udp", UdpListener.class); // // private final String prefix; // private final Class listenerConfigClass; // // ListenerType(String prefix, Class<UdpListener> listenerConfigClass) { // this.prefix = prefix; // this.listenerConfigClass = listenerConfigClass; // } // // public String prefix() { // return prefix; // } // // public Class getListenerConfigClass() { // return listenerConfigClass; // } // }
import com.google.gson.*; import de.cgrotz.kademlia.config.Listener; import de.cgrotz.kademlia.config.ListenerType; import java.lang.reflect.Type;
package de.cgrotz.kademlia.protocol; /** * Created by christoph on 15.01.17. */ public class ListenerMessageTypeAdapter implements JsonDeserializer<Listener>, JsonSerializer<Listener> { private static final String CLASSNAME = "type"; @Override public Listener deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject jsonObject = json.getAsJsonObject(); JsonPrimitive prim = (JsonPrimitive) jsonObject.get(CLASSNAME); String typeName = prim.getAsString();
// Path: src/main/java/de/cgrotz/kademlia/config/Listener.java // @Data // @Builder // public class Listener { // private ListenerType type; // // public static Listener fromUrl(String url) { // if(url.startsWith(ListenerType.UDP.prefix())) { // return UdpListener.from(url); // } // else { // throw new UnknownListenerType(url); // } // } // } // // Path: src/main/java/de/cgrotz/kademlia/config/ListenerType.java // public enum ListenerType { // UDP("udp", UdpListener.class); // // private final String prefix; // private final Class listenerConfigClass; // // ListenerType(String prefix, Class<UdpListener> listenerConfigClass) { // this.prefix = prefix; // this.listenerConfigClass = listenerConfigClass; // } // // public String prefix() { // return prefix; // } // // public Class getListenerConfigClass() { // return listenerConfigClass; // } // } // Path: src/main/java/de/cgrotz/kademlia/protocol/ListenerMessageTypeAdapter.java import com.google.gson.*; import de.cgrotz.kademlia.config.Listener; import de.cgrotz.kademlia.config.ListenerType; import java.lang.reflect.Type; package de.cgrotz.kademlia.protocol; /** * Created by christoph on 15.01.17. */ public class ListenerMessageTypeAdapter implements JsonDeserializer<Listener>, JsonSerializer<Listener> { private static final String CLASSNAME = "type"; @Override public Listener deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject jsonObject = json.getAsJsonObject(); JsonPrimitive prim = (JsonPrimitive) jsonObject.get(CLASSNAME); String typeName = prim.getAsString();
return context.deserialize(jsonObject, ListenerType.valueOf(typeName.toUpperCase()).getListenerConfigClass());
cgrotz/kademlia
src/main/java/de/cgrotz/kademlia/protocol/Pong.java
// Path: src/main/java/de/cgrotz/kademlia/node/Key.java // @Data // @EqualsAndHashCode(of = "key") // public class Key { // public final static int ID_LENGTH = 160; // // private BigInteger key; // // public Key(byte[] result) { // if(result.length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = new BigInteger(result); // } // // public Key(BigInteger key) { // if( key.toByteArray().length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = key; // } // // public Key(int id) { // this.key = BigInteger.valueOf(id); // } // // public static Key random() { // byte[] bytes = new byte[ID_LENGTH / 8]; // SecureRandom sr1 = new SecureRandom(); // sr1.nextBytes(bytes); // return new Key(bytes); // } // // public static Key build(String key) { // return new Key(new BigInteger(key,16)); // } // // /** // * Checks the distance between this and another Key // * // * @param nid // * // * @return The distance of this Key from the given Key // */ // public Key xor(Key nid) // { // return new Key(nid.getKey().xor(this.key)); // } // // /** // * Generates a Key that is some distance away from this Key // * // * @param distance in number of bits // * // * @return Key The newly generated Key // */ // public Key generateNodeIdByDistance(int distance) // { // byte[] result = new byte[ID_LENGTH / 8]; // // /* Since distance = ID_LENGTH - prefixLength, we need to fill that amount with 0's */ // int numByteZeroes = (ID_LENGTH - distance) / 8; // int numBitZeroes = 8 - (distance % 8); // // /* Filling byte zeroes */ // for (int i = 0; i < numByteZeroes; i++) // { // result[i] = 0; // } // // /* Filling bit zeroes */ // BitSet bits = new BitSet(8); // bits.set(0, 8); // // for (int i = 0; i < numBitZeroes; i++) // { // /* Shift 1 zero into the start of the value */ // bits.clear(i); // } // bits.flip(0, 8); // Flip the bits since they're in reverse order // result[numByteZeroes] = (byte) bits.toByteArray()[0]; // // /* Set the remaining bytes to Maximum value */ // for (int i = numByteZeroes + 1; i < result.length; i++) // { // result[i] = Byte.MAX_VALUE; // } // // return this.xor(new Key(result)); // } // // /** // * Counts the number of leading 0's in this Key // * // * @return Integer The number of leading 0's // */ // public int getFirstSetBitIndex() // { // int prefixLength = 0; // // for (byte b : this.key.toByteArray()) // { // if (b == 0) // { // prefixLength += 8; // } // else // { // /* If the byte is not 0, we need to count how many MSBs are 0 */ // int count = 0; // for (int i = 7; i >= 0; i--) // { // boolean a = (b & (1 << i)) == 0; // if (a) // { // count++; // } // else // { // break; // Reset the count if we encounter a non-zero number // } // } // // /* Add the count of MSB 0s to the prefix length */ // prefixLength += count; // // /* Break here since we've now covered the MSB 0s */ // break; // } // } // return prefixLength; // } // // @Override // public String toString() // { // return this.key.toString(16); // } // // // /** // * Gets the distance from this Key to another Key // * // * @param to // * // * @return Integer The distance // */ // public int getDistance(Key to) // { // /** // * Compute the xor of this and to // * Get the index i of the first set bit of the xor returned Key // * The distance between them is ID_LENGTH - i // */ // return ID_LENGTH - this.xor(to).getFirstSetBitIndex(); // } // } // // Path: src/main/java/de/cgrotz/kademlia/node/Node.java // @Data // @EqualsAndHashCode(of={"id"}) // @Builder // public class Node implements Comparable<Node>{ // private Key id; // @Singular // private final List<Listener> advertisedListeners; // private long lastSeen = System.currentTimeMillis(); // // @Override // public int compareTo(Node o) { // if (this.equals(o)) // { // return 0; // } // // return (this.lastSeen > o.lastSeen) ? 1 : -1; // } // }
import de.cgrotz.kademlia.node.Key; import de.cgrotz.kademlia.node.Node; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString;
package de.cgrotz.kademlia.protocol; /** * * Response to Ping * * Created by Christoph on 22.09.2016. */ @Data @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class Pong extends Message {
// Path: src/main/java/de/cgrotz/kademlia/node/Key.java // @Data // @EqualsAndHashCode(of = "key") // public class Key { // public final static int ID_LENGTH = 160; // // private BigInteger key; // // public Key(byte[] result) { // if(result.length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = new BigInteger(result); // } // // public Key(BigInteger key) { // if( key.toByteArray().length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = key; // } // // public Key(int id) { // this.key = BigInteger.valueOf(id); // } // // public static Key random() { // byte[] bytes = new byte[ID_LENGTH / 8]; // SecureRandom sr1 = new SecureRandom(); // sr1.nextBytes(bytes); // return new Key(bytes); // } // // public static Key build(String key) { // return new Key(new BigInteger(key,16)); // } // // /** // * Checks the distance between this and another Key // * // * @param nid // * // * @return The distance of this Key from the given Key // */ // public Key xor(Key nid) // { // return new Key(nid.getKey().xor(this.key)); // } // // /** // * Generates a Key that is some distance away from this Key // * // * @param distance in number of bits // * // * @return Key The newly generated Key // */ // public Key generateNodeIdByDistance(int distance) // { // byte[] result = new byte[ID_LENGTH / 8]; // // /* Since distance = ID_LENGTH - prefixLength, we need to fill that amount with 0's */ // int numByteZeroes = (ID_LENGTH - distance) / 8; // int numBitZeroes = 8 - (distance % 8); // // /* Filling byte zeroes */ // for (int i = 0; i < numByteZeroes; i++) // { // result[i] = 0; // } // // /* Filling bit zeroes */ // BitSet bits = new BitSet(8); // bits.set(0, 8); // // for (int i = 0; i < numBitZeroes; i++) // { // /* Shift 1 zero into the start of the value */ // bits.clear(i); // } // bits.flip(0, 8); // Flip the bits since they're in reverse order // result[numByteZeroes] = (byte) bits.toByteArray()[0]; // // /* Set the remaining bytes to Maximum value */ // for (int i = numByteZeroes + 1; i < result.length; i++) // { // result[i] = Byte.MAX_VALUE; // } // // return this.xor(new Key(result)); // } // // /** // * Counts the number of leading 0's in this Key // * // * @return Integer The number of leading 0's // */ // public int getFirstSetBitIndex() // { // int prefixLength = 0; // // for (byte b : this.key.toByteArray()) // { // if (b == 0) // { // prefixLength += 8; // } // else // { // /* If the byte is not 0, we need to count how many MSBs are 0 */ // int count = 0; // for (int i = 7; i >= 0; i--) // { // boolean a = (b & (1 << i)) == 0; // if (a) // { // count++; // } // else // { // break; // Reset the count if we encounter a non-zero number // } // } // // /* Add the count of MSB 0s to the prefix length */ // prefixLength += count; // // /* Break here since we've now covered the MSB 0s */ // break; // } // } // return prefixLength; // } // // @Override // public String toString() // { // return this.key.toString(16); // } // // // /** // * Gets the distance from this Key to another Key // * // * @param to // * // * @return Integer The distance // */ // public int getDistance(Key to) // { // /** // * Compute the xor of this and to // * Get the index i of the first set bit of the xor returned Key // * The distance between them is ID_LENGTH - i // */ // return ID_LENGTH - this.xor(to).getFirstSetBitIndex(); // } // } // // Path: src/main/java/de/cgrotz/kademlia/node/Node.java // @Data // @EqualsAndHashCode(of={"id"}) // @Builder // public class Node implements Comparable<Node>{ // private Key id; // @Singular // private final List<Listener> advertisedListeners; // private long lastSeen = System.currentTimeMillis(); // // @Override // public int compareTo(Node o) { // if (this.equals(o)) // { // return 0; // } // // return (this.lastSeen > o.lastSeen) ? 1 : -1; // } // } // Path: src/main/java/de/cgrotz/kademlia/protocol/Pong.java import de.cgrotz.kademlia.node.Key; import de.cgrotz.kademlia.node.Node; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; package de.cgrotz.kademlia.protocol; /** * * Response to Ping * * Created by Christoph on 22.09.2016. */ @Data @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class Pong extends Message {
public Pong(long seqId, Node origin) {
cgrotz/kademlia
src/main/java/de/cgrotz/kademlia/events/ReceivedMessageEvent.java
// Path: src/main/java/de/cgrotz/kademlia/protocol/Message.java // @Data // public abstract class Message { // private final MessageType type; // private final long seqId; // // private final Node origin; // }
import de.cgrotz.kademlia.protocol.Message; import lombok.Builder; import lombok.Data;
package de.cgrotz.kademlia.events; /** * Created by Christoph on 06.10.2016. */ @Data @Builder public class ReceivedMessageEvent extends Event {
// Path: src/main/java/de/cgrotz/kademlia/protocol/Message.java // @Data // public abstract class Message { // private final MessageType type; // private final long seqId; // // private final Node origin; // } // Path: src/main/java/de/cgrotz/kademlia/events/ReceivedMessageEvent.java import de.cgrotz.kademlia.protocol.Message; import lombok.Builder; import lombok.Data; package de.cgrotz.kademlia.events; /** * Created by Christoph on 06.10.2016. */ @Data @Builder public class ReceivedMessageEvent extends Event {
private Message message;
cgrotz/kademlia
src/main/java/de/cgrotz/kademlia/protocol/Codec.java
// Path: src/main/java/de/cgrotz/kademlia/config/Listener.java // @Data // @Builder // public class Listener { // private ListenerType type; // // public static Listener fromUrl(String url) { // if(url.startsWith(ListenerType.UDP.prefix())) { // return UdpListener.from(url); // } // else { // throw new UnknownListenerType(url); // } // } // }
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import de.cgrotz.kademlia.config.Listener; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.Base64;
package de.cgrotz.kademlia.protocol; /** * Created by Christoph on 21.09.2016. */ public class Codec { private final Base64.Decoder decoder = Base64.getDecoder(); private final Base64.Encoder encoder = Base64.getEncoder(); private final Gson gson = new GsonBuilder() .registerTypeAdapter(Message.class, new MessageTypeAdapter())
// Path: src/main/java/de/cgrotz/kademlia/config/Listener.java // @Data // @Builder // public class Listener { // private ListenerType type; // // public static Listener fromUrl(String url) { // if(url.startsWith(ListenerType.UDP.prefix())) { // return UdpListener.from(url); // } // else { // throw new UnknownListenerType(url); // } // } // } // Path: src/main/java/de/cgrotz/kademlia/protocol/Codec.java import com.google.gson.Gson; import com.google.gson.GsonBuilder; import de.cgrotz.kademlia.config.Listener; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.Base64; package de.cgrotz.kademlia.protocol; /** * Created by Christoph on 21.09.2016. */ public class Codec { private final Base64.Decoder decoder = Base64.getDecoder(); private final Base64.Encoder encoder = Base64.getEncoder(); private final Gson gson = new GsonBuilder() .registerTypeAdapter(Message.class, new MessageTypeAdapter())
.registerTypeAdapter(Listener.class, new ListenerMessageTypeAdapter())
cgrotz/kademlia
src/main/java/de/cgrotz/kademlia/protocol/ValueReply.java
// Path: src/main/java/de/cgrotz/kademlia/node/Key.java // @Data // @EqualsAndHashCode(of = "key") // public class Key { // public final static int ID_LENGTH = 160; // // private BigInteger key; // // public Key(byte[] result) { // if(result.length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = new BigInteger(result); // } // // public Key(BigInteger key) { // if( key.toByteArray().length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = key; // } // // public Key(int id) { // this.key = BigInteger.valueOf(id); // } // // public static Key random() { // byte[] bytes = new byte[ID_LENGTH / 8]; // SecureRandom sr1 = new SecureRandom(); // sr1.nextBytes(bytes); // return new Key(bytes); // } // // public static Key build(String key) { // return new Key(new BigInteger(key,16)); // } // // /** // * Checks the distance between this and another Key // * // * @param nid // * // * @return The distance of this Key from the given Key // */ // public Key xor(Key nid) // { // return new Key(nid.getKey().xor(this.key)); // } // // /** // * Generates a Key that is some distance away from this Key // * // * @param distance in number of bits // * // * @return Key The newly generated Key // */ // public Key generateNodeIdByDistance(int distance) // { // byte[] result = new byte[ID_LENGTH / 8]; // // /* Since distance = ID_LENGTH - prefixLength, we need to fill that amount with 0's */ // int numByteZeroes = (ID_LENGTH - distance) / 8; // int numBitZeroes = 8 - (distance % 8); // // /* Filling byte zeroes */ // for (int i = 0; i < numByteZeroes; i++) // { // result[i] = 0; // } // // /* Filling bit zeroes */ // BitSet bits = new BitSet(8); // bits.set(0, 8); // // for (int i = 0; i < numBitZeroes; i++) // { // /* Shift 1 zero into the start of the value */ // bits.clear(i); // } // bits.flip(0, 8); // Flip the bits since they're in reverse order // result[numByteZeroes] = (byte) bits.toByteArray()[0]; // // /* Set the remaining bytes to Maximum value */ // for (int i = numByteZeroes + 1; i < result.length; i++) // { // result[i] = Byte.MAX_VALUE; // } // // return this.xor(new Key(result)); // } // // /** // * Counts the number of leading 0's in this Key // * // * @return Integer The number of leading 0's // */ // public int getFirstSetBitIndex() // { // int prefixLength = 0; // // for (byte b : this.key.toByteArray()) // { // if (b == 0) // { // prefixLength += 8; // } // else // { // /* If the byte is not 0, we need to count how many MSBs are 0 */ // int count = 0; // for (int i = 7; i >= 0; i--) // { // boolean a = (b & (1 << i)) == 0; // if (a) // { // count++; // } // else // { // break; // Reset the count if we encounter a non-zero number // } // } // // /* Add the count of MSB 0s to the prefix length */ // prefixLength += count; // // /* Break here since we've now covered the MSB 0s */ // break; // } // } // return prefixLength; // } // // @Override // public String toString() // { // return this.key.toString(16); // } // // // /** // * Gets the distance from this Key to another Key // * // * @param to // * // * @return Integer The distance // */ // public int getDistance(Key to) // { // /** // * Compute the xor of this and to // * Get the index i of the first set bit of the xor returned Key // * The distance between them is ID_LENGTH - i // */ // return ID_LENGTH - this.xor(to).getFirstSetBitIndex(); // } // } // // Path: src/main/java/de/cgrotz/kademlia/node/Node.java // @Data // @EqualsAndHashCode(of={"id"}) // @Builder // public class Node implements Comparable<Node>{ // private Key id; // @Singular // private final List<Listener> advertisedListeners; // private long lastSeen = System.currentTimeMillis(); // // @Override // public int compareTo(Node o) { // if (this.equals(o)) // { // return 0; // } // // return (this.lastSeen > o.lastSeen) ? 1 : -1; // } // }
import de.cgrotz.kademlia.node.Key; import de.cgrotz.kademlia.node.Node; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString;
package de.cgrotz.kademlia.protocol; /** * * Same as FIND_NODE, but if the recipient of the request has the requested key in its store, it will return the corresponding value. * * Created by Christoph on 22.09.2016. */ @Data @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class ValueReply extends Message { private final String value;
// Path: src/main/java/de/cgrotz/kademlia/node/Key.java // @Data // @EqualsAndHashCode(of = "key") // public class Key { // public final static int ID_LENGTH = 160; // // private BigInteger key; // // public Key(byte[] result) { // if(result.length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = new BigInteger(result); // } // // public Key(BigInteger key) { // if( key.toByteArray().length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = key; // } // // public Key(int id) { // this.key = BigInteger.valueOf(id); // } // // public static Key random() { // byte[] bytes = new byte[ID_LENGTH / 8]; // SecureRandom sr1 = new SecureRandom(); // sr1.nextBytes(bytes); // return new Key(bytes); // } // // public static Key build(String key) { // return new Key(new BigInteger(key,16)); // } // // /** // * Checks the distance between this and another Key // * // * @param nid // * // * @return The distance of this Key from the given Key // */ // public Key xor(Key nid) // { // return new Key(nid.getKey().xor(this.key)); // } // // /** // * Generates a Key that is some distance away from this Key // * // * @param distance in number of bits // * // * @return Key The newly generated Key // */ // public Key generateNodeIdByDistance(int distance) // { // byte[] result = new byte[ID_LENGTH / 8]; // // /* Since distance = ID_LENGTH - prefixLength, we need to fill that amount with 0's */ // int numByteZeroes = (ID_LENGTH - distance) / 8; // int numBitZeroes = 8 - (distance % 8); // // /* Filling byte zeroes */ // for (int i = 0; i < numByteZeroes; i++) // { // result[i] = 0; // } // // /* Filling bit zeroes */ // BitSet bits = new BitSet(8); // bits.set(0, 8); // // for (int i = 0; i < numBitZeroes; i++) // { // /* Shift 1 zero into the start of the value */ // bits.clear(i); // } // bits.flip(0, 8); // Flip the bits since they're in reverse order // result[numByteZeroes] = (byte) bits.toByteArray()[0]; // // /* Set the remaining bytes to Maximum value */ // for (int i = numByteZeroes + 1; i < result.length; i++) // { // result[i] = Byte.MAX_VALUE; // } // // return this.xor(new Key(result)); // } // // /** // * Counts the number of leading 0's in this Key // * // * @return Integer The number of leading 0's // */ // public int getFirstSetBitIndex() // { // int prefixLength = 0; // // for (byte b : this.key.toByteArray()) // { // if (b == 0) // { // prefixLength += 8; // } // else // { // /* If the byte is not 0, we need to count how many MSBs are 0 */ // int count = 0; // for (int i = 7; i >= 0; i--) // { // boolean a = (b & (1 << i)) == 0; // if (a) // { // count++; // } // else // { // break; // Reset the count if we encounter a non-zero number // } // } // // /* Add the count of MSB 0s to the prefix length */ // prefixLength += count; // // /* Break here since we've now covered the MSB 0s */ // break; // } // } // return prefixLength; // } // // @Override // public String toString() // { // return this.key.toString(16); // } // // // /** // * Gets the distance from this Key to another Key // * // * @param to // * // * @return Integer The distance // */ // public int getDistance(Key to) // { // /** // * Compute the xor of this and to // * Get the index i of the first set bit of the xor returned Key // * The distance between them is ID_LENGTH - i // */ // return ID_LENGTH - this.xor(to).getFirstSetBitIndex(); // } // } // // Path: src/main/java/de/cgrotz/kademlia/node/Node.java // @Data // @EqualsAndHashCode(of={"id"}) // @Builder // public class Node implements Comparable<Node>{ // private Key id; // @Singular // private final List<Listener> advertisedListeners; // private long lastSeen = System.currentTimeMillis(); // // @Override // public int compareTo(Node o) { // if (this.equals(o)) // { // return 0; // } // // return (this.lastSeen > o.lastSeen) ? 1 : -1; // } // } // Path: src/main/java/de/cgrotz/kademlia/protocol/ValueReply.java import de.cgrotz.kademlia.node.Key; import de.cgrotz.kademlia.node.Node; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; package de.cgrotz.kademlia.protocol; /** * * Same as FIND_NODE, but if the recipient of the request has the requested key in its store, it will return the corresponding value. * * Created by Christoph on 22.09.2016. */ @Data @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class ValueReply extends Message { private final String value;
private final Key key;
cgrotz/kademlia
src/main/java/de/cgrotz/kademlia/protocol/ValueReply.java
// Path: src/main/java/de/cgrotz/kademlia/node/Key.java // @Data // @EqualsAndHashCode(of = "key") // public class Key { // public final static int ID_LENGTH = 160; // // private BigInteger key; // // public Key(byte[] result) { // if(result.length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = new BigInteger(result); // } // // public Key(BigInteger key) { // if( key.toByteArray().length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = key; // } // // public Key(int id) { // this.key = BigInteger.valueOf(id); // } // // public static Key random() { // byte[] bytes = new byte[ID_LENGTH / 8]; // SecureRandom sr1 = new SecureRandom(); // sr1.nextBytes(bytes); // return new Key(bytes); // } // // public static Key build(String key) { // return new Key(new BigInteger(key,16)); // } // // /** // * Checks the distance between this and another Key // * // * @param nid // * // * @return The distance of this Key from the given Key // */ // public Key xor(Key nid) // { // return new Key(nid.getKey().xor(this.key)); // } // // /** // * Generates a Key that is some distance away from this Key // * // * @param distance in number of bits // * // * @return Key The newly generated Key // */ // public Key generateNodeIdByDistance(int distance) // { // byte[] result = new byte[ID_LENGTH / 8]; // // /* Since distance = ID_LENGTH - prefixLength, we need to fill that amount with 0's */ // int numByteZeroes = (ID_LENGTH - distance) / 8; // int numBitZeroes = 8 - (distance % 8); // // /* Filling byte zeroes */ // for (int i = 0; i < numByteZeroes; i++) // { // result[i] = 0; // } // // /* Filling bit zeroes */ // BitSet bits = new BitSet(8); // bits.set(0, 8); // // for (int i = 0; i < numBitZeroes; i++) // { // /* Shift 1 zero into the start of the value */ // bits.clear(i); // } // bits.flip(0, 8); // Flip the bits since they're in reverse order // result[numByteZeroes] = (byte) bits.toByteArray()[0]; // // /* Set the remaining bytes to Maximum value */ // for (int i = numByteZeroes + 1; i < result.length; i++) // { // result[i] = Byte.MAX_VALUE; // } // // return this.xor(new Key(result)); // } // // /** // * Counts the number of leading 0's in this Key // * // * @return Integer The number of leading 0's // */ // public int getFirstSetBitIndex() // { // int prefixLength = 0; // // for (byte b : this.key.toByteArray()) // { // if (b == 0) // { // prefixLength += 8; // } // else // { // /* If the byte is not 0, we need to count how many MSBs are 0 */ // int count = 0; // for (int i = 7; i >= 0; i--) // { // boolean a = (b & (1 << i)) == 0; // if (a) // { // count++; // } // else // { // break; // Reset the count if we encounter a non-zero number // } // } // // /* Add the count of MSB 0s to the prefix length */ // prefixLength += count; // // /* Break here since we've now covered the MSB 0s */ // break; // } // } // return prefixLength; // } // // @Override // public String toString() // { // return this.key.toString(16); // } // // // /** // * Gets the distance from this Key to another Key // * // * @param to // * // * @return Integer The distance // */ // public int getDistance(Key to) // { // /** // * Compute the xor of this and to // * Get the index i of the first set bit of the xor returned Key // * The distance between them is ID_LENGTH - i // */ // return ID_LENGTH - this.xor(to).getFirstSetBitIndex(); // } // } // // Path: src/main/java/de/cgrotz/kademlia/node/Node.java // @Data // @EqualsAndHashCode(of={"id"}) // @Builder // public class Node implements Comparable<Node>{ // private Key id; // @Singular // private final List<Listener> advertisedListeners; // private long lastSeen = System.currentTimeMillis(); // // @Override // public int compareTo(Node o) { // if (this.equals(o)) // { // return 0; // } // // return (this.lastSeen > o.lastSeen) ? 1 : -1; // } // }
import de.cgrotz.kademlia.node.Key; import de.cgrotz.kademlia.node.Node; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString;
package de.cgrotz.kademlia.protocol; /** * * Same as FIND_NODE, but if the recipient of the request has the requested key in its store, it will return the corresponding value. * * Created by Christoph on 22.09.2016. */ @Data @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class ValueReply extends Message { private final String value; private final Key key;
// Path: src/main/java/de/cgrotz/kademlia/node/Key.java // @Data // @EqualsAndHashCode(of = "key") // public class Key { // public final static int ID_LENGTH = 160; // // private BigInteger key; // // public Key(byte[] result) { // if(result.length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = new BigInteger(result); // } // // public Key(BigInteger key) { // if( key.toByteArray().length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = key; // } // // public Key(int id) { // this.key = BigInteger.valueOf(id); // } // // public static Key random() { // byte[] bytes = new byte[ID_LENGTH / 8]; // SecureRandom sr1 = new SecureRandom(); // sr1.nextBytes(bytes); // return new Key(bytes); // } // // public static Key build(String key) { // return new Key(new BigInteger(key,16)); // } // // /** // * Checks the distance between this and another Key // * // * @param nid // * // * @return The distance of this Key from the given Key // */ // public Key xor(Key nid) // { // return new Key(nid.getKey().xor(this.key)); // } // // /** // * Generates a Key that is some distance away from this Key // * // * @param distance in number of bits // * // * @return Key The newly generated Key // */ // public Key generateNodeIdByDistance(int distance) // { // byte[] result = new byte[ID_LENGTH / 8]; // // /* Since distance = ID_LENGTH - prefixLength, we need to fill that amount with 0's */ // int numByteZeroes = (ID_LENGTH - distance) / 8; // int numBitZeroes = 8 - (distance % 8); // // /* Filling byte zeroes */ // for (int i = 0; i < numByteZeroes; i++) // { // result[i] = 0; // } // // /* Filling bit zeroes */ // BitSet bits = new BitSet(8); // bits.set(0, 8); // // for (int i = 0; i < numBitZeroes; i++) // { // /* Shift 1 zero into the start of the value */ // bits.clear(i); // } // bits.flip(0, 8); // Flip the bits since they're in reverse order // result[numByteZeroes] = (byte) bits.toByteArray()[0]; // // /* Set the remaining bytes to Maximum value */ // for (int i = numByteZeroes + 1; i < result.length; i++) // { // result[i] = Byte.MAX_VALUE; // } // // return this.xor(new Key(result)); // } // // /** // * Counts the number of leading 0's in this Key // * // * @return Integer The number of leading 0's // */ // public int getFirstSetBitIndex() // { // int prefixLength = 0; // // for (byte b : this.key.toByteArray()) // { // if (b == 0) // { // prefixLength += 8; // } // else // { // /* If the byte is not 0, we need to count how many MSBs are 0 */ // int count = 0; // for (int i = 7; i >= 0; i--) // { // boolean a = (b & (1 << i)) == 0; // if (a) // { // count++; // } // else // { // break; // Reset the count if we encounter a non-zero number // } // } // // /* Add the count of MSB 0s to the prefix length */ // prefixLength += count; // // /* Break here since we've now covered the MSB 0s */ // break; // } // } // return prefixLength; // } // // @Override // public String toString() // { // return this.key.toString(16); // } // // // /** // * Gets the distance from this Key to another Key // * // * @param to // * // * @return Integer The distance // */ // public int getDistance(Key to) // { // /** // * Compute the xor of this and to // * Get the index i of the first set bit of the xor returned Key // * The distance between them is ID_LENGTH - i // */ // return ID_LENGTH - this.xor(to).getFirstSetBitIndex(); // } // } // // Path: src/main/java/de/cgrotz/kademlia/node/Node.java // @Data // @EqualsAndHashCode(of={"id"}) // @Builder // public class Node implements Comparable<Node>{ // private Key id; // @Singular // private final List<Listener> advertisedListeners; // private long lastSeen = System.currentTimeMillis(); // // @Override // public int compareTo(Node o) { // if (this.equals(o)) // { // return 0; // } // // return (this.lastSeen > o.lastSeen) ? 1 : -1; // } // } // Path: src/main/java/de/cgrotz/kademlia/protocol/ValueReply.java import de.cgrotz.kademlia.node.Key; import de.cgrotz.kademlia.node.Node; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; package de.cgrotz.kademlia.protocol; /** * * Same as FIND_NODE, but if the recipient of the request has the requested key in its store, it will return the corresponding value. * * Created by Christoph on 22.09.2016. */ @Data @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class ValueReply extends Message { private final String value; private final Key key;
public ValueReply(long seqId, Node origin, Key key, String value) {
cgrotz/kademlia
src/main/java/de/cgrotz/kademlia/protocol/StoreReply.java
// Path: src/main/java/de/cgrotz/kademlia/node/Node.java // @Data // @EqualsAndHashCode(of={"id"}) // @Builder // public class Node implements Comparable<Node>{ // private Key id; // @Singular // private final List<Listener> advertisedListeners; // private long lastSeen = System.currentTimeMillis(); // // @Override // public int compareTo(Node o) { // if (this.equals(o)) // { // return 0; // } // // return (this.lastSeen > o.lastSeen) ? 1 : -1; // } // }
import de.cgrotz.kademlia.node.Node; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString;
package de.cgrotz.kademlia.protocol; /** * * Response to Ping * * Created by Christoph on 22.09.2016. */ @Data @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class StoreReply extends Message {
// Path: src/main/java/de/cgrotz/kademlia/node/Node.java // @Data // @EqualsAndHashCode(of={"id"}) // @Builder // public class Node implements Comparable<Node>{ // private Key id; // @Singular // private final List<Listener> advertisedListeners; // private long lastSeen = System.currentTimeMillis(); // // @Override // public int compareTo(Node o) { // if (this.equals(o)) // { // return 0; // } // // return (this.lastSeen > o.lastSeen) ? 1 : -1; // } // } // Path: src/main/java/de/cgrotz/kademlia/protocol/StoreReply.java import de.cgrotz.kademlia.node.Node; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; package de.cgrotz.kademlia.protocol; /** * * Response to Ping * * Created by Christoph on 22.09.2016. */ @Data @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class StoreReply extends Message {
public StoreReply(long seqId, Node origin) {
cgrotz/kademlia
src/main/java/de/cgrotz/kademlia/node/Node.java
// Path: src/main/java/de/cgrotz/kademlia/config/Listener.java // @Data // @Builder // public class Listener { // private ListenerType type; // // public static Listener fromUrl(String url) { // if(url.startsWith(ListenerType.UDP.prefix())) { // return UdpListener.from(url); // } // else { // throw new UnknownListenerType(url); // } // } // }
import de.cgrotz.kademlia.config.Listener; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.Singular; import java.util.List;
package de.cgrotz.kademlia.node; /** * Created by Christoph on 21.09.2016. */ @Data @EqualsAndHashCode(of={"id"}) @Builder public class Node implements Comparable<Node>{ private Key id; @Singular
// Path: src/main/java/de/cgrotz/kademlia/config/Listener.java // @Data // @Builder // public class Listener { // private ListenerType type; // // public static Listener fromUrl(String url) { // if(url.startsWith(ListenerType.UDP.prefix())) { // return UdpListener.from(url); // } // else { // throw new UnknownListenerType(url); // } // } // } // Path: src/main/java/de/cgrotz/kademlia/node/Node.java import de.cgrotz.kademlia.config.Listener; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.Singular; import java.util.List; package de.cgrotz.kademlia.node; /** * Created by Christoph on 21.09.2016. */ @Data @EqualsAndHashCode(of={"id"}) @Builder public class Node implements Comparable<Node>{ private Key id; @Singular
private final List<Listener> advertisedListeners;
cgrotz/kademlia
src/main/java/de/cgrotz/kademlia/config/Listener.java
// Path: src/main/java/de/cgrotz/kademlia/exception/UnknownListenerType.java // public class UnknownListenerType extends RuntimeException{ // public UnknownListenerType(String url) { // super("Can't parse url="+url); // // } // }
import de.cgrotz.kademlia.exception.UnknownListenerType; import lombok.Builder; import lombok.Data;
package de.cgrotz.kademlia.config; /** * Created by Christoph on 30.09.2016. */ @Data @Builder public class Listener { private ListenerType type; public static Listener fromUrl(String url) { if(url.startsWith(ListenerType.UDP.prefix())) { return UdpListener.from(url); } else {
// Path: src/main/java/de/cgrotz/kademlia/exception/UnknownListenerType.java // public class UnknownListenerType extends RuntimeException{ // public UnknownListenerType(String url) { // super("Can't parse url="+url); // // } // } // Path: src/main/java/de/cgrotz/kademlia/config/Listener.java import de.cgrotz.kademlia.exception.UnknownListenerType; import lombok.Builder; import lombok.Data; package de.cgrotz.kademlia.config; /** * Created by Christoph on 30.09.2016. */ @Data @Builder public class Listener { private ListenerType type; public static Listener fromUrl(String url) { if(url.startsWith(ListenerType.UDP.prefix())) { return UdpListener.from(url); } else {
throw new UnknownListenerType(url);
cgrotz/kademlia
src/main/java/de/cgrotz/kademlia/protocol/Message.java
// Path: src/main/java/de/cgrotz/kademlia/node/Node.java // @Data // @EqualsAndHashCode(of={"id"}) // @Builder // public class Node implements Comparable<Node>{ // private Key id; // @Singular // private final List<Listener> advertisedListeners; // private long lastSeen = System.currentTimeMillis(); // // @Override // public int compareTo(Node o) { // if (this.equals(o)) // { // return 0; // } // // return (this.lastSeen > o.lastSeen) ? 1 : -1; // } // }
import de.cgrotz.kademlia.node.Node; import lombok.Data;
package de.cgrotz.kademlia.protocol; /** * Created by Christoph on 21.09.2016. */ @Data public abstract class Message { private final MessageType type; private final long seqId;
// Path: src/main/java/de/cgrotz/kademlia/node/Node.java // @Data // @EqualsAndHashCode(of={"id"}) // @Builder // public class Node implements Comparable<Node>{ // private Key id; // @Singular // private final List<Listener> advertisedListeners; // private long lastSeen = System.currentTimeMillis(); // // @Override // public int compareTo(Node o) { // if (this.equals(o)) // { // return 0; // } // // return (this.lastSeen > o.lastSeen) ? 1 : -1; // } // } // Path: src/main/java/de/cgrotz/kademlia/protocol/Message.java import de.cgrotz.kademlia.node.Node; import lombok.Data; package de.cgrotz.kademlia.protocol; /** * Created by Christoph on 21.09.2016. */ @Data public abstract class Message { private final MessageType type; private final long seqId;
private final Node origin;
cgrotz/kademlia
src/main/java/de/cgrotz/kademlia/server/KademliaServer.java
// Path: src/main/java/de/cgrotz/kademlia/events/Event.java // public abstract class Event { // // } // // Path: src/main/java/de/cgrotz/kademlia/node/Node.java // @Data // @EqualsAndHashCode(of={"id"}) // @Builder // public class Node implements Comparable<Node>{ // private Key id; // @Singular // private final List<Listener> advertisedListeners; // private long lastSeen = System.currentTimeMillis(); // // @Override // public int compareTo(Node o) { // if (this.equals(o)) // { // return 0; // } // // return (this.lastSeen > o.lastSeen) ? 1 : -1; // } // } // // Path: src/main/java/de/cgrotz/kademlia/routing/RoutingTable.java // @ToString // @EqualsAndHashCode // public class RoutingTable { // // private final Key localNodeId; // // private final Bucket[] buckets; // // public RoutingTable(int k, Key localNodeId, KademliaClient client) { // this.localNodeId = localNodeId; // buckets = new Bucket[Key.ID_LENGTH]; // for (int i = 0; i < Key.ID_LENGTH; i++) // { // buckets[i] = new Bucket(client, k, i); // } // } // // /** // * Compute the bucket ID in which a given node should be placed; the bucketId is computed based on how far the node is away from the Local Node. // * // * @param nid The Key for which we want to find which bucket it belong to // * // * @return Integer The bucket ID in which the given node should be placed. // */ // public final int getBucketId(Key nid) // { // int bId = this.localNodeId.getDistance(nid) - 1; // // /* If we are trying to insert a node into it's own routing table, then the bucket ID will be -1, so let's just keep it in bucket 0 */ // return bId < 0 ? 0 : bId; // } // // public void addNode(Node node) { // if(!node.getId().equals(localNodeId)) { // buckets[getBucketId(node.getId())].addNode(node); // } // else { // // System.out.println("Routing table of node="+nodeId+" can't contain itself. (localNodeId="+localNodeId+")"); // } // } // // public Bucket[] getBuckets() { // return buckets; // } // // public Stream<Bucket> getBucketStream() { // return Arrays.stream(buckets); // } // // public List<Node> findClosest(Key lookupId, int numberOfRequiredNodes) { // return getBucketStream().flatMap(bucket -> bucket.getNodes().stream()) // .sorted((node1,node2) -> node1.getId().getKey().xor(lookupId.getKey()).abs() // .compareTo( node2.getId().getKey().xor(lookupId.getKey()).abs() )) // .limit(numberOfRequiredNodes).collect(Collectors.toList()); // } // // public void retireNode(Node node) { // buckets[getBucketId(node.getId())].retireNode(node); // } // } // // Path: src/main/java/de/cgrotz/kademlia/storage/LocalStorage.java // public interface LocalStorage { // void put(Key key, Value value); // // Value get(Key key); // // boolean contains(Key key); // // List<Key> getKeysBeforeTimestamp(long timestamp); // // default void updateLastPublished(Key key, long timestamp) { // Value node = get(key); // node.setLastPublished(timestamp); // put(key, node); // } // }
import de.cgrotz.kademlia.events.Event; import de.cgrotz.kademlia.node.Node; import de.cgrotz.kademlia.routing.RoutingTable; import de.cgrotz.kademlia.storage.LocalStorage; import lombok.Data; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; import java.util.Arrays; import java.util.Map; import java.util.function.Consumer;
package de.cgrotz.kademlia.server; /** * Created by Christoph on 21.09.2016. */ @Data public class KademliaServer { private final Logger LOGGER;
// Path: src/main/java/de/cgrotz/kademlia/events/Event.java // public abstract class Event { // // } // // Path: src/main/java/de/cgrotz/kademlia/node/Node.java // @Data // @EqualsAndHashCode(of={"id"}) // @Builder // public class Node implements Comparable<Node>{ // private Key id; // @Singular // private final List<Listener> advertisedListeners; // private long lastSeen = System.currentTimeMillis(); // // @Override // public int compareTo(Node o) { // if (this.equals(o)) // { // return 0; // } // // return (this.lastSeen > o.lastSeen) ? 1 : -1; // } // } // // Path: src/main/java/de/cgrotz/kademlia/routing/RoutingTable.java // @ToString // @EqualsAndHashCode // public class RoutingTable { // // private final Key localNodeId; // // private final Bucket[] buckets; // // public RoutingTable(int k, Key localNodeId, KademliaClient client) { // this.localNodeId = localNodeId; // buckets = new Bucket[Key.ID_LENGTH]; // for (int i = 0; i < Key.ID_LENGTH; i++) // { // buckets[i] = new Bucket(client, k, i); // } // } // // /** // * Compute the bucket ID in which a given node should be placed; the bucketId is computed based on how far the node is away from the Local Node. // * // * @param nid The Key for which we want to find which bucket it belong to // * // * @return Integer The bucket ID in which the given node should be placed. // */ // public final int getBucketId(Key nid) // { // int bId = this.localNodeId.getDistance(nid) - 1; // // /* If we are trying to insert a node into it's own routing table, then the bucket ID will be -1, so let's just keep it in bucket 0 */ // return bId < 0 ? 0 : bId; // } // // public void addNode(Node node) { // if(!node.getId().equals(localNodeId)) { // buckets[getBucketId(node.getId())].addNode(node); // } // else { // // System.out.println("Routing table of node="+nodeId+" can't contain itself. (localNodeId="+localNodeId+")"); // } // } // // public Bucket[] getBuckets() { // return buckets; // } // // public Stream<Bucket> getBucketStream() { // return Arrays.stream(buckets); // } // // public List<Node> findClosest(Key lookupId, int numberOfRequiredNodes) { // return getBucketStream().flatMap(bucket -> bucket.getNodes().stream()) // .sorted((node1,node2) -> node1.getId().getKey().xor(lookupId.getKey()).abs() // .compareTo( node2.getId().getKey().xor(lookupId.getKey()).abs() )) // .limit(numberOfRequiredNodes).collect(Collectors.toList()); // } // // public void retireNode(Node node) { // buckets[getBucketId(node.getId())].retireNode(node); // } // } // // Path: src/main/java/de/cgrotz/kademlia/storage/LocalStorage.java // public interface LocalStorage { // void put(Key key, Value value); // // Value get(Key key); // // boolean contains(Key key); // // List<Key> getKeysBeforeTimestamp(long timestamp); // // default void updateLastPublished(Key key, long timestamp) { // Value node = get(key); // node.setLastPublished(timestamp); // put(key, node); // } // } // Path: src/main/java/de/cgrotz/kademlia/server/KademliaServer.java import de.cgrotz.kademlia.events.Event; import de.cgrotz.kademlia.node.Node; import de.cgrotz.kademlia.routing.RoutingTable; import de.cgrotz.kademlia.storage.LocalStorage; import lombok.Data; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; import java.util.Arrays; import java.util.Map; import java.util.function.Consumer; package de.cgrotz.kademlia.server; /** * Created by Christoph on 21.09.2016. */ @Data public class KademliaServer { private final Logger LOGGER;
private final RoutingTable routingTable;
cgrotz/kademlia
src/main/java/de/cgrotz/kademlia/server/KademliaServer.java
// Path: src/main/java/de/cgrotz/kademlia/events/Event.java // public abstract class Event { // // } // // Path: src/main/java/de/cgrotz/kademlia/node/Node.java // @Data // @EqualsAndHashCode(of={"id"}) // @Builder // public class Node implements Comparable<Node>{ // private Key id; // @Singular // private final List<Listener> advertisedListeners; // private long lastSeen = System.currentTimeMillis(); // // @Override // public int compareTo(Node o) { // if (this.equals(o)) // { // return 0; // } // // return (this.lastSeen > o.lastSeen) ? 1 : -1; // } // } // // Path: src/main/java/de/cgrotz/kademlia/routing/RoutingTable.java // @ToString // @EqualsAndHashCode // public class RoutingTable { // // private final Key localNodeId; // // private final Bucket[] buckets; // // public RoutingTable(int k, Key localNodeId, KademliaClient client) { // this.localNodeId = localNodeId; // buckets = new Bucket[Key.ID_LENGTH]; // for (int i = 0; i < Key.ID_LENGTH; i++) // { // buckets[i] = new Bucket(client, k, i); // } // } // // /** // * Compute the bucket ID in which a given node should be placed; the bucketId is computed based on how far the node is away from the Local Node. // * // * @param nid The Key for which we want to find which bucket it belong to // * // * @return Integer The bucket ID in which the given node should be placed. // */ // public final int getBucketId(Key nid) // { // int bId = this.localNodeId.getDistance(nid) - 1; // // /* If we are trying to insert a node into it's own routing table, then the bucket ID will be -1, so let's just keep it in bucket 0 */ // return bId < 0 ? 0 : bId; // } // // public void addNode(Node node) { // if(!node.getId().equals(localNodeId)) { // buckets[getBucketId(node.getId())].addNode(node); // } // else { // // System.out.println("Routing table of node="+nodeId+" can't contain itself. (localNodeId="+localNodeId+")"); // } // } // // public Bucket[] getBuckets() { // return buckets; // } // // public Stream<Bucket> getBucketStream() { // return Arrays.stream(buckets); // } // // public List<Node> findClosest(Key lookupId, int numberOfRequiredNodes) { // return getBucketStream().flatMap(bucket -> bucket.getNodes().stream()) // .sorted((node1,node2) -> node1.getId().getKey().xor(lookupId.getKey()).abs() // .compareTo( node2.getId().getKey().xor(lookupId.getKey()).abs() )) // .limit(numberOfRequiredNodes).collect(Collectors.toList()); // } // // public void retireNode(Node node) { // buckets[getBucketId(node.getId())].retireNode(node); // } // } // // Path: src/main/java/de/cgrotz/kademlia/storage/LocalStorage.java // public interface LocalStorage { // void put(Key key, Value value); // // Value get(Key key); // // boolean contains(Key key); // // List<Key> getKeysBeforeTimestamp(long timestamp); // // default void updateLastPublished(Key key, long timestamp) { // Value node = get(key); // node.setLastPublished(timestamp); // put(key, node); // } // }
import de.cgrotz.kademlia.events.Event; import de.cgrotz.kademlia.node.Node; import de.cgrotz.kademlia.routing.RoutingTable; import de.cgrotz.kademlia.storage.LocalStorage; import lombok.Data; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; import java.util.Arrays; import java.util.Map; import java.util.function.Consumer;
package de.cgrotz.kademlia.server; /** * Created by Christoph on 21.09.2016. */ @Data public class KademliaServer { private final Logger LOGGER; private final RoutingTable routingTable;
// Path: src/main/java/de/cgrotz/kademlia/events/Event.java // public abstract class Event { // // } // // Path: src/main/java/de/cgrotz/kademlia/node/Node.java // @Data // @EqualsAndHashCode(of={"id"}) // @Builder // public class Node implements Comparable<Node>{ // private Key id; // @Singular // private final List<Listener> advertisedListeners; // private long lastSeen = System.currentTimeMillis(); // // @Override // public int compareTo(Node o) { // if (this.equals(o)) // { // return 0; // } // // return (this.lastSeen > o.lastSeen) ? 1 : -1; // } // } // // Path: src/main/java/de/cgrotz/kademlia/routing/RoutingTable.java // @ToString // @EqualsAndHashCode // public class RoutingTable { // // private final Key localNodeId; // // private final Bucket[] buckets; // // public RoutingTable(int k, Key localNodeId, KademliaClient client) { // this.localNodeId = localNodeId; // buckets = new Bucket[Key.ID_LENGTH]; // for (int i = 0; i < Key.ID_LENGTH; i++) // { // buckets[i] = new Bucket(client, k, i); // } // } // // /** // * Compute the bucket ID in which a given node should be placed; the bucketId is computed based on how far the node is away from the Local Node. // * // * @param nid The Key for which we want to find which bucket it belong to // * // * @return Integer The bucket ID in which the given node should be placed. // */ // public final int getBucketId(Key nid) // { // int bId = this.localNodeId.getDistance(nid) - 1; // // /* If we are trying to insert a node into it's own routing table, then the bucket ID will be -1, so let's just keep it in bucket 0 */ // return bId < 0 ? 0 : bId; // } // // public void addNode(Node node) { // if(!node.getId().equals(localNodeId)) { // buckets[getBucketId(node.getId())].addNode(node); // } // else { // // System.out.println("Routing table of node="+nodeId+" can't contain itself. (localNodeId="+localNodeId+")"); // } // } // // public Bucket[] getBuckets() { // return buckets; // } // // public Stream<Bucket> getBucketStream() { // return Arrays.stream(buckets); // } // // public List<Node> findClosest(Key lookupId, int numberOfRequiredNodes) { // return getBucketStream().flatMap(bucket -> bucket.getNodes().stream()) // .sorted((node1,node2) -> node1.getId().getKey().xor(lookupId.getKey()).abs() // .compareTo( node2.getId().getKey().xor(lookupId.getKey()).abs() )) // .limit(numberOfRequiredNodes).collect(Collectors.toList()); // } // // public void retireNode(Node node) { // buckets[getBucketId(node.getId())].retireNode(node); // } // } // // Path: src/main/java/de/cgrotz/kademlia/storage/LocalStorage.java // public interface LocalStorage { // void put(Key key, Value value); // // Value get(Key key); // // boolean contains(Key key); // // List<Key> getKeysBeforeTimestamp(long timestamp); // // default void updateLastPublished(Key key, long timestamp) { // Value node = get(key); // node.setLastPublished(timestamp); // put(key, node); // } // } // Path: src/main/java/de/cgrotz/kademlia/server/KademliaServer.java import de.cgrotz.kademlia.events.Event; import de.cgrotz.kademlia.node.Node; import de.cgrotz.kademlia.routing.RoutingTable; import de.cgrotz.kademlia.storage.LocalStorage; import lombok.Data; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; import java.util.Arrays; import java.util.Map; import java.util.function.Consumer; package de.cgrotz.kademlia.server; /** * Created by Christoph on 21.09.2016. */ @Data public class KademliaServer { private final Logger LOGGER; private final RoutingTable routingTable;
private final Node localNode;
cgrotz/kademlia
src/main/java/de/cgrotz/kademlia/server/KademliaServer.java
// Path: src/main/java/de/cgrotz/kademlia/events/Event.java // public abstract class Event { // // } // // Path: src/main/java/de/cgrotz/kademlia/node/Node.java // @Data // @EqualsAndHashCode(of={"id"}) // @Builder // public class Node implements Comparable<Node>{ // private Key id; // @Singular // private final List<Listener> advertisedListeners; // private long lastSeen = System.currentTimeMillis(); // // @Override // public int compareTo(Node o) { // if (this.equals(o)) // { // return 0; // } // // return (this.lastSeen > o.lastSeen) ? 1 : -1; // } // } // // Path: src/main/java/de/cgrotz/kademlia/routing/RoutingTable.java // @ToString // @EqualsAndHashCode // public class RoutingTable { // // private final Key localNodeId; // // private final Bucket[] buckets; // // public RoutingTable(int k, Key localNodeId, KademliaClient client) { // this.localNodeId = localNodeId; // buckets = new Bucket[Key.ID_LENGTH]; // for (int i = 0; i < Key.ID_LENGTH; i++) // { // buckets[i] = new Bucket(client, k, i); // } // } // // /** // * Compute the bucket ID in which a given node should be placed; the bucketId is computed based on how far the node is away from the Local Node. // * // * @param nid The Key for which we want to find which bucket it belong to // * // * @return Integer The bucket ID in which the given node should be placed. // */ // public final int getBucketId(Key nid) // { // int bId = this.localNodeId.getDistance(nid) - 1; // // /* If we are trying to insert a node into it's own routing table, then the bucket ID will be -1, so let's just keep it in bucket 0 */ // return bId < 0 ? 0 : bId; // } // // public void addNode(Node node) { // if(!node.getId().equals(localNodeId)) { // buckets[getBucketId(node.getId())].addNode(node); // } // else { // // System.out.println("Routing table of node="+nodeId+" can't contain itself. (localNodeId="+localNodeId+")"); // } // } // // public Bucket[] getBuckets() { // return buckets; // } // // public Stream<Bucket> getBucketStream() { // return Arrays.stream(buckets); // } // // public List<Node> findClosest(Key lookupId, int numberOfRequiredNodes) { // return getBucketStream().flatMap(bucket -> bucket.getNodes().stream()) // .sorted((node1,node2) -> node1.getId().getKey().xor(lookupId.getKey()).abs() // .compareTo( node2.getId().getKey().xor(lookupId.getKey()).abs() )) // .limit(numberOfRequiredNodes).collect(Collectors.toList()); // } // // public void retireNode(Node node) { // buckets[getBucketId(node.getId())].retireNode(node); // } // } // // Path: src/main/java/de/cgrotz/kademlia/storage/LocalStorage.java // public interface LocalStorage { // void put(Key key, Value value); // // Value get(Key key); // // boolean contains(Key key); // // List<Key> getKeysBeforeTimestamp(long timestamp); // // default void updateLastPublished(Key key, long timestamp) { // Value node = get(key); // node.setLastPublished(timestamp); // put(key, node); // } // }
import de.cgrotz.kademlia.events.Event; import de.cgrotz.kademlia.node.Node; import de.cgrotz.kademlia.routing.RoutingTable; import de.cgrotz.kademlia.storage.LocalStorage; import lombok.Data; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; import java.util.Arrays; import java.util.Map; import java.util.function.Consumer;
package de.cgrotz.kademlia.server; /** * Created by Christoph on 21.09.2016. */ @Data public class KademliaServer { private final Logger LOGGER; private final RoutingTable routingTable; private final Node localNode; private final int kValue;
// Path: src/main/java/de/cgrotz/kademlia/events/Event.java // public abstract class Event { // // } // // Path: src/main/java/de/cgrotz/kademlia/node/Node.java // @Data // @EqualsAndHashCode(of={"id"}) // @Builder // public class Node implements Comparable<Node>{ // private Key id; // @Singular // private final List<Listener> advertisedListeners; // private long lastSeen = System.currentTimeMillis(); // // @Override // public int compareTo(Node o) { // if (this.equals(o)) // { // return 0; // } // // return (this.lastSeen > o.lastSeen) ? 1 : -1; // } // } // // Path: src/main/java/de/cgrotz/kademlia/routing/RoutingTable.java // @ToString // @EqualsAndHashCode // public class RoutingTable { // // private final Key localNodeId; // // private final Bucket[] buckets; // // public RoutingTable(int k, Key localNodeId, KademliaClient client) { // this.localNodeId = localNodeId; // buckets = new Bucket[Key.ID_LENGTH]; // for (int i = 0; i < Key.ID_LENGTH; i++) // { // buckets[i] = new Bucket(client, k, i); // } // } // // /** // * Compute the bucket ID in which a given node should be placed; the bucketId is computed based on how far the node is away from the Local Node. // * // * @param nid The Key for which we want to find which bucket it belong to // * // * @return Integer The bucket ID in which the given node should be placed. // */ // public final int getBucketId(Key nid) // { // int bId = this.localNodeId.getDistance(nid) - 1; // // /* If we are trying to insert a node into it's own routing table, then the bucket ID will be -1, so let's just keep it in bucket 0 */ // return bId < 0 ? 0 : bId; // } // // public void addNode(Node node) { // if(!node.getId().equals(localNodeId)) { // buckets[getBucketId(node.getId())].addNode(node); // } // else { // // System.out.println("Routing table of node="+nodeId+" can't contain itself. (localNodeId="+localNodeId+")"); // } // } // // public Bucket[] getBuckets() { // return buckets; // } // // public Stream<Bucket> getBucketStream() { // return Arrays.stream(buckets); // } // // public List<Node> findClosest(Key lookupId, int numberOfRequiredNodes) { // return getBucketStream().flatMap(bucket -> bucket.getNodes().stream()) // .sorted((node1,node2) -> node1.getId().getKey().xor(lookupId.getKey()).abs() // .compareTo( node2.getId().getKey().xor(lookupId.getKey()).abs() )) // .limit(numberOfRequiredNodes).collect(Collectors.toList()); // } // // public void retireNode(Node node) { // buckets[getBucketId(node.getId())].retireNode(node); // } // } // // Path: src/main/java/de/cgrotz/kademlia/storage/LocalStorage.java // public interface LocalStorage { // void put(Key key, Value value); // // Value get(Key key); // // boolean contains(Key key); // // List<Key> getKeysBeforeTimestamp(long timestamp); // // default void updateLastPublished(Key key, long timestamp) { // Value node = get(key); // node.setLastPublished(timestamp); // put(key, node); // } // } // Path: src/main/java/de/cgrotz/kademlia/server/KademliaServer.java import de.cgrotz.kademlia.events.Event; import de.cgrotz.kademlia.node.Node; import de.cgrotz.kademlia.routing.RoutingTable; import de.cgrotz.kademlia.storage.LocalStorage; import lombok.Data; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; import java.util.Arrays; import java.util.Map; import java.util.function.Consumer; package de.cgrotz.kademlia.server; /** * Created by Christoph on 21.09.2016. */ @Data public class KademliaServer { private final Logger LOGGER; private final RoutingTable routingTable; private final Node localNode; private final int kValue;
private final LocalStorage localStorage;
cgrotz/kademlia
src/main/java/de/cgrotz/kademlia/server/KademliaServer.java
// Path: src/main/java/de/cgrotz/kademlia/events/Event.java // public abstract class Event { // // } // // Path: src/main/java/de/cgrotz/kademlia/node/Node.java // @Data // @EqualsAndHashCode(of={"id"}) // @Builder // public class Node implements Comparable<Node>{ // private Key id; // @Singular // private final List<Listener> advertisedListeners; // private long lastSeen = System.currentTimeMillis(); // // @Override // public int compareTo(Node o) { // if (this.equals(o)) // { // return 0; // } // // return (this.lastSeen > o.lastSeen) ? 1 : -1; // } // } // // Path: src/main/java/de/cgrotz/kademlia/routing/RoutingTable.java // @ToString // @EqualsAndHashCode // public class RoutingTable { // // private final Key localNodeId; // // private final Bucket[] buckets; // // public RoutingTable(int k, Key localNodeId, KademliaClient client) { // this.localNodeId = localNodeId; // buckets = new Bucket[Key.ID_LENGTH]; // for (int i = 0; i < Key.ID_LENGTH; i++) // { // buckets[i] = new Bucket(client, k, i); // } // } // // /** // * Compute the bucket ID in which a given node should be placed; the bucketId is computed based on how far the node is away from the Local Node. // * // * @param nid The Key for which we want to find which bucket it belong to // * // * @return Integer The bucket ID in which the given node should be placed. // */ // public final int getBucketId(Key nid) // { // int bId = this.localNodeId.getDistance(nid) - 1; // // /* If we are trying to insert a node into it's own routing table, then the bucket ID will be -1, so let's just keep it in bucket 0 */ // return bId < 0 ? 0 : bId; // } // // public void addNode(Node node) { // if(!node.getId().equals(localNodeId)) { // buckets[getBucketId(node.getId())].addNode(node); // } // else { // // System.out.println("Routing table of node="+nodeId+" can't contain itself. (localNodeId="+localNodeId+")"); // } // } // // public Bucket[] getBuckets() { // return buckets; // } // // public Stream<Bucket> getBucketStream() { // return Arrays.stream(buckets); // } // // public List<Node> findClosest(Key lookupId, int numberOfRequiredNodes) { // return getBucketStream().flatMap(bucket -> bucket.getNodes().stream()) // .sorted((node1,node2) -> node1.getId().getKey().xor(lookupId.getKey()).abs() // .compareTo( node2.getId().getKey().xor(lookupId.getKey()).abs() )) // .limit(numberOfRequiredNodes).collect(Collectors.toList()); // } // // public void retireNode(Node node) { // buckets[getBucketId(node.getId())].retireNode(node); // } // } // // Path: src/main/java/de/cgrotz/kademlia/storage/LocalStorage.java // public interface LocalStorage { // void put(Key key, Value value); // // Value get(Key key); // // boolean contains(Key key); // // List<Key> getKeysBeforeTimestamp(long timestamp); // // default void updateLastPublished(Key key, long timestamp) { // Value node = get(key); // node.setLastPublished(timestamp); // put(key, node); // } // }
import de.cgrotz.kademlia.events.Event; import de.cgrotz.kademlia.node.Node; import de.cgrotz.kademlia.routing.RoutingTable; import de.cgrotz.kademlia.storage.LocalStorage; import lombok.Data; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; import java.util.Arrays; import java.util.Map; import java.util.function.Consumer;
package de.cgrotz.kademlia.server; /** * Created by Christoph on 21.09.2016. */ @Data public class KademliaServer { private final Logger LOGGER; private final RoutingTable routingTable; private final Node localNode; private final int kValue; private final LocalStorage localStorage;
// Path: src/main/java/de/cgrotz/kademlia/events/Event.java // public abstract class Event { // // } // // Path: src/main/java/de/cgrotz/kademlia/node/Node.java // @Data // @EqualsAndHashCode(of={"id"}) // @Builder // public class Node implements Comparable<Node>{ // private Key id; // @Singular // private final List<Listener> advertisedListeners; // private long lastSeen = System.currentTimeMillis(); // // @Override // public int compareTo(Node o) { // if (this.equals(o)) // { // return 0; // } // // return (this.lastSeen > o.lastSeen) ? 1 : -1; // } // } // // Path: src/main/java/de/cgrotz/kademlia/routing/RoutingTable.java // @ToString // @EqualsAndHashCode // public class RoutingTable { // // private final Key localNodeId; // // private final Bucket[] buckets; // // public RoutingTable(int k, Key localNodeId, KademliaClient client) { // this.localNodeId = localNodeId; // buckets = new Bucket[Key.ID_LENGTH]; // for (int i = 0; i < Key.ID_LENGTH; i++) // { // buckets[i] = new Bucket(client, k, i); // } // } // // /** // * Compute the bucket ID in which a given node should be placed; the bucketId is computed based on how far the node is away from the Local Node. // * // * @param nid The Key for which we want to find which bucket it belong to // * // * @return Integer The bucket ID in which the given node should be placed. // */ // public final int getBucketId(Key nid) // { // int bId = this.localNodeId.getDistance(nid) - 1; // // /* If we are trying to insert a node into it's own routing table, then the bucket ID will be -1, so let's just keep it in bucket 0 */ // return bId < 0 ? 0 : bId; // } // // public void addNode(Node node) { // if(!node.getId().equals(localNodeId)) { // buckets[getBucketId(node.getId())].addNode(node); // } // else { // // System.out.println("Routing table of node="+nodeId+" can't contain itself. (localNodeId="+localNodeId+")"); // } // } // // public Bucket[] getBuckets() { // return buckets; // } // // public Stream<Bucket> getBucketStream() { // return Arrays.stream(buckets); // } // // public List<Node> findClosest(Key lookupId, int numberOfRequiredNodes) { // return getBucketStream().flatMap(bucket -> bucket.getNodes().stream()) // .sorted((node1,node2) -> node1.getId().getKey().xor(lookupId.getKey()).abs() // .compareTo( node2.getId().getKey().xor(lookupId.getKey()).abs() )) // .limit(numberOfRequiredNodes).collect(Collectors.toList()); // } // // public void retireNode(Node node) { // buckets[getBucketId(node.getId())].retireNode(node); // } // } // // Path: src/main/java/de/cgrotz/kademlia/storage/LocalStorage.java // public interface LocalStorage { // void put(Key key, Value value); // // Value get(Key key); // // boolean contains(Key key); // // List<Key> getKeysBeforeTimestamp(long timestamp); // // default void updateLastPublished(Key key, long timestamp) { // Value node = get(key); // node.setLastPublished(timestamp); // put(key, node); // } // } // Path: src/main/java/de/cgrotz/kademlia/server/KademliaServer.java import de.cgrotz.kademlia.events.Event; import de.cgrotz.kademlia.node.Node; import de.cgrotz.kademlia.routing.RoutingTable; import de.cgrotz.kademlia.storage.LocalStorage; import lombok.Data; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; import java.util.Arrays; import java.util.Map; import java.util.function.Consumer; package de.cgrotz.kademlia.server; /** * Created by Christoph on 21.09.2016. */ @Data public class KademliaServer { private final Logger LOGGER; private final RoutingTable routingTable; private final Node localNode; private final int kValue; private final LocalStorage localStorage;
private final Map<String, Consumer<Event>> eventConsumers;
cgrotz/kademlia
src/main/java/de/cgrotz/kademlia/protocol/NodeReply.java
// Path: src/main/java/de/cgrotz/kademlia/node/Node.java // @Data // @EqualsAndHashCode(of={"id"}) // @Builder // public class Node implements Comparable<Node>{ // private Key id; // @Singular // private final List<Listener> advertisedListeners; // private long lastSeen = System.currentTimeMillis(); // // @Override // public int compareTo(Node o) { // if (this.equals(o)) // { // return 0; // } // // return (this.lastSeen > o.lastSeen) ? 1 : -1; // } // }
import de.cgrotz.kademlia.node.Node; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; import java.util.List;
package de.cgrotz.kademlia.protocol; /** * Created by Christoph on 23.09.2016. */ @Data @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class NodeReply extends Message {
// Path: src/main/java/de/cgrotz/kademlia/node/Node.java // @Data // @EqualsAndHashCode(of={"id"}) // @Builder // public class Node implements Comparable<Node>{ // private Key id; // @Singular // private final List<Listener> advertisedListeners; // private long lastSeen = System.currentTimeMillis(); // // @Override // public int compareTo(Node o) { // if (this.equals(o)) // { // return 0; // } // // return (this.lastSeen > o.lastSeen) ? 1 : -1; // } // } // Path: src/main/java/de/cgrotz/kademlia/protocol/NodeReply.java import de.cgrotz.kademlia.node.Node; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; import java.util.List; package de.cgrotz.kademlia.protocol; /** * Created by Christoph on 23.09.2016. */ @Data @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class NodeReply extends Message {
private final List<Node> nodes;
cgrotz/kademlia
src/main/java/de/cgrotz/kademlia/protocol/FindValue.java
// Path: src/main/java/de/cgrotz/kademlia/node/Key.java // @Data // @EqualsAndHashCode(of = "key") // public class Key { // public final static int ID_LENGTH = 160; // // private BigInteger key; // // public Key(byte[] result) { // if(result.length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = new BigInteger(result); // } // // public Key(BigInteger key) { // if( key.toByteArray().length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = key; // } // // public Key(int id) { // this.key = BigInteger.valueOf(id); // } // // public static Key random() { // byte[] bytes = new byte[ID_LENGTH / 8]; // SecureRandom sr1 = new SecureRandom(); // sr1.nextBytes(bytes); // return new Key(bytes); // } // // public static Key build(String key) { // return new Key(new BigInteger(key,16)); // } // // /** // * Checks the distance between this and another Key // * // * @param nid // * // * @return The distance of this Key from the given Key // */ // public Key xor(Key nid) // { // return new Key(nid.getKey().xor(this.key)); // } // // /** // * Generates a Key that is some distance away from this Key // * // * @param distance in number of bits // * // * @return Key The newly generated Key // */ // public Key generateNodeIdByDistance(int distance) // { // byte[] result = new byte[ID_LENGTH / 8]; // // /* Since distance = ID_LENGTH - prefixLength, we need to fill that amount with 0's */ // int numByteZeroes = (ID_LENGTH - distance) / 8; // int numBitZeroes = 8 - (distance % 8); // // /* Filling byte zeroes */ // for (int i = 0; i < numByteZeroes; i++) // { // result[i] = 0; // } // // /* Filling bit zeroes */ // BitSet bits = new BitSet(8); // bits.set(0, 8); // // for (int i = 0; i < numBitZeroes; i++) // { // /* Shift 1 zero into the start of the value */ // bits.clear(i); // } // bits.flip(0, 8); // Flip the bits since they're in reverse order // result[numByteZeroes] = (byte) bits.toByteArray()[0]; // // /* Set the remaining bytes to Maximum value */ // for (int i = numByteZeroes + 1; i < result.length; i++) // { // result[i] = Byte.MAX_VALUE; // } // // return this.xor(new Key(result)); // } // // /** // * Counts the number of leading 0's in this Key // * // * @return Integer The number of leading 0's // */ // public int getFirstSetBitIndex() // { // int prefixLength = 0; // // for (byte b : this.key.toByteArray()) // { // if (b == 0) // { // prefixLength += 8; // } // else // { // /* If the byte is not 0, we need to count how many MSBs are 0 */ // int count = 0; // for (int i = 7; i >= 0; i--) // { // boolean a = (b & (1 << i)) == 0; // if (a) // { // count++; // } // else // { // break; // Reset the count if we encounter a non-zero number // } // } // // /* Add the count of MSB 0s to the prefix length */ // prefixLength += count; // // /* Break here since we've now covered the MSB 0s */ // break; // } // } // return prefixLength; // } // // @Override // public String toString() // { // return this.key.toString(16); // } // // // /** // * Gets the distance from this Key to another Key // * // * @param to // * // * @return Integer The distance // */ // public int getDistance(Key to) // { // /** // * Compute the xor of this and to // * Get the index i of the first set bit of the xor returned Key // * The distance between them is ID_LENGTH - i // */ // return ID_LENGTH - this.xor(to).getFirstSetBitIndex(); // } // } // // Path: src/main/java/de/cgrotz/kademlia/node/Node.java // @Data // @EqualsAndHashCode(of={"id"}) // @Builder // public class Node implements Comparable<Node>{ // private Key id; // @Singular // private final List<Listener> advertisedListeners; // private long lastSeen = System.currentTimeMillis(); // // @Override // public int compareTo(Node o) { // if (this.equals(o)) // { // return 0; // } // // return (this.lastSeen > o.lastSeen) ? 1 : -1; // } // }
import de.cgrotz.kademlia.node.Key; import de.cgrotz.kademlia.node.Node; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString;
package de.cgrotz.kademlia.protocol; /** * * Same as FIND_NODE, but if the recipient of the request has the requested key in its store, it will return the corresponding value. * * Created by Christoph on 22.09.2016. */ @Data @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class FindValue extends Message {
// Path: src/main/java/de/cgrotz/kademlia/node/Key.java // @Data // @EqualsAndHashCode(of = "key") // public class Key { // public final static int ID_LENGTH = 160; // // private BigInteger key; // // public Key(byte[] result) { // if(result.length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = new BigInteger(result); // } // // public Key(BigInteger key) { // if( key.toByteArray().length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = key; // } // // public Key(int id) { // this.key = BigInteger.valueOf(id); // } // // public static Key random() { // byte[] bytes = new byte[ID_LENGTH / 8]; // SecureRandom sr1 = new SecureRandom(); // sr1.nextBytes(bytes); // return new Key(bytes); // } // // public static Key build(String key) { // return new Key(new BigInteger(key,16)); // } // // /** // * Checks the distance between this and another Key // * // * @param nid // * // * @return The distance of this Key from the given Key // */ // public Key xor(Key nid) // { // return new Key(nid.getKey().xor(this.key)); // } // // /** // * Generates a Key that is some distance away from this Key // * // * @param distance in number of bits // * // * @return Key The newly generated Key // */ // public Key generateNodeIdByDistance(int distance) // { // byte[] result = new byte[ID_LENGTH / 8]; // // /* Since distance = ID_LENGTH - prefixLength, we need to fill that amount with 0's */ // int numByteZeroes = (ID_LENGTH - distance) / 8; // int numBitZeroes = 8 - (distance % 8); // // /* Filling byte zeroes */ // for (int i = 0; i < numByteZeroes; i++) // { // result[i] = 0; // } // // /* Filling bit zeroes */ // BitSet bits = new BitSet(8); // bits.set(0, 8); // // for (int i = 0; i < numBitZeroes; i++) // { // /* Shift 1 zero into the start of the value */ // bits.clear(i); // } // bits.flip(0, 8); // Flip the bits since they're in reverse order // result[numByteZeroes] = (byte) bits.toByteArray()[0]; // // /* Set the remaining bytes to Maximum value */ // for (int i = numByteZeroes + 1; i < result.length; i++) // { // result[i] = Byte.MAX_VALUE; // } // // return this.xor(new Key(result)); // } // // /** // * Counts the number of leading 0's in this Key // * // * @return Integer The number of leading 0's // */ // public int getFirstSetBitIndex() // { // int prefixLength = 0; // // for (byte b : this.key.toByteArray()) // { // if (b == 0) // { // prefixLength += 8; // } // else // { // /* If the byte is not 0, we need to count how many MSBs are 0 */ // int count = 0; // for (int i = 7; i >= 0; i--) // { // boolean a = (b & (1 << i)) == 0; // if (a) // { // count++; // } // else // { // break; // Reset the count if we encounter a non-zero number // } // } // // /* Add the count of MSB 0s to the prefix length */ // prefixLength += count; // // /* Break here since we've now covered the MSB 0s */ // break; // } // } // return prefixLength; // } // // @Override // public String toString() // { // return this.key.toString(16); // } // // // /** // * Gets the distance from this Key to another Key // * // * @param to // * // * @return Integer The distance // */ // public int getDistance(Key to) // { // /** // * Compute the xor of this and to // * Get the index i of the first set bit of the xor returned Key // * The distance between them is ID_LENGTH - i // */ // return ID_LENGTH - this.xor(to).getFirstSetBitIndex(); // } // } // // Path: src/main/java/de/cgrotz/kademlia/node/Node.java // @Data // @EqualsAndHashCode(of={"id"}) // @Builder // public class Node implements Comparable<Node>{ // private Key id; // @Singular // private final List<Listener> advertisedListeners; // private long lastSeen = System.currentTimeMillis(); // // @Override // public int compareTo(Node o) { // if (this.equals(o)) // { // return 0; // } // // return (this.lastSeen > o.lastSeen) ? 1 : -1; // } // } // Path: src/main/java/de/cgrotz/kademlia/protocol/FindValue.java import de.cgrotz.kademlia.node.Key; import de.cgrotz.kademlia.node.Node; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; package de.cgrotz.kademlia.protocol; /** * * Same as FIND_NODE, but if the recipient of the request has the requested key in its store, it will return the corresponding value. * * Created by Christoph on 22.09.2016. */ @Data @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class FindValue extends Message {
private final Key key;
cgrotz/kademlia
src/main/java/de/cgrotz/kademlia/protocol/FindValue.java
// Path: src/main/java/de/cgrotz/kademlia/node/Key.java // @Data // @EqualsAndHashCode(of = "key") // public class Key { // public final static int ID_LENGTH = 160; // // private BigInteger key; // // public Key(byte[] result) { // if(result.length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = new BigInteger(result); // } // // public Key(BigInteger key) { // if( key.toByteArray().length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = key; // } // // public Key(int id) { // this.key = BigInteger.valueOf(id); // } // // public static Key random() { // byte[] bytes = new byte[ID_LENGTH / 8]; // SecureRandom sr1 = new SecureRandom(); // sr1.nextBytes(bytes); // return new Key(bytes); // } // // public static Key build(String key) { // return new Key(new BigInteger(key,16)); // } // // /** // * Checks the distance between this and another Key // * // * @param nid // * // * @return The distance of this Key from the given Key // */ // public Key xor(Key nid) // { // return new Key(nid.getKey().xor(this.key)); // } // // /** // * Generates a Key that is some distance away from this Key // * // * @param distance in number of bits // * // * @return Key The newly generated Key // */ // public Key generateNodeIdByDistance(int distance) // { // byte[] result = new byte[ID_LENGTH / 8]; // // /* Since distance = ID_LENGTH - prefixLength, we need to fill that amount with 0's */ // int numByteZeroes = (ID_LENGTH - distance) / 8; // int numBitZeroes = 8 - (distance % 8); // // /* Filling byte zeroes */ // for (int i = 0; i < numByteZeroes; i++) // { // result[i] = 0; // } // // /* Filling bit zeroes */ // BitSet bits = new BitSet(8); // bits.set(0, 8); // // for (int i = 0; i < numBitZeroes; i++) // { // /* Shift 1 zero into the start of the value */ // bits.clear(i); // } // bits.flip(0, 8); // Flip the bits since they're in reverse order // result[numByteZeroes] = (byte) bits.toByteArray()[0]; // // /* Set the remaining bytes to Maximum value */ // for (int i = numByteZeroes + 1; i < result.length; i++) // { // result[i] = Byte.MAX_VALUE; // } // // return this.xor(new Key(result)); // } // // /** // * Counts the number of leading 0's in this Key // * // * @return Integer The number of leading 0's // */ // public int getFirstSetBitIndex() // { // int prefixLength = 0; // // for (byte b : this.key.toByteArray()) // { // if (b == 0) // { // prefixLength += 8; // } // else // { // /* If the byte is not 0, we need to count how many MSBs are 0 */ // int count = 0; // for (int i = 7; i >= 0; i--) // { // boolean a = (b & (1 << i)) == 0; // if (a) // { // count++; // } // else // { // break; // Reset the count if we encounter a non-zero number // } // } // // /* Add the count of MSB 0s to the prefix length */ // prefixLength += count; // // /* Break here since we've now covered the MSB 0s */ // break; // } // } // return prefixLength; // } // // @Override // public String toString() // { // return this.key.toString(16); // } // // // /** // * Gets the distance from this Key to another Key // * // * @param to // * // * @return Integer The distance // */ // public int getDistance(Key to) // { // /** // * Compute the xor of this and to // * Get the index i of the first set bit of the xor returned Key // * The distance between them is ID_LENGTH - i // */ // return ID_LENGTH - this.xor(to).getFirstSetBitIndex(); // } // } // // Path: src/main/java/de/cgrotz/kademlia/node/Node.java // @Data // @EqualsAndHashCode(of={"id"}) // @Builder // public class Node implements Comparable<Node>{ // private Key id; // @Singular // private final List<Listener> advertisedListeners; // private long lastSeen = System.currentTimeMillis(); // // @Override // public int compareTo(Node o) { // if (this.equals(o)) // { // return 0; // } // // return (this.lastSeen > o.lastSeen) ? 1 : -1; // } // }
import de.cgrotz.kademlia.node.Key; import de.cgrotz.kademlia.node.Node; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString;
package de.cgrotz.kademlia.protocol; /** * * Same as FIND_NODE, but if the recipient of the request has the requested key in its store, it will return the corresponding value. * * Created by Christoph on 22.09.2016. */ @Data @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class FindValue extends Message { private final Key key;
// Path: src/main/java/de/cgrotz/kademlia/node/Key.java // @Data // @EqualsAndHashCode(of = "key") // public class Key { // public final static int ID_LENGTH = 160; // // private BigInteger key; // // public Key(byte[] result) { // if(result.length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = new BigInteger(result); // } // // public Key(BigInteger key) { // if( key.toByteArray().length > ID_LENGTH/8 ) { // throw new RuntimeException("ID to long. Needs to be "+ID_LENGTH+"bits long." ); // } // this.key = key; // } // // public Key(int id) { // this.key = BigInteger.valueOf(id); // } // // public static Key random() { // byte[] bytes = new byte[ID_LENGTH / 8]; // SecureRandom sr1 = new SecureRandom(); // sr1.nextBytes(bytes); // return new Key(bytes); // } // // public static Key build(String key) { // return new Key(new BigInteger(key,16)); // } // // /** // * Checks the distance between this and another Key // * // * @param nid // * // * @return The distance of this Key from the given Key // */ // public Key xor(Key nid) // { // return new Key(nid.getKey().xor(this.key)); // } // // /** // * Generates a Key that is some distance away from this Key // * // * @param distance in number of bits // * // * @return Key The newly generated Key // */ // public Key generateNodeIdByDistance(int distance) // { // byte[] result = new byte[ID_LENGTH / 8]; // // /* Since distance = ID_LENGTH - prefixLength, we need to fill that amount with 0's */ // int numByteZeroes = (ID_LENGTH - distance) / 8; // int numBitZeroes = 8 - (distance % 8); // // /* Filling byte zeroes */ // for (int i = 0; i < numByteZeroes; i++) // { // result[i] = 0; // } // // /* Filling bit zeroes */ // BitSet bits = new BitSet(8); // bits.set(0, 8); // // for (int i = 0; i < numBitZeroes; i++) // { // /* Shift 1 zero into the start of the value */ // bits.clear(i); // } // bits.flip(0, 8); // Flip the bits since they're in reverse order // result[numByteZeroes] = (byte) bits.toByteArray()[0]; // // /* Set the remaining bytes to Maximum value */ // for (int i = numByteZeroes + 1; i < result.length; i++) // { // result[i] = Byte.MAX_VALUE; // } // // return this.xor(new Key(result)); // } // // /** // * Counts the number of leading 0's in this Key // * // * @return Integer The number of leading 0's // */ // public int getFirstSetBitIndex() // { // int prefixLength = 0; // // for (byte b : this.key.toByteArray()) // { // if (b == 0) // { // prefixLength += 8; // } // else // { // /* If the byte is not 0, we need to count how many MSBs are 0 */ // int count = 0; // for (int i = 7; i >= 0; i--) // { // boolean a = (b & (1 << i)) == 0; // if (a) // { // count++; // } // else // { // break; // Reset the count if we encounter a non-zero number // } // } // // /* Add the count of MSB 0s to the prefix length */ // prefixLength += count; // // /* Break here since we've now covered the MSB 0s */ // break; // } // } // return prefixLength; // } // // @Override // public String toString() // { // return this.key.toString(16); // } // // // /** // * Gets the distance from this Key to another Key // * // * @param to // * // * @return Integer The distance // */ // public int getDistance(Key to) // { // /** // * Compute the xor of this and to // * Get the index i of the first set bit of the xor returned Key // * The distance between them is ID_LENGTH - i // */ // return ID_LENGTH - this.xor(to).getFirstSetBitIndex(); // } // } // // Path: src/main/java/de/cgrotz/kademlia/node/Node.java // @Data // @EqualsAndHashCode(of={"id"}) // @Builder // public class Node implements Comparable<Node>{ // private Key id; // @Singular // private final List<Listener> advertisedListeners; // private long lastSeen = System.currentTimeMillis(); // // @Override // public int compareTo(Node o) { // if (this.equals(o)) // { // return 0; // } // // return (this.lastSeen > o.lastSeen) ? 1 : -1; // } // } // Path: src/main/java/de/cgrotz/kademlia/protocol/FindValue.java import de.cgrotz.kademlia.node.Key; import de.cgrotz.kademlia.node.Node; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; package de.cgrotz.kademlia.protocol; /** * * Same as FIND_NODE, but if the recipient of the request has the requested key in its store, it will return the corresponding value. * * Created by Christoph on 22.09.2016. */ @Data @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class FindValue extends Message { private final Key key;
public FindValue(long seqId, Node origin, Key key) {
IstiN/android_training_2014
task_manager/app/src/main/java/com/epam/training/taskmanager/source/VkDataSource.java
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/Api.java // public class Api { // // public static final String BASE_PATH = "https://api.vk.com/method/"; // public static final String VERSION_VALUE = "5.8"; // public static final String VERSION_PARAM = "v"; // // public static final String FRIENDS_GET = BASE_PATH + "friends.get?fields=photo_200_orig,online,nickname"; // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/CoreApplication.java // public class CoreApplication extends Application { // // private HttpDataSource mHttpDataSource; // private CachedHttpDataSource mCachedHttpDataSource; // private VkDataSource mVkDataSource; // private MySuperImageLoader mMySuperImageLoader; // // @Override // public void onCreate() { // super.onCreate(); // mMySuperImageLoader = new MySuperImageLoader(this); // mHttpDataSource = new HttpDataSource(); // mVkDataSource = new VkDataSource(); // mCachedHttpDataSource = new CachedHttpDataSource(this); // } // // @Override // public Object getSystemService(String name) { // if (HttpDataSource.KEY.equals(name)) { // //for android kitkat + // if (mHttpDataSource == null) { // mHttpDataSource = new HttpDataSource(); // } // return mHttpDataSource; // } // if (CachedHttpDataSource.KEY.equals(name)) { // //for android kitkat + // if (mCachedHttpDataSource == null) { // mCachedHttpDataSource = new CachedHttpDataSource(this); // } // return mCachedHttpDataSource; // } // if (VkDataSource.KEY.equals(name)) { // //for android kitkat + // if (mVkDataSource == null) { // mVkDataSource = new VkDataSource(); // } // return mVkDataSource; // } // if (MySuperImageLoader.KEY.equals(name)) { // //for android kitkat + // if (mMySuperImageLoader == null) { // mMySuperImageLoader = new MySuperImageLoader(this); // } // return mMySuperImageLoader; // } // return super.getSystemService(name); // } // // public static <T> T get(Context context, String key) { // if (context == null || key == null){ // throw new IllegalArgumentException("Context and key must not be null"); // } // T systemService = (T) context.getSystemService(key); // if (systemService == null) { // context = context.getApplicationContext(); // systemService = (T) context.getSystemService(key); // } // if (systemService == null) { // throw new IllegalStateException(key + " not available"); // } // return systemService; // } // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/auth/VkOAuthHelper.java // public class VkOAuthHelper { // // public static interface Callbacks { // // void onError(Exception e); // // void onSuccess(); // // } // // //TODO don't do it in your project // private static String sToken; // // public static final String REDIRECT_URL = "https://oauth.vk.com/blank.html"; // public static final String AUTORIZATION_URL = "https://oauth.vk.com/authorize?client_id=4611084&scope=offline,wall,photos,status&redirect_uri=" + REDIRECT_URL + "&display=touch&response_type=token"; // private static final String TAG = VkOAuthHelper.class.getSimpleName(); // // public static String sign(String url) { // if (url.contains("?")) { // return url + "&access_token="+sToken; // } else { // return url + "?access_token="+sToken; // } // } // // public static boolean isLogged() { // return !TextUtils.isEmpty(sToken); // } // // public static boolean proceedRedirectURL(Activity activity, String url, Callbacks callbacks) { // if (url.startsWith(REDIRECT_URL)) { // Uri uri = Uri.parse(url); // String fragment = uri.getFragment(); // Uri parsedFragment = Uri.parse("http://temp.com?" + fragment); // String accessToken = parsedFragment.getQueryParameter("access_token"); // if (!TextUtils.isEmpty(accessToken)) { // //TODO save sToken to the secure store // //TODO create account in account manager // Log.d(TAG, "token " + accessToken); // sToken = accessToken; // callbacks.onSuccess(); // return true; // } else { // String error = parsedFragment.getQueryParameter("error"); // String errorDescription = parsedFragment.getQueryParameter("error_description"); // String errorReason = parsedFragment.getQueryParameter("error_reason"); // if (!TextUtils.isEmpty(error)) { // callbacks.onError(new AuthenticationException(error+", reason : " + errorReason +"("+errorDescription+")")); // return false; // } else { // //WTF? // } // } // } // return false; // } // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/utils/AuthUtils.java // public class AuthUtils { // // public static boolean isLogged() { // return VkOAuthHelper.isLogged(); // } // // }
import android.content.Context; import android.net.Uri; import android.text.TextUtils; import com.epam.training.taskmanager.Api; import com.epam.training.taskmanager.CoreApplication; import com.epam.training.taskmanager.auth.VkOAuthHelper; import com.epam.training.taskmanager.utils.AuthUtils; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.net.URL;
package com.epam.training.taskmanager.source; /** * Created by IstiN on 17.10.2014. */ public class VkDataSource extends HttpDataSource { public static final String KEY = "VkDataSource"; public static VkDataSource get(Context context) {
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/Api.java // public class Api { // // public static final String BASE_PATH = "https://api.vk.com/method/"; // public static final String VERSION_VALUE = "5.8"; // public static final String VERSION_PARAM = "v"; // // public static final String FRIENDS_GET = BASE_PATH + "friends.get?fields=photo_200_orig,online,nickname"; // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/CoreApplication.java // public class CoreApplication extends Application { // // private HttpDataSource mHttpDataSource; // private CachedHttpDataSource mCachedHttpDataSource; // private VkDataSource mVkDataSource; // private MySuperImageLoader mMySuperImageLoader; // // @Override // public void onCreate() { // super.onCreate(); // mMySuperImageLoader = new MySuperImageLoader(this); // mHttpDataSource = new HttpDataSource(); // mVkDataSource = new VkDataSource(); // mCachedHttpDataSource = new CachedHttpDataSource(this); // } // // @Override // public Object getSystemService(String name) { // if (HttpDataSource.KEY.equals(name)) { // //for android kitkat + // if (mHttpDataSource == null) { // mHttpDataSource = new HttpDataSource(); // } // return mHttpDataSource; // } // if (CachedHttpDataSource.KEY.equals(name)) { // //for android kitkat + // if (mCachedHttpDataSource == null) { // mCachedHttpDataSource = new CachedHttpDataSource(this); // } // return mCachedHttpDataSource; // } // if (VkDataSource.KEY.equals(name)) { // //for android kitkat + // if (mVkDataSource == null) { // mVkDataSource = new VkDataSource(); // } // return mVkDataSource; // } // if (MySuperImageLoader.KEY.equals(name)) { // //for android kitkat + // if (mMySuperImageLoader == null) { // mMySuperImageLoader = new MySuperImageLoader(this); // } // return mMySuperImageLoader; // } // return super.getSystemService(name); // } // // public static <T> T get(Context context, String key) { // if (context == null || key == null){ // throw new IllegalArgumentException("Context and key must not be null"); // } // T systemService = (T) context.getSystemService(key); // if (systemService == null) { // context = context.getApplicationContext(); // systemService = (T) context.getSystemService(key); // } // if (systemService == null) { // throw new IllegalStateException(key + " not available"); // } // return systemService; // } // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/auth/VkOAuthHelper.java // public class VkOAuthHelper { // // public static interface Callbacks { // // void onError(Exception e); // // void onSuccess(); // // } // // //TODO don't do it in your project // private static String sToken; // // public static final String REDIRECT_URL = "https://oauth.vk.com/blank.html"; // public static final String AUTORIZATION_URL = "https://oauth.vk.com/authorize?client_id=4611084&scope=offline,wall,photos,status&redirect_uri=" + REDIRECT_URL + "&display=touch&response_type=token"; // private static final String TAG = VkOAuthHelper.class.getSimpleName(); // // public static String sign(String url) { // if (url.contains("?")) { // return url + "&access_token="+sToken; // } else { // return url + "?access_token="+sToken; // } // } // // public static boolean isLogged() { // return !TextUtils.isEmpty(sToken); // } // // public static boolean proceedRedirectURL(Activity activity, String url, Callbacks callbacks) { // if (url.startsWith(REDIRECT_URL)) { // Uri uri = Uri.parse(url); // String fragment = uri.getFragment(); // Uri parsedFragment = Uri.parse("http://temp.com?" + fragment); // String accessToken = parsedFragment.getQueryParameter("access_token"); // if (!TextUtils.isEmpty(accessToken)) { // //TODO save sToken to the secure store // //TODO create account in account manager // Log.d(TAG, "token " + accessToken); // sToken = accessToken; // callbacks.onSuccess(); // return true; // } else { // String error = parsedFragment.getQueryParameter("error"); // String errorDescription = parsedFragment.getQueryParameter("error_description"); // String errorReason = parsedFragment.getQueryParameter("error_reason"); // if (!TextUtils.isEmpty(error)) { // callbacks.onError(new AuthenticationException(error+", reason : " + errorReason +"("+errorDescription+")")); // return false; // } else { // //WTF? // } // } // } // return false; // } // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/utils/AuthUtils.java // public class AuthUtils { // // public static boolean isLogged() { // return VkOAuthHelper.isLogged(); // } // // } // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/source/VkDataSource.java import android.content.Context; import android.net.Uri; import android.text.TextUtils; import com.epam.training.taskmanager.Api; import com.epam.training.taskmanager.CoreApplication; import com.epam.training.taskmanager.auth.VkOAuthHelper; import com.epam.training.taskmanager.utils.AuthUtils; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.net.URL; package com.epam.training.taskmanager.source; /** * Created by IstiN on 17.10.2014. */ public class VkDataSource extends HttpDataSource { public static final String KEY = "VkDataSource"; public static VkDataSource get(Context context) {
return CoreApplication.get(context, KEY);
IstiN/android_training_2014
task_manager/app/src/main/java/com/epam/training/taskmanager/source/VkDataSource.java
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/Api.java // public class Api { // // public static final String BASE_PATH = "https://api.vk.com/method/"; // public static final String VERSION_VALUE = "5.8"; // public static final String VERSION_PARAM = "v"; // // public static final String FRIENDS_GET = BASE_PATH + "friends.get?fields=photo_200_orig,online,nickname"; // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/CoreApplication.java // public class CoreApplication extends Application { // // private HttpDataSource mHttpDataSource; // private CachedHttpDataSource mCachedHttpDataSource; // private VkDataSource mVkDataSource; // private MySuperImageLoader mMySuperImageLoader; // // @Override // public void onCreate() { // super.onCreate(); // mMySuperImageLoader = new MySuperImageLoader(this); // mHttpDataSource = new HttpDataSource(); // mVkDataSource = new VkDataSource(); // mCachedHttpDataSource = new CachedHttpDataSource(this); // } // // @Override // public Object getSystemService(String name) { // if (HttpDataSource.KEY.equals(name)) { // //for android kitkat + // if (mHttpDataSource == null) { // mHttpDataSource = new HttpDataSource(); // } // return mHttpDataSource; // } // if (CachedHttpDataSource.KEY.equals(name)) { // //for android kitkat + // if (mCachedHttpDataSource == null) { // mCachedHttpDataSource = new CachedHttpDataSource(this); // } // return mCachedHttpDataSource; // } // if (VkDataSource.KEY.equals(name)) { // //for android kitkat + // if (mVkDataSource == null) { // mVkDataSource = new VkDataSource(); // } // return mVkDataSource; // } // if (MySuperImageLoader.KEY.equals(name)) { // //for android kitkat + // if (mMySuperImageLoader == null) { // mMySuperImageLoader = new MySuperImageLoader(this); // } // return mMySuperImageLoader; // } // return super.getSystemService(name); // } // // public static <T> T get(Context context, String key) { // if (context == null || key == null){ // throw new IllegalArgumentException("Context and key must not be null"); // } // T systemService = (T) context.getSystemService(key); // if (systemService == null) { // context = context.getApplicationContext(); // systemService = (T) context.getSystemService(key); // } // if (systemService == null) { // throw new IllegalStateException(key + " not available"); // } // return systemService; // } // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/auth/VkOAuthHelper.java // public class VkOAuthHelper { // // public static interface Callbacks { // // void onError(Exception e); // // void onSuccess(); // // } // // //TODO don't do it in your project // private static String sToken; // // public static final String REDIRECT_URL = "https://oauth.vk.com/blank.html"; // public static final String AUTORIZATION_URL = "https://oauth.vk.com/authorize?client_id=4611084&scope=offline,wall,photos,status&redirect_uri=" + REDIRECT_URL + "&display=touch&response_type=token"; // private static final String TAG = VkOAuthHelper.class.getSimpleName(); // // public static String sign(String url) { // if (url.contains("?")) { // return url + "&access_token="+sToken; // } else { // return url + "?access_token="+sToken; // } // } // // public static boolean isLogged() { // return !TextUtils.isEmpty(sToken); // } // // public static boolean proceedRedirectURL(Activity activity, String url, Callbacks callbacks) { // if (url.startsWith(REDIRECT_URL)) { // Uri uri = Uri.parse(url); // String fragment = uri.getFragment(); // Uri parsedFragment = Uri.parse("http://temp.com?" + fragment); // String accessToken = parsedFragment.getQueryParameter("access_token"); // if (!TextUtils.isEmpty(accessToken)) { // //TODO save sToken to the secure store // //TODO create account in account manager // Log.d(TAG, "token " + accessToken); // sToken = accessToken; // callbacks.onSuccess(); // return true; // } else { // String error = parsedFragment.getQueryParameter("error"); // String errorDescription = parsedFragment.getQueryParameter("error_description"); // String errorReason = parsedFragment.getQueryParameter("error_reason"); // if (!TextUtils.isEmpty(error)) { // callbacks.onError(new AuthenticationException(error+", reason : " + errorReason +"("+errorDescription+")")); // return false; // } else { // //WTF? // } // } // } // return false; // } // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/utils/AuthUtils.java // public class AuthUtils { // // public static boolean isLogged() { // return VkOAuthHelper.isLogged(); // } // // }
import android.content.Context; import android.net.Uri; import android.text.TextUtils; import com.epam.training.taskmanager.Api; import com.epam.training.taskmanager.CoreApplication; import com.epam.training.taskmanager.auth.VkOAuthHelper; import com.epam.training.taskmanager.utils.AuthUtils; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.net.URL;
package com.epam.training.taskmanager.source; /** * Created by IstiN on 17.10.2014. */ public class VkDataSource extends HttpDataSource { public static final String KEY = "VkDataSource"; public static VkDataSource get(Context context) { return CoreApplication.get(context, KEY); } @Override public InputStream getResult(String p) throws Exception {
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/Api.java // public class Api { // // public static final String BASE_PATH = "https://api.vk.com/method/"; // public static final String VERSION_VALUE = "5.8"; // public static final String VERSION_PARAM = "v"; // // public static final String FRIENDS_GET = BASE_PATH + "friends.get?fields=photo_200_orig,online,nickname"; // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/CoreApplication.java // public class CoreApplication extends Application { // // private HttpDataSource mHttpDataSource; // private CachedHttpDataSource mCachedHttpDataSource; // private VkDataSource mVkDataSource; // private MySuperImageLoader mMySuperImageLoader; // // @Override // public void onCreate() { // super.onCreate(); // mMySuperImageLoader = new MySuperImageLoader(this); // mHttpDataSource = new HttpDataSource(); // mVkDataSource = new VkDataSource(); // mCachedHttpDataSource = new CachedHttpDataSource(this); // } // // @Override // public Object getSystemService(String name) { // if (HttpDataSource.KEY.equals(name)) { // //for android kitkat + // if (mHttpDataSource == null) { // mHttpDataSource = new HttpDataSource(); // } // return mHttpDataSource; // } // if (CachedHttpDataSource.KEY.equals(name)) { // //for android kitkat + // if (mCachedHttpDataSource == null) { // mCachedHttpDataSource = new CachedHttpDataSource(this); // } // return mCachedHttpDataSource; // } // if (VkDataSource.KEY.equals(name)) { // //for android kitkat + // if (mVkDataSource == null) { // mVkDataSource = new VkDataSource(); // } // return mVkDataSource; // } // if (MySuperImageLoader.KEY.equals(name)) { // //for android kitkat + // if (mMySuperImageLoader == null) { // mMySuperImageLoader = new MySuperImageLoader(this); // } // return mMySuperImageLoader; // } // return super.getSystemService(name); // } // // public static <T> T get(Context context, String key) { // if (context == null || key == null){ // throw new IllegalArgumentException("Context and key must not be null"); // } // T systemService = (T) context.getSystemService(key); // if (systemService == null) { // context = context.getApplicationContext(); // systemService = (T) context.getSystemService(key); // } // if (systemService == null) { // throw new IllegalStateException(key + " not available"); // } // return systemService; // } // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/auth/VkOAuthHelper.java // public class VkOAuthHelper { // // public static interface Callbacks { // // void onError(Exception e); // // void onSuccess(); // // } // // //TODO don't do it in your project // private static String sToken; // // public static final String REDIRECT_URL = "https://oauth.vk.com/blank.html"; // public static final String AUTORIZATION_URL = "https://oauth.vk.com/authorize?client_id=4611084&scope=offline,wall,photos,status&redirect_uri=" + REDIRECT_URL + "&display=touch&response_type=token"; // private static final String TAG = VkOAuthHelper.class.getSimpleName(); // // public static String sign(String url) { // if (url.contains("?")) { // return url + "&access_token="+sToken; // } else { // return url + "?access_token="+sToken; // } // } // // public static boolean isLogged() { // return !TextUtils.isEmpty(sToken); // } // // public static boolean proceedRedirectURL(Activity activity, String url, Callbacks callbacks) { // if (url.startsWith(REDIRECT_URL)) { // Uri uri = Uri.parse(url); // String fragment = uri.getFragment(); // Uri parsedFragment = Uri.parse("http://temp.com?" + fragment); // String accessToken = parsedFragment.getQueryParameter("access_token"); // if (!TextUtils.isEmpty(accessToken)) { // //TODO save sToken to the secure store // //TODO create account in account manager // Log.d(TAG, "token " + accessToken); // sToken = accessToken; // callbacks.onSuccess(); // return true; // } else { // String error = parsedFragment.getQueryParameter("error"); // String errorDescription = parsedFragment.getQueryParameter("error_description"); // String errorReason = parsedFragment.getQueryParameter("error_reason"); // if (!TextUtils.isEmpty(error)) { // callbacks.onError(new AuthenticationException(error+", reason : " + errorReason +"("+errorDescription+")")); // return false; // } else { // //WTF? // } // } // } // return false; // } // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/utils/AuthUtils.java // public class AuthUtils { // // public static boolean isLogged() { // return VkOAuthHelper.isLogged(); // } // // } // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/source/VkDataSource.java import android.content.Context; import android.net.Uri; import android.text.TextUtils; import com.epam.training.taskmanager.Api; import com.epam.training.taskmanager.CoreApplication; import com.epam.training.taskmanager.auth.VkOAuthHelper; import com.epam.training.taskmanager.utils.AuthUtils; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.net.URL; package com.epam.training.taskmanager.source; /** * Created by IstiN on 17.10.2014. */ public class VkDataSource extends HttpDataSource { public static final String KEY = "VkDataSource"; public static VkDataSource get(Context context) { return CoreApplication.get(context, KEY); } @Override public InputStream getResult(String p) throws Exception {
String signUrl = VkOAuthHelper.sign(p);
IstiN/android_training_2014
task_manager/app/src/main/java/com/epam/training/taskmanager/source/VkDataSource.java
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/Api.java // public class Api { // // public static final String BASE_PATH = "https://api.vk.com/method/"; // public static final String VERSION_VALUE = "5.8"; // public static final String VERSION_PARAM = "v"; // // public static final String FRIENDS_GET = BASE_PATH + "friends.get?fields=photo_200_orig,online,nickname"; // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/CoreApplication.java // public class CoreApplication extends Application { // // private HttpDataSource mHttpDataSource; // private CachedHttpDataSource mCachedHttpDataSource; // private VkDataSource mVkDataSource; // private MySuperImageLoader mMySuperImageLoader; // // @Override // public void onCreate() { // super.onCreate(); // mMySuperImageLoader = new MySuperImageLoader(this); // mHttpDataSource = new HttpDataSource(); // mVkDataSource = new VkDataSource(); // mCachedHttpDataSource = new CachedHttpDataSource(this); // } // // @Override // public Object getSystemService(String name) { // if (HttpDataSource.KEY.equals(name)) { // //for android kitkat + // if (mHttpDataSource == null) { // mHttpDataSource = new HttpDataSource(); // } // return mHttpDataSource; // } // if (CachedHttpDataSource.KEY.equals(name)) { // //for android kitkat + // if (mCachedHttpDataSource == null) { // mCachedHttpDataSource = new CachedHttpDataSource(this); // } // return mCachedHttpDataSource; // } // if (VkDataSource.KEY.equals(name)) { // //for android kitkat + // if (mVkDataSource == null) { // mVkDataSource = new VkDataSource(); // } // return mVkDataSource; // } // if (MySuperImageLoader.KEY.equals(name)) { // //for android kitkat + // if (mMySuperImageLoader == null) { // mMySuperImageLoader = new MySuperImageLoader(this); // } // return mMySuperImageLoader; // } // return super.getSystemService(name); // } // // public static <T> T get(Context context, String key) { // if (context == null || key == null){ // throw new IllegalArgumentException("Context and key must not be null"); // } // T systemService = (T) context.getSystemService(key); // if (systemService == null) { // context = context.getApplicationContext(); // systemService = (T) context.getSystemService(key); // } // if (systemService == null) { // throw new IllegalStateException(key + " not available"); // } // return systemService; // } // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/auth/VkOAuthHelper.java // public class VkOAuthHelper { // // public static interface Callbacks { // // void onError(Exception e); // // void onSuccess(); // // } // // //TODO don't do it in your project // private static String sToken; // // public static final String REDIRECT_URL = "https://oauth.vk.com/blank.html"; // public static final String AUTORIZATION_URL = "https://oauth.vk.com/authorize?client_id=4611084&scope=offline,wall,photos,status&redirect_uri=" + REDIRECT_URL + "&display=touch&response_type=token"; // private static final String TAG = VkOAuthHelper.class.getSimpleName(); // // public static String sign(String url) { // if (url.contains("?")) { // return url + "&access_token="+sToken; // } else { // return url + "?access_token="+sToken; // } // } // // public static boolean isLogged() { // return !TextUtils.isEmpty(sToken); // } // // public static boolean proceedRedirectURL(Activity activity, String url, Callbacks callbacks) { // if (url.startsWith(REDIRECT_URL)) { // Uri uri = Uri.parse(url); // String fragment = uri.getFragment(); // Uri parsedFragment = Uri.parse("http://temp.com?" + fragment); // String accessToken = parsedFragment.getQueryParameter("access_token"); // if (!TextUtils.isEmpty(accessToken)) { // //TODO save sToken to the secure store // //TODO create account in account manager // Log.d(TAG, "token " + accessToken); // sToken = accessToken; // callbacks.onSuccess(); // return true; // } else { // String error = parsedFragment.getQueryParameter("error"); // String errorDescription = parsedFragment.getQueryParameter("error_description"); // String errorReason = parsedFragment.getQueryParameter("error_reason"); // if (!TextUtils.isEmpty(error)) { // callbacks.onError(new AuthenticationException(error+", reason : " + errorReason +"("+errorDescription+")")); // return false; // } else { // //WTF? // } // } // } // return false; // } // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/utils/AuthUtils.java // public class AuthUtils { // // public static boolean isLogged() { // return VkOAuthHelper.isLogged(); // } // // }
import android.content.Context; import android.net.Uri; import android.text.TextUtils; import com.epam.training.taskmanager.Api; import com.epam.training.taskmanager.CoreApplication; import com.epam.training.taskmanager.auth.VkOAuthHelper; import com.epam.training.taskmanager.utils.AuthUtils; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.net.URL;
package com.epam.training.taskmanager.source; /** * Created by IstiN on 17.10.2014. */ public class VkDataSource extends HttpDataSource { public static final String KEY = "VkDataSource"; public static VkDataSource get(Context context) { return CoreApplication.get(context, KEY); } @Override public InputStream getResult(String p) throws Exception { String signUrl = VkOAuthHelper.sign(p);
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/Api.java // public class Api { // // public static final String BASE_PATH = "https://api.vk.com/method/"; // public static final String VERSION_VALUE = "5.8"; // public static final String VERSION_PARAM = "v"; // // public static final String FRIENDS_GET = BASE_PATH + "friends.get?fields=photo_200_orig,online,nickname"; // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/CoreApplication.java // public class CoreApplication extends Application { // // private HttpDataSource mHttpDataSource; // private CachedHttpDataSource mCachedHttpDataSource; // private VkDataSource mVkDataSource; // private MySuperImageLoader mMySuperImageLoader; // // @Override // public void onCreate() { // super.onCreate(); // mMySuperImageLoader = new MySuperImageLoader(this); // mHttpDataSource = new HttpDataSource(); // mVkDataSource = new VkDataSource(); // mCachedHttpDataSource = new CachedHttpDataSource(this); // } // // @Override // public Object getSystemService(String name) { // if (HttpDataSource.KEY.equals(name)) { // //for android kitkat + // if (mHttpDataSource == null) { // mHttpDataSource = new HttpDataSource(); // } // return mHttpDataSource; // } // if (CachedHttpDataSource.KEY.equals(name)) { // //for android kitkat + // if (mCachedHttpDataSource == null) { // mCachedHttpDataSource = new CachedHttpDataSource(this); // } // return mCachedHttpDataSource; // } // if (VkDataSource.KEY.equals(name)) { // //for android kitkat + // if (mVkDataSource == null) { // mVkDataSource = new VkDataSource(); // } // return mVkDataSource; // } // if (MySuperImageLoader.KEY.equals(name)) { // //for android kitkat + // if (mMySuperImageLoader == null) { // mMySuperImageLoader = new MySuperImageLoader(this); // } // return mMySuperImageLoader; // } // return super.getSystemService(name); // } // // public static <T> T get(Context context, String key) { // if (context == null || key == null){ // throw new IllegalArgumentException("Context and key must not be null"); // } // T systemService = (T) context.getSystemService(key); // if (systemService == null) { // context = context.getApplicationContext(); // systemService = (T) context.getSystemService(key); // } // if (systemService == null) { // throw new IllegalStateException(key + " not available"); // } // return systemService; // } // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/auth/VkOAuthHelper.java // public class VkOAuthHelper { // // public static interface Callbacks { // // void onError(Exception e); // // void onSuccess(); // // } // // //TODO don't do it in your project // private static String sToken; // // public static final String REDIRECT_URL = "https://oauth.vk.com/blank.html"; // public static final String AUTORIZATION_URL = "https://oauth.vk.com/authorize?client_id=4611084&scope=offline,wall,photos,status&redirect_uri=" + REDIRECT_URL + "&display=touch&response_type=token"; // private static final String TAG = VkOAuthHelper.class.getSimpleName(); // // public static String sign(String url) { // if (url.contains("?")) { // return url + "&access_token="+sToken; // } else { // return url + "?access_token="+sToken; // } // } // // public static boolean isLogged() { // return !TextUtils.isEmpty(sToken); // } // // public static boolean proceedRedirectURL(Activity activity, String url, Callbacks callbacks) { // if (url.startsWith(REDIRECT_URL)) { // Uri uri = Uri.parse(url); // String fragment = uri.getFragment(); // Uri parsedFragment = Uri.parse("http://temp.com?" + fragment); // String accessToken = parsedFragment.getQueryParameter("access_token"); // if (!TextUtils.isEmpty(accessToken)) { // //TODO save sToken to the secure store // //TODO create account in account manager // Log.d(TAG, "token " + accessToken); // sToken = accessToken; // callbacks.onSuccess(); // return true; // } else { // String error = parsedFragment.getQueryParameter("error"); // String errorDescription = parsedFragment.getQueryParameter("error_description"); // String errorReason = parsedFragment.getQueryParameter("error_reason"); // if (!TextUtils.isEmpty(error)) { // callbacks.onError(new AuthenticationException(error+", reason : " + errorReason +"("+errorDescription+")")); // return false; // } else { // //WTF? // } // } // } // return false; // } // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/utils/AuthUtils.java // public class AuthUtils { // // public static boolean isLogged() { // return VkOAuthHelper.isLogged(); // } // // } // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/source/VkDataSource.java import android.content.Context; import android.net.Uri; import android.text.TextUtils; import com.epam.training.taskmanager.Api; import com.epam.training.taskmanager.CoreApplication; import com.epam.training.taskmanager.auth.VkOAuthHelper; import com.epam.training.taskmanager.utils.AuthUtils; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.net.URL; package com.epam.training.taskmanager.source; /** * Created by IstiN on 17.10.2014. */ public class VkDataSource extends HttpDataSource { public static final String KEY = "VkDataSource"; public static VkDataSource get(Context context) { return CoreApplication.get(context, KEY); } @Override public InputStream getResult(String p) throws Exception { String signUrl = VkOAuthHelper.sign(p);
String versionValue = Uri.parse(signUrl).getQueryParameter(Api.VERSION_PARAM);
IstiN/android_training_2014
task_manager/app/src/main/java/com/epam/training/taskmanager/os/AsyncTask.java
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/os/assist/LIFOLinkedBlockingDeque.java // public class LIFOLinkedBlockingDeque<T> extends LinkedBlockingDeque<T> { // private static final long serialVersionUID = -4114786347960826192L; // // /** // * Inserts the specified element at the front of this deque if it is possible to do so immediately without violating // * capacity restrictions, returning <tt>true</tt> upon success and <tt>false</tt> if no space is currently // * available. When using a capacity-restricted deque, this method is generally preferable to the {@link #addFirst // * addFirst} method, which can fail to insert an element only by throwing an exception. // * // * @param e // * the element to add // * @throws ClassCastException // * {@inheritDoc} // * @throws NullPointerException // * if the specified element is null // * @throws IllegalArgumentException // * {@inheritDoc} // */ // @Override // public boolean offer(T e) { // return super.offerFirst(e); // } // // /** // * Retrieves and removes the first element of this deque. This method differs from {@link #pollFirst pollFirst} only // * in that it throws an exception if this deque is empty. // * // * @return the head of this deque // * @throws java.util.NoSuchElementException // * if this deque is empty // */ // @Override // public T remove() { // return super.removeFirst(); // } // }
import android.os.Handler; import com.epam.training.taskmanager.os.assist.LIFOLinkedBlockingDeque; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit;
package com.epam.training.taskmanager.os; /** * Created by IstiN on 24.10.2014. */ public abstract class AsyncTask<Params, Progress, Result> { private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors(); private static final ExecutorService sExecutor; static {
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/os/assist/LIFOLinkedBlockingDeque.java // public class LIFOLinkedBlockingDeque<T> extends LinkedBlockingDeque<T> { // private static final long serialVersionUID = -4114786347960826192L; // // /** // * Inserts the specified element at the front of this deque if it is possible to do so immediately without violating // * capacity restrictions, returning <tt>true</tt> upon success and <tt>false</tt> if no space is currently // * available. When using a capacity-restricted deque, this method is generally preferable to the {@link #addFirst // * addFirst} method, which can fail to insert an element only by throwing an exception. // * // * @param e // * the element to add // * @throws ClassCastException // * {@inheritDoc} // * @throws NullPointerException // * if the specified element is null // * @throws IllegalArgumentException // * {@inheritDoc} // */ // @Override // public boolean offer(T e) { // return super.offerFirst(e); // } // // /** // * Retrieves and removes the first element of this deque. This method differs from {@link #pollFirst pollFirst} only // * in that it throws an exception if this deque is empty. // * // * @return the head of this deque // * @throws java.util.NoSuchElementException // * if this deque is empty // */ // @Override // public T remove() { // return super.removeFirst(); // } // } // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/os/AsyncTask.java import android.os.Handler; import com.epam.training.taskmanager.os.assist.LIFOLinkedBlockingDeque; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; package com.epam.training.taskmanager.os; /** * Created by IstiN on 24.10.2014. */ public abstract class AsyncTask<Params, Progress, Result> { private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors(); private static final ExecutorService sExecutor; static {
sExecutor = new ThreadPoolExecutor(CPU_COUNT, CPU_COUNT, 0L, TimeUnit.MILLISECONDS, new LIFOLinkedBlockingDeque<Runnable>());
IstiN/android_training_2014
task_manager/app/src/main/java/com/epam/training/taskmanager/processing/StringProcessor.java
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/source/HttpDataSource.java // public class HttpDataSource implements DataSource<InputStream, String> { // // public static final String KEY = "HttpDataSource"; // // public static HttpDataSource get(Context context) { // return CoreApplication.get(context, KEY); // } // // @Override // public InputStream getResult(String p) throws Exception { // //download data and return // URL url = new URL(p); // // Read all the text returned by the server // InputStream inputStream = url.openStream(); // return inputStream; // } // // public static void close(Closeable in) { // if (in != null) { // try { // in.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // }
import com.epam.training.taskmanager.source.HttpDataSource; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader;
package com.epam.training.taskmanager.processing; /** * Created by IstiN on 17.10.2014. */ public class StringProcessor implements Processor<String, InputStream> { @Override public String process(InputStream inputStream) throws Exception { InputStreamReader inputStreamReader = null; BufferedReader in = null; try { inputStreamReader = new InputStreamReader(inputStream); in = new BufferedReader(inputStreamReader); String str; StringBuilder builder = new StringBuilder(); while ((str = in.readLine()) != null) { builder.append(str); } return builder.toString(); } finally {
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/source/HttpDataSource.java // public class HttpDataSource implements DataSource<InputStream, String> { // // public static final String KEY = "HttpDataSource"; // // public static HttpDataSource get(Context context) { // return CoreApplication.get(context, KEY); // } // // @Override // public InputStream getResult(String p) throws Exception { // //download data and return // URL url = new URL(p); // // Read all the text returned by the server // InputStream inputStream = url.openStream(); // return inputStream; // } // // public static void close(Closeable in) { // if (in != null) { // try { // in.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // } // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/processing/StringProcessor.java import com.epam.training.taskmanager.source.HttpDataSource; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; package com.epam.training.taskmanager.processing; /** * Created by IstiN on 17.10.2014. */ public class StringProcessor implements Processor<String, InputStream> { @Override public String process(InputStream inputStream) throws Exception { InputStreamReader inputStreamReader = null; BufferedReader in = null; try { inputStreamReader = new InputStreamReader(inputStream); in = new BufferedReader(inputStreamReader); String str; StringBuilder builder = new StringBuilder(); while ((str = in.readLine()) != null) { builder.append(str); } return builder.toString(); } finally {
HttpDataSource.close(in);
IstiN/android_training_2014
task_manager/app/src/main/java/com/epam/training/taskmanager/LoginActivity.java
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/auth/secure/EncrManager.java // public class EncrManager { // // public static final String ENCODING = "UTF8"; // public static final String DES = "DES"; // // // public static String encrypt(final Context context, final String value) throws Exception { // String sourceKey = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID); // Toast.makeText(context, sourceKey, Toast.LENGTH_SHORT).show(); // byte[] bytesKey = sourceKey.getBytes(ENCODING); // final DESKeySpec keySpec = new DESKeySpec(bytesKey); // final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); // final SecretKey key = keyFactory.generateSecret(keySpec); // final byte[] text = value.getBytes(ENCODING); // final Cipher cipher = Cipher.getInstance(DES); // cipher.init(Cipher.ENCRYPT_MODE, key); // return Base64.encodeToString(cipher.doFinal(text), Base64.DEFAULT); // // } // // public static String decrypt(final Context context, final String value) throws Exception { // String sourceKey = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID); // Toast.makeText(context, sourceKey, Toast.LENGTH_SHORT).show(); // byte[] bytesKey = sourceKey.getBytes(ENCODING); // final DESKeySpec keySpec = new DESKeySpec(bytesKey); // final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); // final SecretKey key = keyFactory.generateSecret(keySpec); // final byte[] encrypedBytes = Base64.decode(value, Base64.DEFAULT); // final Cipher cipher = Cipher.getInstance(DES); // cipher.init(Cipher.DECRYPT_MODE, key); // final byte[] plainTextBytes = cipher.doFinal(encrypedBytes); // return new String(plainTextBytes); // } // // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/helper/ConcurrencySampleHelper.java // public class ConcurrencySampleHelper { // // public static void success() { // final List<String> array = new CopyOnWriteArrayList<String>(); // generateTestValues(array); // concurrencyThreadTest(array); // } // // public static void success2() { // final List<String> array = new ArrayList<String>(); // generateTestValues(array); // concurrencyThreadTestWithLock(array); // } // // public static void fail() { // final List<String> array = new ArrayList<String>(); // generateTestValues(array); // concurrencyThreadTest(array); // } // // private static void generateTestValues(List<String> array) { // for (int i = 0; i < 10; i++) { // generateNewValue(array); // } // } // // private static void concurrencyThreadTest(final List<String> array) { // new Thread(new Runnable() { // @Override // public void run() { // for (String value : array) { // try { // Log.d("concurrent", "foreach array size " + array.size()); // Thread.currentThread().sleep(700l); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // } // }).start(); // new Thread(new Runnable() { // @Override // public void run() { // try { // Thread.currentThread().sleep(500l); // } catch (InterruptedException e) { // e.printStackTrace(); // } // generateNewValue(array); // Log.d("concurrent", "new value array size " + array.size()); // } // }).start(); // } // // private static void concurrencyThreadTestWithLock(final List<String> array) { // final Object lock = new Object(); // new Thread(new Runnable() { // @Override // public void run() { // synchronized (lock) { // for (String value : array) { // try { // Log.d("concurrent", "foreach array size " + array.size()); // Thread.currentThread().sleep(700l); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // } // } // }).start(); // new Thread(new Runnable() { // @Override // public void run() { // try { // Thread.currentThread().sleep(500l); // } catch (InterruptedException e) { // e.printStackTrace(); // } // synchronized (lock) { // generateNewValue(array); // } // Log.d("concurrent", "new value array size " + array.size()); // } // }).start(); // } // // private static void generateNewValue(List<String> array) { // array.add(UUID.randomUUID().toString()); // } // // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/utils/AuthUtils.java // public class AuthUtils { // // public static boolean isLogged() { // return VkOAuthHelper.isLogged(); // } // // }
import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.epam.training.taskmanager.auth.secure.EncrManager; import com.epam.training.taskmanager.helper.ConcurrencySampleHelper; import com.epam.training.taskmanager.utils.AuthUtils; import java.util.concurrent.ConcurrentMap;
package com.epam.training.taskmanager; public class LoginActivity extends ActionBarActivity { public static final int REQUEST_CODE_VK = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); Button cancelBtn = (Button) findViewById(R.id.cancel_btn); cancelBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); } public void onConcurrencyFailClick(View view) {
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/auth/secure/EncrManager.java // public class EncrManager { // // public static final String ENCODING = "UTF8"; // public static final String DES = "DES"; // // // public static String encrypt(final Context context, final String value) throws Exception { // String sourceKey = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID); // Toast.makeText(context, sourceKey, Toast.LENGTH_SHORT).show(); // byte[] bytesKey = sourceKey.getBytes(ENCODING); // final DESKeySpec keySpec = new DESKeySpec(bytesKey); // final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); // final SecretKey key = keyFactory.generateSecret(keySpec); // final byte[] text = value.getBytes(ENCODING); // final Cipher cipher = Cipher.getInstance(DES); // cipher.init(Cipher.ENCRYPT_MODE, key); // return Base64.encodeToString(cipher.doFinal(text), Base64.DEFAULT); // // } // // public static String decrypt(final Context context, final String value) throws Exception { // String sourceKey = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID); // Toast.makeText(context, sourceKey, Toast.LENGTH_SHORT).show(); // byte[] bytesKey = sourceKey.getBytes(ENCODING); // final DESKeySpec keySpec = new DESKeySpec(bytesKey); // final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); // final SecretKey key = keyFactory.generateSecret(keySpec); // final byte[] encrypedBytes = Base64.decode(value, Base64.DEFAULT); // final Cipher cipher = Cipher.getInstance(DES); // cipher.init(Cipher.DECRYPT_MODE, key); // final byte[] plainTextBytes = cipher.doFinal(encrypedBytes); // return new String(plainTextBytes); // } // // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/helper/ConcurrencySampleHelper.java // public class ConcurrencySampleHelper { // // public static void success() { // final List<String> array = new CopyOnWriteArrayList<String>(); // generateTestValues(array); // concurrencyThreadTest(array); // } // // public static void success2() { // final List<String> array = new ArrayList<String>(); // generateTestValues(array); // concurrencyThreadTestWithLock(array); // } // // public static void fail() { // final List<String> array = new ArrayList<String>(); // generateTestValues(array); // concurrencyThreadTest(array); // } // // private static void generateTestValues(List<String> array) { // for (int i = 0; i < 10; i++) { // generateNewValue(array); // } // } // // private static void concurrencyThreadTest(final List<String> array) { // new Thread(new Runnable() { // @Override // public void run() { // for (String value : array) { // try { // Log.d("concurrent", "foreach array size " + array.size()); // Thread.currentThread().sleep(700l); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // } // }).start(); // new Thread(new Runnable() { // @Override // public void run() { // try { // Thread.currentThread().sleep(500l); // } catch (InterruptedException e) { // e.printStackTrace(); // } // generateNewValue(array); // Log.d("concurrent", "new value array size " + array.size()); // } // }).start(); // } // // private static void concurrencyThreadTestWithLock(final List<String> array) { // final Object lock = new Object(); // new Thread(new Runnable() { // @Override // public void run() { // synchronized (lock) { // for (String value : array) { // try { // Log.d("concurrent", "foreach array size " + array.size()); // Thread.currentThread().sleep(700l); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // } // } // }).start(); // new Thread(new Runnable() { // @Override // public void run() { // try { // Thread.currentThread().sleep(500l); // } catch (InterruptedException e) { // e.printStackTrace(); // } // synchronized (lock) { // generateNewValue(array); // } // Log.d("concurrent", "new value array size " + array.size()); // } // }).start(); // } // // private static void generateNewValue(List<String> array) { // array.add(UUID.randomUUID().toString()); // } // // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/utils/AuthUtils.java // public class AuthUtils { // // public static boolean isLogged() { // return VkOAuthHelper.isLogged(); // } // // } // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/LoginActivity.java import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.epam.training.taskmanager.auth.secure.EncrManager; import com.epam.training.taskmanager.helper.ConcurrencySampleHelper; import com.epam.training.taskmanager.utils.AuthUtils; import java.util.concurrent.ConcurrentMap; package com.epam.training.taskmanager; public class LoginActivity extends ActionBarActivity { public static final int REQUEST_CODE_VK = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); Button cancelBtn = (Button) findViewById(R.id.cancel_btn); cancelBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); } public void onConcurrencyFailClick(View view) {
ConcurrencySampleHelper.fail();
IstiN/android_training_2014
task_manager/app/src/main/java/com/epam/training/taskmanager/LoginActivity.java
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/auth/secure/EncrManager.java // public class EncrManager { // // public static final String ENCODING = "UTF8"; // public static final String DES = "DES"; // // // public static String encrypt(final Context context, final String value) throws Exception { // String sourceKey = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID); // Toast.makeText(context, sourceKey, Toast.LENGTH_SHORT).show(); // byte[] bytesKey = sourceKey.getBytes(ENCODING); // final DESKeySpec keySpec = new DESKeySpec(bytesKey); // final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); // final SecretKey key = keyFactory.generateSecret(keySpec); // final byte[] text = value.getBytes(ENCODING); // final Cipher cipher = Cipher.getInstance(DES); // cipher.init(Cipher.ENCRYPT_MODE, key); // return Base64.encodeToString(cipher.doFinal(text), Base64.DEFAULT); // // } // // public static String decrypt(final Context context, final String value) throws Exception { // String sourceKey = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID); // Toast.makeText(context, sourceKey, Toast.LENGTH_SHORT).show(); // byte[] bytesKey = sourceKey.getBytes(ENCODING); // final DESKeySpec keySpec = new DESKeySpec(bytesKey); // final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); // final SecretKey key = keyFactory.generateSecret(keySpec); // final byte[] encrypedBytes = Base64.decode(value, Base64.DEFAULT); // final Cipher cipher = Cipher.getInstance(DES); // cipher.init(Cipher.DECRYPT_MODE, key); // final byte[] plainTextBytes = cipher.doFinal(encrypedBytes); // return new String(plainTextBytes); // } // // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/helper/ConcurrencySampleHelper.java // public class ConcurrencySampleHelper { // // public static void success() { // final List<String> array = new CopyOnWriteArrayList<String>(); // generateTestValues(array); // concurrencyThreadTest(array); // } // // public static void success2() { // final List<String> array = new ArrayList<String>(); // generateTestValues(array); // concurrencyThreadTestWithLock(array); // } // // public static void fail() { // final List<String> array = new ArrayList<String>(); // generateTestValues(array); // concurrencyThreadTest(array); // } // // private static void generateTestValues(List<String> array) { // for (int i = 0; i < 10; i++) { // generateNewValue(array); // } // } // // private static void concurrencyThreadTest(final List<String> array) { // new Thread(new Runnable() { // @Override // public void run() { // for (String value : array) { // try { // Log.d("concurrent", "foreach array size " + array.size()); // Thread.currentThread().sleep(700l); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // } // }).start(); // new Thread(new Runnable() { // @Override // public void run() { // try { // Thread.currentThread().sleep(500l); // } catch (InterruptedException e) { // e.printStackTrace(); // } // generateNewValue(array); // Log.d("concurrent", "new value array size " + array.size()); // } // }).start(); // } // // private static void concurrencyThreadTestWithLock(final List<String> array) { // final Object lock = new Object(); // new Thread(new Runnable() { // @Override // public void run() { // synchronized (lock) { // for (String value : array) { // try { // Log.d("concurrent", "foreach array size " + array.size()); // Thread.currentThread().sleep(700l); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // } // } // }).start(); // new Thread(new Runnable() { // @Override // public void run() { // try { // Thread.currentThread().sleep(500l); // } catch (InterruptedException e) { // e.printStackTrace(); // } // synchronized (lock) { // generateNewValue(array); // } // Log.d("concurrent", "new value array size " + array.size()); // } // }).start(); // } // // private static void generateNewValue(List<String> array) { // array.add(UUID.randomUUID().toString()); // } // // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/utils/AuthUtils.java // public class AuthUtils { // // public static boolean isLogged() { // return VkOAuthHelper.isLogged(); // } // // }
import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.epam.training.taskmanager.auth.secure.EncrManager; import com.epam.training.taskmanager.helper.ConcurrencySampleHelper; import com.epam.training.taskmanager.utils.AuthUtils; import java.util.concurrent.ConcurrentMap;
} }); } public void onConcurrencyFailClick(View view) { ConcurrencySampleHelper.fail(); } public void onConcurrencySuccessClick(View view) { ConcurrencySampleHelper.success(); } public void onConcurrencySuccess2Click(View view) { ConcurrencySampleHelper.success2(); } public void onLoginClick(View view) { Toast.makeText(this, "implement me", Toast.LENGTH_SHORT).show(); } public void onFragmentsClick(View view) { startActivity(new Intent(this, FragmentLayoutSupportActivity.class)); } private String mSomeSecureString; public void onEncrDecrClick(View view) { if (mSomeSecureString == null) { EditText editText = (EditText) findViewById(R.id.password); try {
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/auth/secure/EncrManager.java // public class EncrManager { // // public static final String ENCODING = "UTF8"; // public static final String DES = "DES"; // // // public static String encrypt(final Context context, final String value) throws Exception { // String sourceKey = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID); // Toast.makeText(context, sourceKey, Toast.LENGTH_SHORT).show(); // byte[] bytesKey = sourceKey.getBytes(ENCODING); // final DESKeySpec keySpec = new DESKeySpec(bytesKey); // final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); // final SecretKey key = keyFactory.generateSecret(keySpec); // final byte[] text = value.getBytes(ENCODING); // final Cipher cipher = Cipher.getInstance(DES); // cipher.init(Cipher.ENCRYPT_MODE, key); // return Base64.encodeToString(cipher.doFinal(text), Base64.DEFAULT); // // } // // public static String decrypt(final Context context, final String value) throws Exception { // String sourceKey = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID); // Toast.makeText(context, sourceKey, Toast.LENGTH_SHORT).show(); // byte[] bytesKey = sourceKey.getBytes(ENCODING); // final DESKeySpec keySpec = new DESKeySpec(bytesKey); // final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); // final SecretKey key = keyFactory.generateSecret(keySpec); // final byte[] encrypedBytes = Base64.decode(value, Base64.DEFAULT); // final Cipher cipher = Cipher.getInstance(DES); // cipher.init(Cipher.DECRYPT_MODE, key); // final byte[] plainTextBytes = cipher.doFinal(encrypedBytes); // return new String(plainTextBytes); // } // // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/helper/ConcurrencySampleHelper.java // public class ConcurrencySampleHelper { // // public static void success() { // final List<String> array = new CopyOnWriteArrayList<String>(); // generateTestValues(array); // concurrencyThreadTest(array); // } // // public static void success2() { // final List<String> array = new ArrayList<String>(); // generateTestValues(array); // concurrencyThreadTestWithLock(array); // } // // public static void fail() { // final List<String> array = new ArrayList<String>(); // generateTestValues(array); // concurrencyThreadTest(array); // } // // private static void generateTestValues(List<String> array) { // for (int i = 0; i < 10; i++) { // generateNewValue(array); // } // } // // private static void concurrencyThreadTest(final List<String> array) { // new Thread(new Runnable() { // @Override // public void run() { // for (String value : array) { // try { // Log.d("concurrent", "foreach array size " + array.size()); // Thread.currentThread().sleep(700l); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // } // }).start(); // new Thread(new Runnable() { // @Override // public void run() { // try { // Thread.currentThread().sleep(500l); // } catch (InterruptedException e) { // e.printStackTrace(); // } // generateNewValue(array); // Log.d("concurrent", "new value array size " + array.size()); // } // }).start(); // } // // private static void concurrencyThreadTestWithLock(final List<String> array) { // final Object lock = new Object(); // new Thread(new Runnable() { // @Override // public void run() { // synchronized (lock) { // for (String value : array) { // try { // Log.d("concurrent", "foreach array size " + array.size()); // Thread.currentThread().sleep(700l); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // } // } // }).start(); // new Thread(new Runnable() { // @Override // public void run() { // try { // Thread.currentThread().sleep(500l); // } catch (InterruptedException e) { // e.printStackTrace(); // } // synchronized (lock) { // generateNewValue(array); // } // Log.d("concurrent", "new value array size " + array.size()); // } // }).start(); // } // // private static void generateNewValue(List<String> array) { // array.add(UUID.randomUUID().toString()); // } // // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/utils/AuthUtils.java // public class AuthUtils { // // public static boolean isLogged() { // return VkOAuthHelper.isLogged(); // } // // } // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/LoginActivity.java import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.epam.training.taskmanager.auth.secure.EncrManager; import com.epam.training.taskmanager.helper.ConcurrencySampleHelper; import com.epam.training.taskmanager.utils.AuthUtils; import java.util.concurrent.ConcurrentMap; } }); } public void onConcurrencyFailClick(View view) { ConcurrencySampleHelper.fail(); } public void onConcurrencySuccessClick(View view) { ConcurrencySampleHelper.success(); } public void onConcurrencySuccess2Click(View view) { ConcurrencySampleHelper.success2(); } public void onLoginClick(View view) { Toast.makeText(this, "implement me", Toast.LENGTH_SHORT).show(); } public void onFragmentsClick(View view) { startActivity(new Intent(this, FragmentLayoutSupportActivity.class)); } private String mSomeSecureString; public void onEncrDecrClick(View view) { if (mSomeSecureString == null) { EditText editText = (EditText) findViewById(R.id.password); try {
mSomeSecureString = EncrManager.encrypt(this, editText.getText().toString());
IstiN/android_training_2014
task_manager/app/src/main/java/com/epam/training/taskmanager/source/HttpDataSource.java
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/CoreApplication.java // public class CoreApplication extends Application { // // private HttpDataSource mHttpDataSource; // private CachedHttpDataSource mCachedHttpDataSource; // private VkDataSource mVkDataSource; // private MySuperImageLoader mMySuperImageLoader; // // @Override // public void onCreate() { // super.onCreate(); // mMySuperImageLoader = new MySuperImageLoader(this); // mHttpDataSource = new HttpDataSource(); // mVkDataSource = new VkDataSource(); // mCachedHttpDataSource = new CachedHttpDataSource(this); // } // // @Override // public Object getSystemService(String name) { // if (HttpDataSource.KEY.equals(name)) { // //for android kitkat + // if (mHttpDataSource == null) { // mHttpDataSource = new HttpDataSource(); // } // return mHttpDataSource; // } // if (CachedHttpDataSource.KEY.equals(name)) { // //for android kitkat + // if (mCachedHttpDataSource == null) { // mCachedHttpDataSource = new CachedHttpDataSource(this); // } // return mCachedHttpDataSource; // } // if (VkDataSource.KEY.equals(name)) { // //for android kitkat + // if (mVkDataSource == null) { // mVkDataSource = new VkDataSource(); // } // return mVkDataSource; // } // if (MySuperImageLoader.KEY.equals(name)) { // //for android kitkat + // if (mMySuperImageLoader == null) { // mMySuperImageLoader = new MySuperImageLoader(this); // } // return mMySuperImageLoader; // } // return super.getSystemService(name); // } // // public static <T> T get(Context context, String key) { // if (context == null || key == null){ // throw new IllegalArgumentException("Context and key must not be null"); // } // T systemService = (T) context.getSystemService(key); // if (systemService == null) { // context = context.getApplicationContext(); // systemService = (T) context.getSystemService(key); // } // if (systemService == null) { // throw new IllegalStateException(key + " not available"); // } // return systemService; // } // }
import android.content.Context; import com.epam.training.taskmanager.CoreApplication; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.net.URL;
package com.epam.training.taskmanager.source; /** * Created by IstiN on 17.10.2014. */ public class HttpDataSource implements DataSource<InputStream, String> { public static final String KEY = "HttpDataSource"; public static HttpDataSource get(Context context) {
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/CoreApplication.java // public class CoreApplication extends Application { // // private HttpDataSource mHttpDataSource; // private CachedHttpDataSource mCachedHttpDataSource; // private VkDataSource mVkDataSource; // private MySuperImageLoader mMySuperImageLoader; // // @Override // public void onCreate() { // super.onCreate(); // mMySuperImageLoader = new MySuperImageLoader(this); // mHttpDataSource = new HttpDataSource(); // mVkDataSource = new VkDataSource(); // mCachedHttpDataSource = new CachedHttpDataSource(this); // } // // @Override // public Object getSystemService(String name) { // if (HttpDataSource.KEY.equals(name)) { // //for android kitkat + // if (mHttpDataSource == null) { // mHttpDataSource = new HttpDataSource(); // } // return mHttpDataSource; // } // if (CachedHttpDataSource.KEY.equals(name)) { // //for android kitkat + // if (mCachedHttpDataSource == null) { // mCachedHttpDataSource = new CachedHttpDataSource(this); // } // return mCachedHttpDataSource; // } // if (VkDataSource.KEY.equals(name)) { // //for android kitkat + // if (mVkDataSource == null) { // mVkDataSource = new VkDataSource(); // } // return mVkDataSource; // } // if (MySuperImageLoader.KEY.equals(name)) { // //for android kitkat + // if (mMySuperImageLoader == null) { // mMySuperImageLoader = new MySuperImageLoader(this); // } // return mMySuperImageLoader; // } // return super.getSystemService(name); // } // // public static <T> T get(Context context, String key) { // if (context == null || key == null){ // throw new IllegalArgumentException("Context and key must not be null"); // } // T systemService = (T) context.getSystemService(key); // if (systemService == null) { // context = context.getApplicationContext(); // systemService = (T) context.getSystemService(key); // } // if (systemService == null) { // throw new IllegalStateException(key + " not available"); // } // return systemService; // } // } // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/source/HttpDataSource.java import android.content.Context; import com.epam.training.taskmanager.CoreApplication; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.net.URL; package com.epam.training.taskmanager.source; /** * Created by IstiN on 17.10.2014. */ public class HttpDataSource implements DataSource<InputStream, String> { public static final String KEY = "HttpDataSource"; public static HttpDataSource get(Context context) {
return CoreApplication.get(context, KEY);
IstiN/android_training_2014
task_manager/app/src/main/java/com/epam/training/taskmanager/StartActivity.java
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/service/ServiceResult.java // public class ServiceResult { // // public static final String KEY_RESULT_RECEIVER = "result_receiver"; // public static final String ACTION_EXECUTE_WITH_RESULT_RECEIVER = "action_executeWithResultReceiver"; // public static final String ACTION_EXECUTE_WITH_SERVICE_CONNECTION = "action_executeWithServiceConnection"; // // //BroadcastReceiver / local BroadcastReceiver // //Singleton/bus messaging // // public static void executeWithResultReceiver(Activity activity) { // Log.d(ACTION_EXECUTE_WITH_RESULT_RECEIVER, "executeWithResultReceiver"); // Intent serviceIntent = new Intent(activity, MyCoolService.class); // serviceIntent.setAction(ACTION_EXECUTE_WITH_RESULT_RECEIVER); // Handler handler = new Handler(); // ResultReceiver resultReceiver = new ResultReceiver(handler) { // @Override // protected void onReceiveResult(int resultCode, Bundle resultData) { // super.onReceiveResult(resultCode, resultData); // Log.d(ACTION_EXECUTE_WITH_RESULT_RECEIVER, resultCode + " " + resultData); // } // }; // serviceIntent.putExtra(KEY_RESULT_RECEIVER, resultReceiver); // activity.startService(serviceIntent); // } // // public static void executeWithServiceConnection(final Activity activity) { // Log.d(ACTION_EXECUTE_WITH_SERVICE_CONNECTION, "executeWithServiceConnection"); // final Intent serviceIntent = new Intent(activity, MyCoolService.class); // serviceIntent.setAction(ACTION_EXECUTE_WITH_SERVICE_CONNECTION); // activity.bindService(serviceIntent, new ServiceConnection() { // @Override // public void onServiceConnected(ComponentName name, IBinder service) { // Log.d(ACTION_EXECUTE_WITH_SERVICE_CONNECTION, "onServiceConnected"); // final MyCoolService myCoolService = ((MyCoolService.ServiceBinder<MyCoolService>) service).getService(); // myCoolService.addRunnable(new Runnable() { // @Override // public void run() { // Log.d(ACTION_EXECUTE_WITH_SERVICE_CONNECTION, "event "); // myCoolService.removeRunnable(this); // } // }); // activity.startService(serviceIntent); // //TODO make action // activity.unbindService(this); // } // // @Override // public void onServiceDisconnected(ComponentName name) { // Log.d(ACTION_EXECUTE_WITH_SERVICE_CONNECTION, "onServiceDisconnected"); // } // }, Context.BIND_AUTO_CREATE); // } // // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/utils/AuthUtils.java // public class AuthUtils { // // public static boolean isLogged() { // return VkOAuthHelper.isLogged(); // } // // }
import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import com.epam.training.taskmanager.service.ServiceResult; import com.epam.training.taskmanager.utils.AuthUtils;
package com.epam.training.taskmanager; public class StartActivity extends ActionBarActivity { public static final int REQUEST_LOGIN = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //ServiceResult.executeWithResultReceiver(this);
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/service/ServiceResult.java // public class ServiceResult { // // public static final String KEY_RESULT_RECEIVER = "result_receiver"; // public static final String ACTION_EXECUTE_WITH_RESULT_RECEIVER = "action_executeWithResultReceiver"; // public static final String ACTION_EXECUTE_WITH_SERVICE_CONNECTION = "action_executeWithServiceConnection"; // // //BroadcastReceiver / local BroadcastReceiver // //Singleton/bus messaging // // public static void executeWithResultReceiver(Activity activity) { // Log.d(ACTION_EXECUTE_WITH_RESULT_RECEIVER, "executeWithResultReceiver"); // Intent serviceIntent = new Intent(activity, MyCoolService.class); // serviceIntent.setAction(ACTION_EXECUTE_WITH_RESULT_RECEIVER); // Handler handler = new Handler(); // ResultReceiver resultReceiver = new ResultReceiver(handler) { // @Override // protected void onReceiveResult(int resultCode, Bundle resultData) { // super.onReceiveResult(resultCode, resultData); // Log.d(ACTION_EXECUTE_WITH_RESULT_RECEIVER, resultCode + " " + resultData); // } // }; // serviceIntent.putExtra(KEY_RESULT_RECEIVER, resultReceiver); // activity.startService(serviceIntent); // } // // public static void executeWithServiceConnection(final Activity activity) { // Log.d(ACTION_EXECUTE_WITH_SERVICE_CONNECTION, "executeWithServiceConnection"); // final Intent serviceIntent = new Intent(activity, MyCoolService.class); // serviceIntent.setAction(ACTION_EXECUTE_WITH_SERVICE_CONNECTION); // activity.bindService(serviceIntent, new ServiceConnection() { // @Override // public void onServiceConnected(ComponentName name, IBinder service) { // Log.d(ACTION_EXECUTE_WITH_SERVICE_CONNECTION, "onServiceConnected"); // final MyCoolService myCoolService = ((MyCoolService.ServiceBinder<MyCoolService>) service).getService(); // myCoolService.addRunnable(new Runnable() { // @Override // public void run() { // Log.d(ACTION_EXECUTE_WITH_SERVICE_CONNECTION, "event "); // myCoolService.removeRunnable(this); // } // }); // activity.startService(serviceIntent); // //TODO make action // activity.unbindService(this); // } // // @Override // public void onServiceDisconnected(ComponentName name) { // Log.d(ACTION_EXECUTE_WITH_SERVICE_CONNECTION, "onServiceDisconnected"); // } // }, Context.BIND_AUTO_CREATE); // } // // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/utils/AuthUtils.java // public class AuthUtils { // // public static boolean isLogged() { // return VkOAuthHelper.isLogged(); // } // // } // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/StartActivity.java import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import com.epam.training.taskmanager.service.ServiceResult; import com.epam.training.taskmanager.utils.AuthUtils; package com.epam.training.taskmanager; public class StartActivity extends ActionBarActivity { public static final int REQUEST_LOGIN = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //ServiceResult.executeWithResultReceiver(this);
ServiceResult.executeWithServiceConnection(this);
IstiN/android_training_2014
task_manager/app/src/main/java/com/epam/training/taskmanager/StartActivity.java
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/service/ServiceResult.java // public class ServiceResult { // // public static final String KEY_RESULT_RECEIVER = "result_receiver"; // public static final String ACTION_EXECUTE_WITH_RESULT_RECEIVER = "action_executeWithResultReceiver"; // public static final String ACTION_EXECUTE_WITH_SERVICE_CONNECTION = "action_executeWithServiceConnection"; // // //BroadcastReceiver / local BroadcastReceiver // //Singleton/bus messaging // // public static void executeWithResultReceiver(Activity activity) { // Log.d(ACTION_EXECUTE_WITH_RESULT_RECEIVER, "executeWithResultReceiver"); // Intent serviceIntent = new Intent(activity, MyCoolService.class); // serviceIntent.setAction(ACTION_EXECUTE_WITH_RESULT_RECEIVER); // Handler handler = new Handler(); // ResultReceiver resultReceiver = new ResultReceiver(handler) { // @Override // protected void onReceiveResult(int resultCode, Bundle resultData) { // super.onReceiveResult(resultCode, resultData); // Log.d(ACTION_EXECUTE_WITH_RESULT_RECEIVER, resultCode + " " + resultData); // } // }; // serviceIntent.putExtra(KEY_RESULT_RECEIVER, resultReceiver); // activity.startService(serviceIntent); // } // // public static void executeWithServiceConnection(final Activity activity) { // Log.d(ACTION_EXECUTE_WITH_SERVICE_CONNECTION, "executeWithServiceConnection"); // final Intent serviceIntent = new Intent(activity, MyCoolService.class); // serviceIntent.setAction(ACTION_EXECUTE_WITH_SERVICE_CONNECTION); // activity.bindService(serviceIntent, new ServiceConnection() { // @Override // public void onServiceConnected(ComponentName name, IBinder service) { // Log.d(ACTION_EXECUTE_WITH_SERVICE_CONNECTION, "onServiceConnected"); // final MyCoolService myCoolService = ((MyCoolService.ServiceBinder<MyCoolService>) service).getService(); // myCoolService.addRunnable(new Runnable() { // @Override // public void run() { // Log.d(ACTION_EXECUTE_WITH_SERVICE_CONNECTION, "event "); // myCoolService.removeRunnable(this); // } // }); // activity.startService(serviceIntent); // //TODO make action // activity.unbindService(this); // } // // @Override // public void onServiceDisconnected(ComponentName name) { // Log.d(ACTION_EXECUTE_WITH_SERVICE_CONNECTION, "onServiceDisconnected"); // } // }, Context.BIND_AUTO_CREATE); // } // // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/utils/AuthUtils.java // public class AuthUtils { // // public static boolean isLogged() { // return VkOAuthHelper.isLogged(); // } // // }
import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import com.epam.training.taskmanager.service.ServiceResult; import com.epam.training.taskmanager.utils.AuthUtils;
package com.epam.training.taskmanager; public class StartActivity extends ActionBarActivity { public static final int REQUEST_LOGIN = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //ServiceResult.executeWithResultReceiver(this); ServiceResult.executeWithServiceConnection(this);
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/service/ServiceResult.java // public class ServiceResult { // // public static final String KEY_RESULT_RECEIVER = "result_receiver"; // public static final String ACTION_EXECUTE_WITH_RESULT_RECEIVER = "action_executeWithResultReceiver"; // public static final String ACTION_EXECUTE_WITH_SERVICE_CONNECTION = "action_executeWithServiceConnection"; // // //BroadcastReceiver / local BroadcastReceiver // //Singleton/bus messaging // // public static void executeWithResultReceiver(Activity activity) { // Log.d(ACTION_EXECUTE_WITH_RESULT_RECEIVER, "executeWithResultReceiver"); // Intent serviceIntent = new Intent(activity, MyCoolService.class); // serviceIntent.setAction(ACTION_EXECUTE_WITH_RESULT_RECEIVER); // Handler handler = new Handler(); // ResultReceiver resultReceiver = new ResultReceiver(handler) { // @Override // protected void onReceiveResult(int resultCode, Bundle resultData) { // super.onReceiveResult(resultCode, resultData); // Log.d(ACTION_EXECUTE_WITH_RESULT_RECEIVER, resultCode + " " + resultData); // } // }; // serviceIntent.putExtra(KEY_RESULT_RECEIVER, resultReceiver); // activity.startService(serviceIntent); // } // // public static void executeWithServiceConnection(final Activity activity) { // Log.d(ACTION_EXECUTE_WITH_SERVICE_CONNECTION, "executeWithServiceConnection"); // final Intent serviceIntent = new Intent(activity, MyCoolService.class); // serviceIntent.setAction(ACTION_EXECUTE_WITH_SERVICE_CONNECTION); // activity.bindService(serviceIntent, new ServiceConnection() { // @Override // public void onServiceConnected(ComponentName name, IBinder service) { // Log.d(ACTION_EXECUTE_WITH_SERVICE_CONNECTION, "onServiceConnected"); // final MyCoolService myCoolService = ((MyCoolService.ServiceBinder<MyCoolService>) service).getService(); // myCoolService.addRunnable(new Runnable() { // @Override // public void run() { // Log.d(ACTION_EXECUTE_WITH_SERVICE_CONNECTION, "event "); // myCoolService.removeRunnable(this); // } // }); // activity.startService(serviceIntent); // //TODO make action // activity.unbindService(this); // } // // @Override // public void onServiceDisconnected(ComponentName name) { // Log.d(ACTION_EXECUTE_WITH_SERVICE_CONNECTION, "onServiceDisconnected"); // } // }, Context.BIND_AUTO_CREATE); // } // // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/utils/AuthUtils.java // public class AuthUtils { // // public static boolean isLogged() { // return VkOAuthHelper.isLogged(); // } // // } // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/StartActivity.java import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import com.epam.training.taskmanager.service.ServiceResult; import com.epam.training.taskmanager.utils.AuthUtils; package com.epam.training.taskmanager; public class StartActivity extends ActionBarActivity { public static final int REQUEST_LOGIN = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //ServiceResult.executeWithResultReceiver(this); ServiceResult.executeWithServiceConnection(this);
if (AuthUtils.isLogged()) {
IstiN/android_training_2014
task_manager/app/src/main/java/com/epam/training/taskmanager/DetailsFragmentActivity.java
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/fragments/DetailsFragment.java // public class DetailsFragment extends Fragment { // /** // * Create a new instance of DetailsFragment, initialized to // * show the text at 'index'. // */ // public static DetailsFragment newInstance(int index) { // DetailsFragment f = new DetailsFragment(); // // // Supply index input as an argument. // Bundle args = new Bundle(); // args.putInt("index", index); // f.setArguments(args); // // return f; // } // // // // public int getShownIndex() { // return getArguments().getInt("index", 0); // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, // Bundle savedInstanceState) { // if (container == null) { // // We have different layouts, and in one of them this // // fragment's containing frame doesn't exist. The fragment // // may still be created from its saved state, but there is // // no reason to try to create its view hierarchy because it // // won't be displayed. Note this is not needed -- we could // // just run the code below, where we would create and return // // the view hierarchy; it would just never be used. // return null; // } // // ScrollView scroller = new ScrollView(getActivity()); // TextView text = new TextView(getActivity()); // int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, // 4, getActivity().getResources().getDisplayMetrics()); // text.setPadding(padding, padding, padding, padding); // scroller.addView(text); // text.setText(Shakespeare.DIALOGUE[getShownIndex()]); // return scroller; // } // }
import android.content.res.Configuration; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import com.epam.training.taskmanager.fragments.DetailsFragment;
package com.epam.training.taskmanager; /** * Created by IstiN on 12.11.2014. */ public class DetailsFragmentActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { // If the screen is now in landscape mode, we can show the // dialog in-line with the list so we don't need this activity. finish(); return; } if (savedInstanceState == null) { // During initial setup, plug in the details fragment.
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/fragments/DetailsFragment.java // public class DetailsFragment extends Fragment { // /** // * Create a new instance of DetailsFragment, initialized to // * show the text at 'index'. // */ // public static DetailsFragment newInstance(int index) { // DetailsFragment f = new DetailsFragment(); // // // Supply index input as an argument. // Bundle args = new Bundle(); // args.putInt("index", index); // f.setArguments(args); // // return f; // } // // // // public int getShownIndex() { // return getArguments().getInt("index", 0); // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, // Bundle savedInstanceState) { // if (container == null) { // // We have different layouts, and in one of them this // // fragment's containing frame doesn't exist. The fragment // // may still be created from its saved state, but there is // // no reason to try to create its view hierarchy because it // // won't be displayed. Note this is not needed -- we could // // just run the code below, where we would create and return // // the view hierarchy; it would just never be used. // return null; // } // // ScrollView scroller = new ScrollView(getActivity()); // TextView text = new TextView(getActivity()); // int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, // 4, getActivity().getResources().getDisplayMetrics()); // text.setPadding(padding, padding, padding, padding); // scroller.addView(text); // text.setText(Shakespeare.DIALOGUE[getShownIndex()]); // return scroller; // } // } // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/DetailsFragmentActivity.java import android.content.res.Configuration; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import com.epam.training.taskmanager.fragments.DetailsFragment; package com.epam.training.taskmanager; /** * Created by IstiN on 12.11.2014. */ public class DetailsFragmentActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { // If the screen is now in landscape mode, we can show the // dialog in-line with the list so we don't need this activity. finish(); return; } if (savedInstanceState == null) { // During initial setup, plug in the details fragment.
DetailsFragment details = new DetailsFragment();
IstiN/android_training_2014
task_manager/app/src/main/java/com/epam/training/taskmanager/processing/BitmapProcessor.java
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/source/HttpDataSource.java // public class HttpDataSource implements DataSource<InputStream, String> { // // public static final String KEY = "HttpDataSource"; // // public static HttpDataSource get(Context context) { // return CoreApplication.get(context, KEY); // } // // @Override // public InputStream getResult(String p) throws Exception { // //download data and return // URL url = new URL(p); // // Read all the text returned by the server // InputStream inputStream = url.openStream(); // return inputStream; // } // // public static void close(Closeable in) { // if (in != null) { // try { // in.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // }
import android.graphics.Bitmap; import android.graphics.BitmapFactory; import com.epam.training.taskmanager.source.HttpDataSource; import java.io.InputStream;
package com.epam.training.taskmanager.processing; /** * Created by IstiN on 14.11.2014. */ public class BitmapProcessor implements Processor<Bitmap, InputStream> { @Override public Bitmap process(InputStream inputStream) throws Exception { try { return BitmapFactory.decodeStream(inputStream); } finally {
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/source/HttpDataSource.java // public class HttpDataSource implements DataSource<InputStream, String> { // // public static final String KEY = "HttpDataSource"; // // public static HttpDataSource get(Context context) { // return CoreApplication.get(context, KEY); // } // // @Override // public InputStream getResult(String p) throws Exception { // //download data and return // URL url = new URL(p); // // Read all the text returned by the server // InputStream inputStream = url.openStream(); // return inputStream; // } // // public static void close(Closeable in) { // if (in != null) { // try { // in.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // } // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/processing/BitmapProcessor.java import android.graphics.Bitmap; import android.graphics.BitmapFactory; import com.epam.training.taskmanager.source.HttpDataSource; import java.io.InputStream; package com.epam.training.taskmanager.processing; /** * Created by IstiN on 14.11.2014. */ public class BitmapProcessor implements Processor<Bitmap, InputStream> { @Override public Bitmap process(InputStream inputStream) throws Exception { try { return BitmapFactory.decodeStream(inputStream); } finally {
HttpDataSource.close(inputStream);
IstiN/android_training_2014
task_manager/app/src/main/java/com/epam/training/taskmanager/DetailsActivity.java
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/bo/NoteGsonModel.java // public class NoteGsonModel implements Serializable { // // private String title; // // private String content; // // private Long id; // // public NoteGsonModel(Long id, String title, String content) { // this.title = title; // this.content = content; // this.id = id; // } // // public String getTitle() { // return title; // } // // public Long getId() { // return id; // } // // public String getContent() { // return content; // } // }
import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.widget.TextView; import com.epam.training.taskmanager.bo.NoteGsonModel;
package com.epam.training.taskmanager; public class DetailsActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_details);
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/bo/NoteGsonModel.java // public class NoteGsonModel implements Serializable { // // private String title; // // private String content; // // private Long id; // // public NoteGsonModel(Long id, String title, String content) { // this.title = title; // this.content = content; // this.id = id; // } // // public String getTitle() { // return title; // } // // public Long getId() { // return id; // } // // public String getContent() { // return content; // } // } // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/DetailsActivity.java import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.widget.TextView; import com.epam.training.taskmanager.bo.NoteGsonModel; package com.epam.training.taskmanager; public class DetailsActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_details);
NoteGsonModel noteGsonModel = (NoteGsonModel) getIntent().getSerializableExtra("item");
IstiN/android_training_2014
task_manager/app/src/main/java/com/epam/training/taskmanager/helper/DataManager.java
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/os/AsyncTask.java // public abstract class AsyncTask<Params, Progress, Result> { // // private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors(); // // private static final ExecutorService sExecutor; // // static { // sExecutor = new ThreadPoolExecutor(CPU_COUNT, CPU_COUNT, 0L, TimeUnit.MILLISECONDS, new LIFOLinkedBlockingDeque<Runnable>()); // } // // public AsyncTask() { // // } // // protected void onPreExecute() { // // } // // protected void onPostExecute(Result processingResult) { // // } // // protected abstract Result doInBackground(Params... params) throws Exception; // // public void execute(final Params... params) { // final Handler handler = new Handler(); // onPreExecute(); // sExecutor.execute(new Runnable() { // @Override // public void run() { // try { // final Result result = doInBackground(params); // handler.post(new Runnable() { // @Override // public void run() { // onPostExecute(result); // } // }); // } catch (final Exception e) { // handler.post(new Runnable() { // @Override // public void run() { // onPostException(e); // } // }); // } // } // }); // } // // protected abstract void onPostException(Exception e); // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/processing/Processor.java // public interface Processor<ProcessingResult, Source> { // // ProcessingResult process(Source source) throws Exception; // // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/source/DataSource.java // public interface DataSource<Result,Params>{ // // Result getResult(Params params) throws Exception; // // }
import android.os.Handler; import com.epam.training.taskmanager.os.AsyncTask; import com.epam.training.taskmanager.processing.Processor; import com.epam.training.taskmanager.source.DataSource;
package com.epam.training.taskmanager.helper; /** * Created by IstiN on 15.10.2014. */ public class DataManager { public static final boolean IS_ASYNC_TASK = true; public static interface Callback<Result> { void onDataLoadStart(); void onDone(Result data); void onError(Exception e); } public static interface MySuperLoader<ProcessingResult, DataSourceResult, Params> {
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/os/AsyncTask.java // public abstract class AsyncTask<Params, Progress, Result> { // // private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors(); // // private static final ExecutorService sExecutor; // // static { // sExecutor = new ThreadPoolExecutor(CPU_COUNT, CPU_COUNT, 0L, TimeUnit.MILLISECONDS, new LIFOLinkedBlockingDeque<Runnable>()); // } // // public AsyncTask() { // // } // // protected void onPreExecute() { // // } // // protected void onPostExecute(Result processingResult) { // // } // // protected abstract Result doInBackground(Params... params) throws Exception; // // public void execute(final Params... params) { // final Handler handler = new Handler(); // onPreExecute(); // sExecutor.execute(new Runnable() { // @Override // public void run() { // try { // final Result result = doInBackground(params); // handler.post(new Runnable() { // @Override // public void run() { // onPostExecute(result); // } // }); // } catch (final Exception e) { // handler.post(new Runnable() { // @Override // public void run() { // onPostException(e); // } // }); // } // } // }); // } // // protected abstract void onPostException(Exception e); // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/processing/Processor.java // public interface Processor<ProcessingResult, Source> { // // ProcessingResult process(Source source) throws Exception; // // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/source/DataSource.java // public interface DataSource<Result,Params>{ // // Result getResult(Params params) throws Exception; // // } // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/helper/DataManager.java import android.os.Handler; import com.epam.training.taskmanager.os.AsyncTask; import com.epam.training.taskmanager.processing.Processor; import com.epam.training.taskmanager.source.DataSource; package com.epam.training.taskmanager.helper; /** * Created by IstiN on 15.10.2014. */ public class DataManager { public static final boolean IS_ASYNC_TASK = true; public static interface Callback<Result> { void onDataLoadStart(); void onDone(Result data); void onError(Exception e); } public static interface MySuperLoader<ProcessingResult, DataSourceResult, Params> {
void load(final Callback<ProcessingResult> callback, Params params, final DataSource<DataSourceResult, Params> dataSource, final Processor<ProcessingResult, DataSourceResult> processor);
IstiN/android_training_2014
task_manager/app/src/main/java/com/epam/training/taskmanager/helper/DataManager.java
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/os/AsyncTask.java // public abstract class AsyncTask<Params, Progress, Result> { // // private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors(); // // private static final ExecutorService sExecutor; // // static { // sExecutor = new ThreadPoolExecutor(CPU_COUNT, CPU_COUNT, 0L, TimeUnit.MILLISECONDS, new LIFOLinkedBlockingDeque<Runnable>()); // } // // public AsyncTask() { // // } // // protected void onPreExecute() { // // } // // protected void onPostExecute(Result processingResult) { // // } // // protected abstract Result doInBackground(Params... params) throws Exception; // // public void execute(final Params... params) { // final Handler handler = new Handler(); // onPreExecute(); // sExecutor.execute(new Runnable() { // @Override // public void run() { // try { // final Result result = doInBackground(params); // handler.post(new Runnable() { // @Override // public void run() { // onPostExecute(result); // } // }); // } catch (final Exception e) { // handler.post(new Runnable() { // @Override // public void run() { // onPostException(e); // } // }); // } // } // }); // } // // protected abstract void onPostException(Exception e); // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/processing/Processor.java // public interface Processor<ProcessingResult, Source> { // // ProcessingResult process(Source source) throws Exception; // // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/source/DataSource.java // public interface DataSource<Result,Params>{ // // Result getResult(Params params) throws Exception; // // }
import android.os.Handler; import com.epam.training.taskmanager.os.AsyncTask; import com.epam.training.taskmanager.processing.Processor; import com.epam.training.taskmanager.source.DataSource;
package com.epam.training.taskmanager.helper; /** * Created by IstiN on 15.10.2014. */ public class DataManager { public static final boolean IS_ASYNC_TASK = true; public static interface Callback<Result> { void onDataLoadStart(); void onDone(Result data); void onError(Exception e); } public static interface MySuperLoader<ProcessingResult, DataSourceResult, Params> {
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/os/AsyncTask.java // public abstract class AsyncTask<Params, Progress, Result> { // // private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors(); // // private static final ExecutorService sExecutor; // // static { // sExecutor = new ThreadPoolExecutor(CPU_COUNT, CPU_COUNT, 0L, TimeUnit.MILLISECONDS, new LIFOLinkedBlockingDeque<Runnable>()); // } // // public AsyncTask() { // // } // // protected void onPreExecute() { // // } // // protected void onPostExecute(Result processingResult) { // // } // // protected abstract Result doInBackground(Params... params) throws Exception; // // public void execute(final Params... params) { // final Handler handler = new Handler(); // onPreExecute(); // sExecutor.execute(new Runnable() { // @Override // public void run() { // try { // final Result result = doInBackground(params); // handler.post(new Runnable() { // @Override // public void run() { // onPostExecute(result); // } // }); // } catch (final Exception e) { // handler.post(new Runnable() { // @Override // public void run() { // onPostException(e); // } // }); // } // } // }); // } // // protected abstract void onPostException(Exception e); // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/processing/Processor.java // public interface Processor<ProcessingResult, Source> { // // ProcessingResult process(Source source) throws Exception; // // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/source/DataSource.java // public interface DataSource<Result,Params>{ // // Result getResult(Params params) throws Exception; // // } // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/helper/DataManager.java import android.os.Handler; import com.epam.training.taskmanager.os.AsyncTask; import com.epam.training.taskmanager.processing.Processor; import com.epam.training.taskmanager.source.DataSource; package com.epam.training.taskmanager.helper; /** * Created by IstiN on 15.10.2014. */ public class DataManager { public static final boolean IS_ASYNC_TASK = true; public static interface Callback<Result> { void onDataLoadStart(); void onDone(Result data); void onError(Exception e); } public static interface MySuperLoader<ProcessingResult, DataSourceResult, Params> {
void load(final Callback<ProcessingResult> callback, Params params, final DataSource<DataSourceResult, Params> dataSource, final Processor<ProcessingResult, DataSourceResult> processor);
IstiN/android_training_2014
task_manager/app/src/main/java/com/epam/training/taskmanager/helper/DataManager.java
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/os/AsyncTask.java // public abstract class AsyncTask<Params, Progress, Result> { // // private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors(); // // private static final ExecutorService sExecutor; // // static { // sExecutor = new ThreadPoolExecutor(CPU_COUNT, CPU_COUNT, 0L, TimeUnit.MILLISECONDS, new LIFOLinkedBlockingDeque<Runnable>()); // } // // public AsyncTask() { // // } // // protected void onPreExecute() { // // } // // protected void onPostExecute(Result processingResult) { // // } // // protected abstract Result doInBackground(Params... params) throws Exception; // // public void execute(final Params... params) { // final Handler handler = new Handler(); // onPreExecute(); // sExecutor.execute(new Runnable() { // @Override // public void run() { // try { // final Result result = doInBackground(params); // handler.post(new Runnable() { // @Override // public void run() { // onPostExecute(result); // } // }); // } catch (final Exception e) { // handler.post(new Runnable() { // @Override // public void run() { // onPostException(e); // } // }); // } // } // }); // } // // protected abstract void onPostException(Exception e); // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/processing/Processor.java // public interface Processor<ProcessingResult, Source> { // // ProcessingResult process(Source source) throws Exception; // // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/source/DataSource.java // public interface DataSource<Result,Params>{ // // Result getResult(Params params) throws Exception; // // }
import android.os.Handler; import com.epam.training.taskmanager.os.AsyncTask; import com.epam.training.taskmanager.processing.Processor; import com.epam.training.taskmanager.source.DataSource;
final Params params, final DataSource<DataSourceResult, Params> dataSource, final Processor<ProcessingResult, DataSourceResult> processor ) { loadData(callback, params, dataSource, processor, new MySuperLoader<ProcessingResult, DataSourceResult, Params>() { @Override public void load(Callback<ProcessingResult> callback, Params params, DataSource<DataSourceResult, Params> dataSource, Processor<ProcessingResult, DataSourceResult> processor) { if (IS_ASYNC_TASK) { executeInAsyncTask(callback, params, dataSource, processor); } else { executeInThread(callback, params, dataSource, processor); } } }); } public static <ProcessingResult, DataSourceResult, Params> void loadData( final Callback<ProcessingResult> callback, final Params params, final DataSource<DataSourceResult, Params> dataSource, final Processor<ProcessingResult, DataSourceResult> processor, final MySuperLoader<ProcessingResult, DataSourceResult, Params> mySuperLoader) { if (callback == null) { throw new IllegalArgumentException("callback can't be null"); } mySuperLoader.load(callback, params, dataSource, processor); } private static <ProcessingResult, DataSourceResult, Params> void executeInAsyncTask(final Callback<ProcessingResult> callback, Params params, final DataSource<DataSourceResult, Params> dataSource, final Processor<ProcessingResult, DataSourceResult> processor) {
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/os/AsyncTask.java // public abstract class AsyncTask<Params, Progress, Result> { // // private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors(); // // private static final ExecutorService sExecutor; // // static { // sExecutor = new ThreadPoolExecutor(CPU_COUNT, CPU_COUNT, 0L, TimeUnit.MILLISECONDS, new LIFOLinkedBlockingDeque<Runnable>()); // } // // public AsyncTask() { // // } // // protected void onPreExecute() { // // } // // protected void onPostExecute(Result processingResult) { // // } // // protected abstract Result doInBackground(Params... params) throws Exception; // // public void execute(final Params... params) { // final Handler handler = new Handler(); // onPreExecute(); // sExecutor.execute(new Runnable() { // @Override // public void run() { // try { // final Result result = doInBackground(params); // handler.post(new Runnable() { // @Override // public void run() { // onPostExecute(result); // } // }); // } catch (final Exception e) { // handler.post(new Runnable() { // @Override // public void run() { // onPostException(e); // } // }); // } // } // }); // } // // protected abstract void onPostException(Exception e); // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/processing/Processor.java // public interface Processor<ProcessingResult, Source> { // // ProcessingResult process(Source source) throws Exception; // // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/source/DataSource.java // public interface DataSource<Result,Params>{ // // Result getResult(Params params) throws Exception; // // } // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/helper/DataManager.java import android.os.Handler; import com.epam.training.taskmanager.os.AsyncTask; import com.epam.training.taskmanager.processing.Processor; import com.epam.training.taskmanager.source.DataSource; final Params params, final DataSource<DataSourceResult, Params> dataSource, final Processor<ProcessingResult, DataSourceResult> processor ) { loadData(callback, params, dataSource, processor, new MySuperLoader<ProcessingResult, DataSourceResult, Params>() { @Override public void load(Callback<ProcessingResult> callback, Params params, DataSource<DataSourceResult, Params> dataSource, Processor<ProcessingResult, DataSourceResult> processor) { if (IS_ASYNC_TASK) { executeInAsyncTask(callback, params, dataSource, processor); } else { executeInThread(callback, params, dataSource, processor); } } }); } public static <ProcessingResult, DataSourceResult, Params> void loadData( final Callback<ProcessingResult> callback, final Params params, final DataSource<DataSourceResult, Params> dataSource, final Processor<ProcessingResult, DataSourceResult> processor, final MySuperLoader<ProcessingResult, DataSourceResult, Params> mySuperLoader) { if (callback == null) { throw new IllegalArgumentException("callback can't be null"); } mySuperLoader.load(callback, params, dataSource, processor); } private static <ProcessingResult, DataSourceResult, Params> void executeInAsyncTask(final Callback<ProcessingResult> callback, Params params, final DataSource<DataSourceResult, Params> dataSource, final Processor<ProcessingResult, DataSourceResult> processor) {
new AsyncTask<Params, Void, ProcessingResult>() {
IstiN/android_training_2014
task_manager/app/src/main/java/com/epam/training/taskmanager/utils/AuthUtils.java
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/auth/VkOAuthHelper.java // public class VkOAuthHelper { // // public static interface Callbacks { // // void onError(Exception e); // // void onSuccess(); // // } // // //TODO don't do it in your project // private static String sToken; // // public static final String REDIRECT_URL = "https://oauth.vk.com/blank.html"; // public static final String AUTORIZATION_URL = "https://oauth.vk.com/authorize?client_id=4611084&scope=offline,wall,photos,status&redirect_uri=" + REDIRECT_URL + "&display=touch&response_type=token"; // private static final String TAG = VkOAuthHelper.class.getSimpleName(); // // public static String sign(String url) { // if (url.contains("?")) { // return url + "&access_token="+sToken; // } else { // return url + "?access_token="+sToken; // } // } // // public static boolean isLogged() { // return !TextUtils.isEmpty(sToken); // } // // public static boolean proceedRedirectURL(Activity activity, String url, Callbacks callbacks) { // if (url.startsWith(REDIRECT_URL)) { // Uri uri = Uri.parse(url); // String fragment = uri.getFragment(); // Uri parsedFragment = Uri.parse("http://temp.com?" + fragment); // String accessToken = parsedFragment.getQueryParameter("access_token"); // if (!TextUtils.isEmpty(accessToken)) { // //TODO save sToken to the secure store // //TODO create account in account manager // Log.d(TAG, "token " + accessToken); // sToken = accessToken; // callbacks.onSuccess(); // return true; // } else { // String error = parsedFragment.getQueryParameter("error"); // String errorDescription = parsedFragment.getQueryParameter("error_description"); // String errorReason = parsedFragment.getQueryParameter("error_reason"); // if (!TextUtils.isEmpty(error)) { // callbacks.onError(new AuthenticationException(error+", reason : " + errorReason +"("+errorDescription+")")); // return false; // } else { // //WTF? // } // } // } // return false; // } // }
import com.epam.training.taskmanager.auth.VkOAuthHelper;
package com.epam.training.taskmanager.utils; /** * Created by Uladzimir_Klyshevich on 10/3/2014. */ public class AuthUtils { public static boolean isLogged() {
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/auth/VkOAuthHelper.java // public class VkOAuthHelper { // // public static interface Callbacks { // // void onError(Exception e); // // void onSuccess(); // // } // // //TODO don't do it in your project // private static String sToken; // // public static final String REDIRECT_URL = "https://oauth.vk.com/blank.html"; // public static final String AUTORIZATION_URL = "https://oauth.vk.com/authorize?client_id=4611084&scope=offline,wall,photos,status&redirect_uri=" + REDIRECT_URL + "&display=touch&response_type=token"; // private static final String TAG = VkOAuthHelper.class.getSimpleName(); // // public static String sign(String url) { // if (url.contains("?")) { // return url + "&access_token="+sToken; // } else { // return url + "?access_token="+sToken; // } // } // // public static boolean isLogged() { // return !TextUtils.isEmpty(sToken); // } // // public static boolean proceedRedirectURL(Activity activity, String url, Callbacks callbacks) { // if (url.startsWith(REDIRECT_URL)) { // Uri uri = Uri.parse(url); // String fragment = uri.getFragment(); // Uri parsedFragment = Uri.parse("http://temp.com?" + fragment); // String accessToken = parsedFragment.getQueryParameter("access_token"); // if (!TextUtils.isEmpty(accessToken)) { // //TODO save sToken to the secure store // //TODO create account in account manager // Log.d(TAG, "token " + accessToken); // sToken = accessToken; // callbacks.onSuccess(); // return true; // } else { // String error = parsedFragment.getQueryParameter("error"); // String errorDescription = parsedFragment.getQueryParameter("error_description"); // String errorReason = parsedFragment.getQueryParameter("error_reason"); // if (!TextUtils.isEmpty(error)) { // callbacks.onError(new AuthenticationException(error+", reason : " + errorReason +"("+errorDescription+")")); // return false; // } else { // //WTF? // } // } // } // return false; // } // } // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/utils/AuthUtils.java import com.epam.training.taskmanager.auth.VkOAuthHelper; package com.epam.training.taskmanager.utils; /** * Created by Uladzimir_Klyshevich on 10/3/2014. */ public class AuthUtils { public static boolean isLogged() {
return VkOAuthHelper.isLogged();
IstiN/android_training_2014
task_manager/app/src/main/java/com/epam/training/taskmanager/source/CachedHttpDataSource.java
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/CoreApplication.java // public class CoreApplication extends Application { // // private HttpDataSource mHttpDataSource; // private CachedHttpDataSource mCachedHttpDataSource; // private VkDataSource mVkDataSource; // private MySuperImageLoader mMySuperImageLoader; // // @Override // public void onCreate() { // super.onCreate(); // mMySuperImageLoader = new MySuperImageLoader(this); // mHttpDataSource = new HttpDataSource(); // mVkDataSource = new VkDataSource(); // mCachedHttpDataSource = new CachedHttpDataSource(this); // } // // @Override // public Object getSystemService(String name) { // if (HttpDataSource.KEY.equals(name)) { // //for android kitkat + // if (mHttpDataSource == null) { // mHttpDataSource = new HttpDataSource(); // } // return mHttpDataSource; // } // if (CachedHttpDataSource.KEY.equals(name)) { // //for android kitkat + // if (mCachedHttpDataSource == null) { // mCachedHttpDataSource = new CachedHttpDataSource(this); // } // return mCachedHttpDataSource; // } // if (VkDataSource.KEY.equals(name)) { // //for android kitkat + // if (mVkDataSource == null) { // mVkDataSource = new VkDataSource(); // } // return mVkDataSource; // } // if (MySuperImageLoader.KEY.equals(name)) { // //for android kitkat + // if (mMySuperImageLoader == null) { // mMySuperImageLoader = new MySuperImageLoader(this); // } // return mMySuperImageLoader; // } // return super.getSystemService(name); // } // // public static <T> T get(Context context, String key) { // if (context == null || key == null){ // throw new IllegalArgumentException("Context and key must not be null"); // } // T systemService = (T) context.getSystemService(key); // if (systemService == null) { // context = context.getApplicationContext(); // systemService = (T) context.getSystemService(key); // } // if (systemService == null) { // throw new IllegalStateException(key + " not available"); // } // return systemService; // } // }
import android.content.Context; import android.util.Log; import com.epam.training.taskmanager.CoreApplication; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Collections;
package com.epam.training.taskmanager.source; /** * Created by IstiN on 03.12.2014. */ public class CachedHttpDataSource extends HttpDataSource { public static final String KEY = "CachedHttpDataSource"; public static final String TAG = "cache_http_data_source"; private Context mContext; public CachedHttpDataSource(Context context) { mContext = context; } public static CachedHttpDataSource get(Context context) {
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/CoreApplication.java // public class CoreApplication extends Application { // // private HttpDataSource mHttpDataSource; // private CachedHttpDataSource mCachedHttpDataSource; // private VkDataSource mVkDataSource; // private MySuperImageLoader mMySuperImageLoader; // // @Override // public void onCreate() { // super.onCreate(); // mMySuperImageLoader = new MySuperImageLoader(this); // mHttpDataSource = new HttpDataSource(); // mVkDataSource = new VkDataSource(); // mCachedHttpDataSource = new CachedHttpDataSource(this); // } // // @Override // public Object getSystemService(String name) { // if (HttpDataSource.KEY.equals(name)) { // //for android kitkat + // if (mHttpDataSource == null) { // mHttpDataSource = new HttpDataSource(); // } // return mHttpDataSource; // } // if (CachedHttpDataSource.KEY.equals(name)) { // //for android kitkat + // if (mCachedHttpDataSource == null) { // mCachedHttpDataSource = new CachedHttpDataSource(this); // } // return mCachedHttpDataSource; // } // if (VkDataSource.KEY.equals(name)) { // //for android kitkat + // if (mVkDataSource == null) { // mVkDataSource = new VkDataSource(); // } // return mVkDataSource; // } // if (MySuperImageLoader.KEY.equals(name)) { // //for android kitkat + // if (mMySuperImageLoader == null) { // mMySuperImageLoader = new MySuperImageLoader(this); // } // return mMySuperImageLoader; // } // return super.getSystemService(name); // } // // public static <T> T get(Context context, String key) { // if (context == null || key == null){ // throw new IllegalArgumentException("Context and key must not be null"); // } // T systemService = (T) context.getSystemService(key); // if (systemService == null) { // context = context.getApplicationContext(); // systemService = (T) context.getSystemService(key); // } // if (systemService == null) { // throw new IllegalStateException(key + " not available"); // } // return systemService; // } // } // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/source/CachedHttpDataSource.java import android.content.Context; import android.util.Log; import com.epam.training.taskmanager.CoreApplication; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Collections; package com.epam.training.taskmanager.source; /** * Created by IstiN on 03.12.2014. */ public class CachedHttpDataSource extends HttpDataSource { public static final String KEY = "CachedHttpDataSource"; public static final String TAG = "cache_http_data_source"; private Context mContext; public CachedHttpDataSource(Context context) { mContext = context; } public static CachedHttpDataSource get(Context context) {
return CoreApplication.get(context, KEY);
IstiN/android_training_2014
task_manager/app/src/main/java/com/epam/training/taskmanager/FragmentLayoutSupportActivity.java
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/fragments/DetailsFragment.java // public class DetailsFragment extends Fragment { // /** // * Create a new instance of DetailsFragment, initialized to // * show the text at 'index'. // */ // public static DetailsFragment newInstance(int index) { // DetailsFragment f = new DetailsFragment(); // // // Supply index input as an argument. // Bundle args = new Bundle(); // args.putInt("index", index); // f.setArguments(args); // // return f; // } // // // // public int getShownIndex() { // return getArguments().getInt("index", 0); // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, // Bundle savedInstanceState) { // if (container == null) { // // We have different layouts, and in one of them this // // fragment's containing frame doesn't exist. The fragment // // may still be created from its saved state, but there is // // no reason to try to create its view hierarchy because it // // won't be displayed. Note this is not needed -- we could // // just run the code below, where we would create and return // // the view hierarchy; it would just never be used. // return null; // } // // ScrollView scroller = new ScrollView(getActivity()); // TextView text = new TextView(getActivity()); // int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, // 4, getActivity().getResources().getDisplayMetrics()); // text.setPadding(padding, padding, padding, padding); // scroller.addView(text); // text.setText(Shakespeare.DIALOGUE[getShownIndex()]); // return scroller; // } // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/fragments/TitlesFragment.java // public class TitlesFragment extends ListFragment { // // public static <T> T findFirstResponderFor(Fragment fragment, Class<T> clazz) { // FragmentActivity activity = fragment.getActivity(); // if (activity == null) // return null; // if (clazz.isInstance(activity)) { // return clazz.cast(activity); // } // Fragment parentFragment = fragment.getParentFragment(); // while (parentFragment != null) { // if (clazz.isInstance(parentFragment)) { // return clazz.cast(parentFragment); // } // parentFragment = parentFragment.getParentFragment(); // } // return null; // } // // public static interface Callbacks { // // void onShowDetails(int index); // // boolean isDualPane(); // // } // // int mCurCheckPosition = 0; // // // // @Override // public void onActivityCreated(Bundle savedInstanceState) { // super.onActivityCreated(savedInstanceState); // // // Populate list with our static array of titles. // setListAdapter(new ArrayAdapter<String>(getActivity(), // R.layout.simple_list_item_checkable_1, // android.R.id.text1, Shakespeare.TITLES)); // // if (savedInstanceState != null) { // // Restore last state for checked position. // mCurCheckPosition = savedInstanceState.getInt("curChoice", 0); // } // // if (getCallbacks().isDualPane()) { // // In dual-pane mode, the list view highlights the selected item. // getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); // // Make sure our UI is in the correct state. // showDetails(mCurCheckPosition); // } // } // // @Override // public void onSaveInstanceState(Bundle outState) { // super.onSaveInstanceState(outState); // outState.putInt("curChoice", mCurCheckPosition); // } // // @Override // public void onListItemClick(ListView l, View v, int position, long id) { // showDetails(position); // } // // /** // * Helper function to show the details of a selected item, either by // * displaying a fragment in-place in the current UI, or starting a // * whole new activity in which it is displayed. // */ // void showDetails(int index) { // mCurCheckPosition = index; // Callbacks callbacks = getCallbacks(); // if (callbacks.isDualPane()) { // getListView().setItemChecked(index, true); // } // callbacks.onShowDetails(index); // // } // // private Callbacks getCallbacks() { // return findFirstResponderFor(this, Callbacks.class); // } // }
import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentTransaction; import android.view.View; import com.epam.training.taskmanager.fragments.DetailsFragment; import com.epam.training.taskmanager.fragments.TitlesFragment;
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.epam.training.taskmanager; /** * Demonstration of using fragments to implement different activity layouts. * This sample provides a different layout (and activity flow) when run in * landscape. */ public class FragmentLayoutSupportActivity extends FragmentActivity implements TitlesFragment.Callbacks { boolean mDualPane; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_layout_support); // Check to see if we have a frame in which to embed the details // fragment directly in the containing UI. View detailsFrame = findViewById(R.id.details); mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE; } @Override public void onShowDetails(int index) { if (mDualPane) { // We can display everything in-place with fragments, so update // the list to highlight the selected item and show the data. // Check what fragment is currently shown, replace if needed.
// Path: task_manager/app/src/main/java/com/epam/training/taskmanager/fragments/DetailsFragment.java // public class DetailsFragment extends Fragment { // /** // * Create a new instance of DetailsFragment, initialized to // * show the text at 'index'. // */ // public static DetailsFragment newInstance(int index) { // DetailsFragment f = new DetailsFragment(); // // // Supply index input as an argument. // Bundle args = new Bundle(); // args.putInt("index", index); // f.setArguments(args); // // return f; // } // // // // public int getShownIndex() { // return getArguments().getInt("index", 0); // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, // Bundle savedInstanceState) { // if (container == null) { // // We have different layouts, and in one of them this // // fragment's containing frame doesn't exist. The fragment // // may still be created from its saved state, but there is // // no reason to try to create its view hierarchy because it // // won't be displayed. Note this is not needed -- we could // // just run the code below, where we would create and return // // the view hierarchy; it would just never be used. // return null; // } // // ScrollView scroller = new ScrollView(getActivity()); // TextView text = new TextView(getActivity()); // int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, // 4, getActivity().getResources().getDisplayMetrics()); // text.setPadding(padding, padding, padding, padding); // scroller.addView(text); // text.setText(Shakespeare.DIALOGUE[getShownIndex()]); // return scroller; // } // } // // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/fragments/TitlesFragment.java // public class TitlesFragment extends ListFragment { // // public static <T> T findFirstResponderFor(Fragment fragment, Class<T> clazz) { // FragmentActivity activity = fragment.getActivity(); // if (activity == null) // return null; // if (clazz.isInstance(activity)) { // return clazz.cast(activity); // } // Fragment parentFragment = fragment.getParentFragment(); // while (parentFragment != null) { // if (clazz.isInstance(parentFragment)) { // return clazz.cast(parentFragment); // } // parentFragment = parentFragment.getParentFragment(); // } // return null; // } // // public static interface Callbacks { // // void onShowDetails(int index); // // boolean isDualPane(); // // } // // int mCurCheckPosition = 0; // // // // @Override // public void onActivityCreated(Bundle savedInstanceState) { // super.onActivityCreated(savedInstanceState); // // // Populate list with our static array of titles. // setListAdapter(new ArrayAdapter<String>(getActivity(), // R.layout.simple_list_item_checkable_1, // android.R.id.text1, Shakespeare.TITLES)); // // if (savedInstanceState != null) { // // Restore last state for checked position. // mCurCheckPosition = savedInstanceState.getInt("curChoice", 0); // } // // if (getCallbacks().isDualPane()) { // // In dual-pane mode, the list view highlights the selected item. // getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); // // Make sure our UI is in the correct state. // showDetails(mCurCheckPosition); // } // } // // @Override // public void onSaveInstanceState(Bundle outState) { // super.onSaveInstanceState(outState); // outState.putInt("curChoice", mCurCheckPosition); // } // // @Override // public void onListItemClick(ListView l, View v, int position, long id) { // showDetails(position); // } // // /** // * Helper function to show the details of a selected item, either by // * displaying a fragment in-place in the current UI, or starting a // * whole new activity in which it is displayed. // */ // void showDetails(int index) { // mCurCheckPosition = index; // Callbacks callbacks = getCallbacks(); // if (callbacks.isDualPane()) { // getListView().setItemChecked(index, true); // } // callbacks.onShowDetails(index); // // } // // private Callbacks getCallbacks() { // return findFirstResponderFor(this, Callbacks.class); // } // } // Path: task_manager/app/src/main/java/com/epam/training/taskmanager/FragmentLayoutSupportActivity.java import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentTransaction; import android.view.View; import com.epam.training.taskmanager.fragments.DetailsFragment; import com.epam.training.taskmanager.fragments.TitlesFragment; /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.epam.training.taskmanager; /** * Demonstration of using fragments to implement different activity layouts. * This sample provides a different layout (and activity flow) when run in * landscape. */ public class FragmentLayoutSupportActivity extends FragmentActivity implements TitlesFragment.Callbacks { boolean mDualPane; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_layout_support); // Check to see if we have a frame in which to embed the details // fragment directly in the containing UI. View detailsFrame = findViewById(R.id.details); mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE; } @Override public void onShowDetails(int index) { if (mDualPane) { // We can display everything in-place with fragments, so update // the list to highlight the selected item and show the data. // Check what fragment is currently shown, replace if needed.
DetailsFragment details = (DetailsFragment)
webpagebytes/general-cms-plugins
src/main/java/com/webpagebytes/plugins/WPBSQLAdminDataStorage.java
// Path: src/main/java/com/webpagebytes/plugins/WPBSQLDataStoreDao.java // public enum WBSQLQueryOperator{ // LESS_THAN, // GREATER_THAN, // EQUAL, // NOT_EQUAL, // LESS_THAN_OR_EQUAL, // GREATER_THAN_OR_EQUAL // }; // // Path: src/main/java/com/webpagebytes/plugins/WPBSQLDataStoreDao.java // public enum WBSQLSortDirection { // NO_SORT, // ASCENDING, // DESCENDING // };
import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import com.webpagebytes.cms.WPBAdminDataStorage; import com.webpagebytes.cms.exception.WPBIOException; import com.webpagebytes.plugins.WPBSQLDataStoreDao.WBSQLQueryOperator; import com.webpagebytes.plugins.WPBSQLDataStoreDao.WBSQLSortDirection;
/* * Copyright 2014 Webpagebytes * * 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.webpagebytes.plugins; public class WPBSQLAdminDataStorage implements WPBAdminDataStorage { private static final Logger log = Logger.getLogger(WPBSQLAdminDataStorage.class.getName()); private static final String DEFAULT_KEY_FIELD_NAME = "externalKey"; private static final String CONFIG_KEY_FIELD_NAME = "keyFieldName"; private WPBSQLDataStoreDao sqlDataStorageDao; private String keyFieldName; public WPBSQLAdminDataStorage() { keyFieldName = DEFAULT_KEY_FIELD_NAME; } public void initialize(Map<String, String> params) throws WPBIOException { sqlDataStorageDao = new WPBSQLDataStoreDao(params); if (params != null && params.containsKey(CONFIG_KEY_FIELD_NAME)) { keyFieldName = params.get(CONFIG_KEY_FIELD_NAME); } }
// Path: src/main/java/com/webpagebytes/plugins/WPBSQLDataStoreDao.java // public enum WBSQLQueryOperator{ // LESS_THAN, // GREATER_THAN, // EQUAL, // NOT_EQUAL, // LESS_THAN_OR_EQUAL, // GREATER_THAN_OR_EQUAL // }; // // Path: src/main/java/com/webpagebytes/plugins/WPBSQLDataStoreDao.java // public enum WBSQLSortDirection { // NO_SORT, // ASCENDING, // DESCENDING // }; // Path: src/main/java/com/webpagebytes/plugins/WPBSQLAdminDataStorage.java import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import com.webpagebytes.cms.WPBAdminDataStorage; import com.webpagebytes.cms.exception.WPBIOException; import com.webpagebytes.plugins.WPBSQLDataStoreDao.WBSQLQueryOperator; import com.webpagebytes.plugins.WPBSQLDataStoreDao.WBSQLSortDirection; /* * Copyright 2014 Webpagebytes * * 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.webpagebytes.plugins; public class WPBSQLAdminDataStorage implements WPBAdminDataStorage { private static final Logger log = Logger.getLogger(WPBSQLAdminDataStorage.class.getName()); private static final String DEFAULT_KEY_FIELD_NAME = "externalKey"; private static final String CONFIG_KEY_FIELD_NAME = "keyFieldName"; private WPBSQLDataStoreDao sqlDataStorageDao; private String keyFieldName; public WPBSQLAdminDataStorage() { keyFieldName = DEFAULT_KEY_FIELD_NAME; } public void initialize(Map<String, String> params) throws WPBIOException { sqlDataStorageDao = new WPBSQLDataStoreDao(params); if (params != null && params.containsKey(CONFIG_KEY_FIELD_NAME)) { keyFieldName = params.get(CONFIG_KEY_FIELD_NAME); } }
private WPBSQLDataStoreDao.WBSQLQueryOperator adminOperatorToSQLOperator(AdminQueryOperator adminOperator)
webpagebytes/general-cms-plugins
src/main/java/com/webpagebytes/plugins/WPBSQLAdminDataStorage.java
// Path: src/main/java/com/webpagebytes/plugins/WPBSQLDataStoreDao.java // public enum WBSQLQueryOperator{ // LESS_THAN, // GREATER_THAN, // EQUAL, // NOT_EQUAL, // LESS_THAN_OR_EQUAL, // GREATER_THAN_OR_EQUAL // }; // // Path: src/main/java/com/webpagebytes/plugins/WPBSQLDataStoreDao.java // public enum WBSQLSortDirection { // NO_SORT, // ASCENDING, // DESCENDING // };
import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import com.webpagebytes.cms.WPBAdminDataStorage; import com.webpagebytes.cms.exception.WPBIOException; import com.webpagebytes.plugins.WPBSQLDataStoreDao.WBSQLQueryOperator; import com.webpagebytes.plugins.WPBSQLDataStoreDao.WBSQLSortDirection;
public void initialize(Map<String, String> params) throws WPBIOException { sqlDataStorageDao = new WPBSQLDataStoreDao(params); if (params != null && params.containsKey(CONFIG_KEY_FIELD_NAME)) { keyFieldName = params.get(CONFIG_KEY_FIELD_NAME); } } private WPBSQLDataStoreDao.WBSQLQueryOperator adminOperatorToSQLOperator(AdminQueryOperator adminOperator) { switch (adminOperator) { case LESS_THAN: return WBSQLQueryOperator.LESS_THAN; case GREATER_THAN: return WBSQLQueryOperator.GREATER_THAN; case EQUAL: return WBSQLQueryOperator.EQUAL; case GREATER_THAN_OR_EQUAL: return WBSQLQueryOperator.GREATER_THAN_OR_EQUAL; case LESS_THAN_OR_EQUAL: return WBSQLQueryOperator.LESS_THAN_OR_EQUAL; case NOT_EQUAL: return WBSQLQueryOperator.NOT_EQUAL; default: return null; } }
// Path: src/main/java/com/webpagebytes/plugins/WPBSQLDataStoreDao.java // public enum WBSQLQueryOperator{ // LESS_THAN, // GREATER_THAN, // EQUAL, // NOT_EQUAL, // LESS_THAN_OR_EQUAL, // GREATER_THAN_OR_EQUAL // }; // // Path: src/main/java/com/webpagebytes/plugins/WPBSQLDataStoreDao.java // public enum WBSQLSortDirection { // NO_SORT, // ASCENDING, // DESCENDING // }; // Path: src/main/java/com/webpagebytes/plugins/WPBSQLAdminDataStorage.java import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import com.webpagebytes.cms.WPBAdminDataStorage; import com.webpagebytes.cms.exception.WPBIOException; import com.webpagebytes.plugins.WPBSQLDataStoreDao.WBSQLQueryOperator; import com.webpagebytes.plugins.WPBSQLDataStoreDao.WBSQLSortDirection; public void initialize(Map<String, String> params) throws WPBIOException { sqlDataStorageDao = new WPBSQLDataStoreDao(params); if (params != null && params.containsKey(CONFIG_KEY_FIELD_NAME)) { keyFieldName = params.get(CONFIG_KEY_FIELD_NAME); } } private WPBSQLDataStoreDao.WBSQLQueryOperator adminOperatorToSQLOperator(AdminQueryOperator adminOperator) { switch (adminOperator) { case LESS_THAN: return WBSQLQueryOperator.LESS_THAN; case GREATER_THAN: return WBSQLQueryOperator.GREATER_THAN; case EQUAL: return WBSQLQueryOperator.EQUAL; case GREATER_THAN_OR_EQUAL: return WBSQLQueryOperator.GREATER_THAN_OR_EQUAL; case LESS_THAN_OR_EQUAL: return WBSQLQueryOperator.LESS_THAN_OR_EQUAL; case NOT_EQUAL: return WBSQLQueryOperator.NOT_EQUAL; default: return null; } }
private WPBSQLDataStoreDao.WBSQLSortDirection adminDirectionToSQLDirection(AdminSortOperator sortOperator)
commsen/EM
em.storage.nitrite/src/main/java/com/commsen/em/contract/storage/NitriteContractStorage.java
// Path: em.common/src/main/java/com/commsen/em/maven/util/Constants.java // public static final String VAL_EM_HOME = System.getProperty("user.home") + "/.em"; // // Path: em.common/src/main/java/com/commsen/em/storage/ContractStorage.java // public interface ContractStorage { // // boolean saveContractor (File contractor, String coordinates) throws IOException; // // Set<String> getContractors (Requirement requirement); // // Set<String> getAllContracts (); // // }
import static com.commsen.em.maven.util.Constants.VAL_EM_HOME; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map.Entry; import java.util.Set; import org.codehaus.plexus.component.annotations.Component; import org.dizitart.no2.Cursor; import org.dizitart.no2.Document; import org.dizitart.no2.Filter; import org.dizitart.no2.Nitrite; import org.dizitart.no2.NitriteCollection; import org.dizitart.no2.filters.Filters; import org.osgi.resource.Namespace; import org.osgi.resource.Requirement; import com.commsen.em.storage.ContractStorage; import aQute.bnd.header.Attrs; import aQute.bnd.header.Parameters; import aQute.bnd.osgi.Domain; import aQute.bnd.osgi.resource.FilterParser; import aQute.bnd.osgi.resource.FilterParser.And; import aQute.bnd.osgi.resource.FilterParser.Expression; import aQute.bnd.osgi.resource.FilterParser.ExpressionVisitor; import aQute.bnd.osgi.resource.FilterParser.Not; import aQute.bnd.osgi.resource.FilterParser.Op; import aQute.bnd.osgi.resource.FilterParser.Or; import aQute.bnd.osgi.resource.FilterParser.SimpleExpression;
package com.commsen.em.contract.storage; @Component(role=ContractStorage.class) class NitriteContractStorage implements ContractStorage { Set<String> supportedNamespaces = new HashSet<>();
// Path: em.common/src/main/java/com/commsen/em/maven/util/Constants.java // public static final String VAL_EM_HOME = System.getProperty("user.home") + "/.em"; // // Path: em.common/src/main/java/com/commsen/em/storage/ContractStorage.java // public interface ContractStorage { // // boolean saveContractor (File contractor, String coordinates) throws IOException; // // Set<String> getContractors (Requirement requirement); // // Set<String> getAllContracts (); // // } // Path: em.storage.nitrite/src/main/java/com/commsen/em/contract/storage/NitriteContractStorage.java import static com.commsen.em.maven.util.Constants.VAL_EM_HOME; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map.Entry; import java.util.Set; import org.codehaus.plexus.component.annotations.Component; import org.dizitart.no2.Cursor; import org.dizitart.no2.Document; import org.dizitart.no2.Filter; import org.dizitart.no2.Nitrite; import org.dizitart.no2.NitriteCollection; import org.dizitart.no2.filters.Filters; import org.osgi.resource.Namespace; import org.osgi.resource.Requirement; import com.commsen.em.storage.ContractStorage; import aQute.bnd.header.Attrs; import aQute.bnd.header.Parameters; import aQute.bnd.osgi.Domain; import aQute.bnd.osgi.resource.FilterParser; import aQute.bnd.osgi.resource.FilterParser.And; import aQute.bnd.osgi.resource.FilterParser.Expression; import aQute.bnd.osgi.resource.FilterParser.ExpressionVisitor; import aQute.bnd.osgi.resource.FilterParser.Not; import aQute.bnd.osgi.resource.FilterParser.Op; import aQute.bnd.osgi.resource.FilterParser.Or; import aQute.bnd.osgi.resource.FilterParser.SimpleExpression; package com.commsen.em.contract.storage; @Component(role=ContractStorage.class) class NitriteContractStorage implements ContractStorage { Set<String> supportedNamespaces = new HashSet<>();
static String storage = VAL_EM_HOME + "/contracts.db";
commsen/EM
em-maven-extension/src/main/java/com/commsen/em/maven/plugins/EmRegisterContractPlugin.java
// Path: em.common/src/main/java/com/commsen/em/maven/util/Constants.java // public static final String VAL_EXTENSION_VERSION = getVersion("em");
import static com.commsen.em.maven.util.Constants.VAL_EXTENSION_VERSION; import org.apache.maven.MavenExecutionException; import org.apache.maven.model.Plugin; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.component.annotations.Component; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package com.commsen.em.maven.plugins; @Component(role = EmRegisterContractPlugin.class) public class EmRegisterContractPlugin extends DynamicMavenPlugin { private Logger logger = LoggerFactory.getLogger(EmRegisterContractPlugin.class); public void addToPom(MavenProject project) throws MavenExecutionException {
// Path: em.common/src/main/java/com/commsen/em/maven/util/Constants.java // public static final String VAL_EXTENSION_VERSION = getVersion("em"); // Path: em-maven-extension/src/main/java/com/commsen/em/maven/plugins/EmRegisterContractPlugin.java import static com.commsen.em.maven.util.Constants.VAL_EXTENSION_VERSION; import org.apache.maven.MavenExecutionException; import org.apache.maven.model.Plugin; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.component.annotations.Component; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package com.commsen.em.maven.plugins; @Component(role = EmRegisterContractPlugin.class) public class EmRegisterContractPlugin extends DynamicMavenPlugin { private Logger logger = LoggerFactory.getLogger(EmRegisterContractPlugin.class); public void addToPom(MavenProject project) throws MavenExecutionException {
Plugin plugin = createPlugin("com.commsen.em", "em-maven-plugin", VAL_EXTENSION_VERSION, null, "registerContract", "registerContract", "package");
commsen/EM
em-maven-extension/src/main/java/com/commsen/em/maven/plugins/LinkPlugin.java
// Path: em.common/src/main/java/com/commsen/em/maven/util/Constants.java // public static final String VAL_EXTENSION_VERSION = getVersion("em"); // // Path: em.common/src/main/java/com/commsen/em/maven/util/Templates.java // @Component(role = Templates.class) // public class Templates { // // private Configuration cfg = new Configuration(); // // public Templates() { // cfg.setClassForTemplateLoading(this.getClass(), "/"); // cfg.setDefaultEncoding("UTF-8"); // cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); // } // // public Template get (String template) throws IOException { // return cfg.getTemplate(template); // } // // public void process (String template, Object dataModel, Writer out) throws IOException, TemplateException { // get(template).process(dataModel, out); // } // // public String process (String template, Object dataModel) throws IOException, TemplateException { // StringWriter out = new StringWriter(); // get(template).process(dataModel, out); // return out.toString(); // } // // }
import static com.commsen.em.maven.util.Constants.VAL_EXTENSION_VERSION; import org.apache.maven.MavenExecutionException; import org.apache.maven.model.Plugin; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.commsen.em.maven.util.Templates;
package com.commsen.em.maven.plugins; @Component(role = LinkPlugin.class) public class LinkPlugin extends DynamicMavenPlugin { private Logger logger = LoggerFactory.getLogger(LinkPlugin.class); @Requirement
// Path: em.common/src/main/java/com/commsen/em/maven/util/Constants.java // public static final String VAL_EXTENSION_VERSION = getVersion("em"); // // Path: em.common/src/main/java/com/commsen/em/maven/util/Templates.java // @Component(role = Templates.class) // public class Templates { // // private Configuration cfg = new Configuration(); // // public Templates() { // cfg.setClassForTemplateLoading(this.getClass(), "/"); // cfg.setDefaultEncoding("UTF-8"); // cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); // } // // public Template get (String template) throws IOException { // return cfg.getTemplate(template); // } // // public void process (String template, Object dataModel, Writer out) throws IOException, TemplateException { // get(template).process(dataModel, out); // } // // public String process (String template, Object dataModel) throws IOException, TemplateException { // StringWriter out = new StringWriter(); // get(template).process(dataModel, out); // return out.toString(); // } // // } // Path: em-maven-extension/src/main/java/com/commsen/em/maven/plugins/LinkPlugin.java import static com.commsen.em.maven.util.Constants.VAL_EXTENSION_VERSION; import org.apache.maven.MavenExecutionException; import org.apache.maven.model.Plugin; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.commsen.em.maven.util.Templates; package com.commsen.em.maven.plugins; @Component(role = LinkPlugin.class) public class LinkPlugin extends DynamicMavenPlugin { private Logger logger = LoggerFactory.getLogger(LinkPlugin.class); @Requirement
private Templates templates;
commsen/EM
em-maven-extension/src/main/java/com/commsen/em/maven/plugins/LinkPlugin.java
// Path: em.common/src/main/java/com/commsen/em/maven/util/Constants.java // public static final String VAL_EXTENSION_VERSION = getVersion("em"); // // Path: em.common/src/main/java/com/commsen/em/maven/util/Templates.java // @Component(role = Templates.class) // public class Templates { // // private Configuration cfg = new Configuration(); // // public Templates() { // cfg.setClassForTemplateLoading(this.getClass(), "/"); // cfg.setDefaultEncoding("UTF-8"); // cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); // } // // public Template get (String template) throws IOException { // return cfg.getTemplate(template); // } // // public void process (String template, Object dataModel, Writer out) throws IOException, TemplateException { // get(template).process(dataModel, out); // } // // public String process (String template, Object dataModel) throws IOException, TemplateException { // StringWriter out = new StringWriter(); // get(template).process(dataModel, out); // return out.toString(); // } // // }
import static com.commsen.em.maven.util.Constants.VAL_EXTENSION_VERSION; import org.apache.maven.MavenExecutionException; import org.apache.maven.model.Plugin; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.commsen.em.maven.util.Templates;
package com.commsen.em.maven.plugins; @Component(role = LinkPlugin.class) public class LinkPlugin extends DynamicMavenPlugin { private Logger logger = LoggerFactory.getLogger(LinkPlugin.class); @Requirement private Templates templates; public void addToBuild(MavenProject project) throws MavenExecutionException { project.getBuild().getPlugins().add(0, preparePlugin()); logger.info("Added `em-maven-plugin:link` to keep track of modules"); } private Plugin preparePlugin() throws MavenExecutionException { Plugin plugin = createPlugin( // "com.commsen.em", // "em-maven-plugin", //
// Path: em.common/src/main/java/com/commsen/em/maven/util/Constants.java // public static final String VAL_EXTENSION_VERSION = getVersion("em"); // // Path: em.common/src/main/java/com/commsen/em/maven/util/Templates.java // @Component(role = Templates.class) // public class Templates { // // private Configuration cfg = new Configuration(); // // public Templates() { // cfg.setClassForTemplateLoading(this.getClass(), "/"); // cfg.setDefaultEncoding("UTF-8"); // cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); // } // // public Template get (String template) throws IOException { // return cfg.getTemplate(template); // } // // public void process (String template, Object dataModel, Writer out) throws IOException, TemplateException { // get(template).process(dataModel, out); // } // // public String process (String template, Object dataModel) throws IOException, TemplateException { // StringWriter out = new StringWriter(); // get(template).process(dataModel, out); // return out.toString(); // } // // } // Path: em-maven-extension/src/main/java/com/commsen/em/maven/plugins/LinkPlugin.java import static com.commsen.em.maven.util.Constants.VAL_EXTENSION_VERSION; import org.apache.maven.MavenExecutionException; import org.apache.maven.model.Plugin; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.commsen.em.maven.util.Templates; package com.commsen.em.maven.plugins; @Component(role = LinkPlugin.class) public class LinkPlugin extends DynamicMavenPlugin { private Logger logger = LoggerFactory.getLogger(LinkPlugin.class); @Requirement private Templates templates; public void addToBuild(MavenProject project) throws MavenExecutionException { project.getBuild().getPlugins().add(0, preparePlugin()); logger.info("Added `em-maven-plugin:link` to keep track of modules"); } private Plugin preparePlugin() throws MavenExecutionException { Plugin plugin = createPlugin( // "com.commsen.em", // "em-maven-plugin", //
VAL_EXTENSION_VERSION, //
commsen/EM
em-maven-extension/src/main/java/com/commsen/em/maven/plugins/DynamicMavenPlugin.java
// Path: em.common/src/main/java/com/commsen/em/maven/util/MavenConfig.java // @Component(role = MavenConfig.class) // public class MavenConfig { // // public Xpp3Dom asXpp3Dom(String config) throws MavenExecutionException { // try { // return Xpp3DomBuilder.build(new StringReader(config)); // } catch (Exception e) { // throw new MavenExecutionException("Error parsing config", e); // } // } // // }
import org.apache.maven.MavenExecutionException; import org.apache.maven.model.Plugin; import org.apache.maven.model.PluginExecution; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.component.annotations.Requirement; import com.commsen.em.maven.util.MavenConfig;
package com.commsen.em.maven.plugins; public abstract class DynamicMavenPlugin { @Requirement
// Path: em.common/src/main/java/com/commsen/em/maven/util/MavenConfig.java // @Component(role = MavenConfig.class) // public class MavenConfig { // // public Xpp3Dom asXpp3Dom(String config) throws MavenExecutionException { // try { // return Xpp3DomBuilder.build(new StringReader(config)); // } catch (Exception e) { // throw new MavenExecutionException("Error parsing config", e); // } // } // // } // Path: em-maven-extension/src/main/java/com/commsen/em/maven/plugins/DynamicMavenPlugin.java import org.apache.maven.MavenExecutionException; import org.apache.maven.model.Plugin; import org.apache.maven.model.PluginExecution; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.component.annotations.Requirement; import com.commsen.em.maven.util.MavenConfig; package com.commsen.em.maven.plugins; public abstract class DynamicMavenPlugin { @Requirement
MavenConfig mavenConfig;
commsen/EM
em-maven-plugin/src/main/java/org/em/maven/plugin/AddContractorsMojo.java
// Path: em.common/src/main/java/com/commsen/em/storage/ContractStorage.java // public interface ContractStorage { // // boolean saveContractor (File contractor, String coordinates) throws IOException; // // Set<String> getContractors (Requirement requirement); // // Set<String> getAllContracts (); // // }
import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.apache.maven.shared.artifact.resolve.ArtifactResolver; import org.beryx.textio.InputReader.ValueChecker; import org.beryx.textio.TextIO; import org.beryx.textio.TextIoFactory; import org.codehaus.plexus.component.annotations.Requirement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.commsen.em.storage.ContractStorage; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.stream.JsonReader; import aQute.libg.tuple.Pair;
package org.em.maven.plugin; /** * Goal which ... */ @Mojo(name = "addContractors", requiresProject = false) public class AddContractorsMojo extends AbstractMojo { private static final Logger logger = LoggerFactory.getLogger(AddContractorsMojo.class); private TextIO textIO = TextIoFactory.getTextIO(); @Requirement private ArtifactResolver artifactResolver; @Parameter(defaultValue = "${project}", readonly = true, required = true) MavenProject project; @Component
// Path: em.common/src/main/java/com/commsen/em/storage/ContractStorage.java // public interface ContractStorage { // // boolean saveContractor (File contractor, String coordinates) throws IOException; // // Set<String> getContractors (Requirement requirement); // // Set<String> getAllContracts (); // // } // Path: em-maven-plugin/src/main/java/org/em/maven/plugin/AddContractorsMojo.java import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.apache.maven.shared.artifact.resolve.ArtifactResolver; import org.beryx.textio.InputReader.ValueChecker; import org.beryx.textio.TextIO; import org.beryx.textio.TextIoFactory; import org.codehaus.plexus.component.annotations.Requirement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.commsen.em.storage.ContractStorage; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.stream.JsonReader; import aQute.libg.tuple.Pair; package org.em.maven.plugin; /** * Goal which ... */ @Mojo(name = "addContractors", requiresProject = false) public class AddContractorsMojo extends AbstractMojo { private static final Logger logger = LoggerFactory.getLogger(AddContractorsMojo.class); private TextIO textIO = TextIoFactory.getTextIO(); @Requirement private ArtifactResolver artifactResolver; @Parameter(defaultValue = "${project}", readonly = true, required = true) MavenProject project; @Component
ContractStorage contractStorage;
commsen/EM
em-maven-plugin/src/main/java/org/em/maven/plugin/RegisterContractMojo.java
// Path: em.common/src/main/java/com/commsen/em/storage/ContractStorage.java // public interface ContractStorage { // // boolean saveContractor (File contractor, String coordinates) throws IOException; // // Set<String> getContractors (Requirement requirement); // // Set<String> getAllContracts (); // // }
import java.io.IOException; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.commsen.em.storage.ContractStorage;
package org.em.maven.plugin; /** * Goal which ... */ @Mojo(name = "registerContract", defaultPhase = LifecyclePhase.PACKAGE, requiresProject = true) public class RegisterContractMojo extends AbstractMojo { private static final Logger logger = LoggerFactory.getLogger(RegisterContractMojo.class); @Parameter(defaultValue = "${project}", readonly = true) MavenProject project;
// Path: em.common/src/main/java/com/commsen/em/storage/ContractStorage.java // public interface ContractStorage { // // boolean saveContractor (File contractor, String coordinates) throws IOException; // // Set<String> getContractors (Requirement requirement); // // Set<String> getAllContracts (); // // } // Path: em-maven-plugin/src/main/java/org/em/maven/plugin/RegisterContractMojo.java import java.io.IOException; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.commsen.em.storage.ContractStorage; package org.em.maven.plugin; /** * Goal which ... */ @Mojo(name = "registerContract", defaultPhase = LifecyclePhase.PACKAGE, requiresProject = true) public class RegisterContractMojo extends AbstractMojo { private static final Logger logger = LoggerFactory.getLogger(RegisterContractMojo.class); @Parameter(defaultValue = "${project}", readonly = true) MavenProject project;
@Component (role = ContractStorage.class)
commsen/EM
em.storage.nitrite/src/main/java/com/commsen/em/contract/storage/NitritePathStorage.java
// Path: em.common/src/main/java/com/commsen/em/maven/util/Constants.java // public static final String VAL_EM_HOME = System.getProperty("user.home") + "/.em"; // // Path: em.common/src/main/java/com/commsen/em/storage/PathsStorage.java // public interface PathsStorage extends Closeable { // // void savePaths(Path m2path, Path projectPath, Path emPath); // // Path getM2Path (Path path); // // Path getProjectPath (Path path); // // Path getEmPath (Path path); // // }
import static com.commsen.em.maven.util.Constants.VAL_EM_HOME; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.codehaus.plexus.component.annotations.Component; import org.dizitart.no2.Document; import org.dizitart.no2.Nitrite; import org.dizitart.no2.NitriteCollection; import static org.dizitart.no2.filters.Filters.*; import com.commsen.em.storage.PathsStorage;
package com.commsen.em.contract.storage; @Component(role = PathsStorage.class) class NitritePathStorage implements PathsStorage {
// Path: em.common/src/main/java/com/commsen/em/maven/util/Constants.java // public static final String VAL_EM_HOME = System.getProperty("user.home") + "/.em"; // // Path: em.common/src/main/java/com/commsen/em/storage/PathsStorage.java // public interface PathsStorage extends Closeable { // // void savePaths(Path m2path, Path projectPath, Path emPath); // // Path getM2Path (Path path); // // Path getProjectPath (Path path); // // Path getEmPath (Path path); // // } // Path: em.storage.nitrite/src/main/java/com/commsen/em/contract/storage/NitritePathStorage.java import static com.commsen.em.maven.util.Constants.VAL_EM_HOME; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.codehaus.plexus.component.annotations.Component; import org.dizitart.no2.Document; import org.dizitart.no2.Nitrite; import org.dizitart.no2.NitriteCollection; import static org.dizitart.no2.filters.Filters.*; import com.commsen.em.storage.PathsStorage; package com.commsen.em.contract.storage; @Component(role = PathsStorage.class) class NitritePathStorage implements PathsStorage {
static String storage = VAL_EM_HOME + "/paths.db";
commsen/EM
em-maven-extension/src/test/java/com/commsen/en/maven/util/VersionTest.java
// Path: em.common/src/main/java/com/commsen/em/maven/util/Version.java // public class Version { // // // public static String semantic (String version) { // // if (version == null || version.trim().isEmpty()) return "0.0.0"; // // int dashIndex = version.indexOf("-"); // String main = version; // String rest = ""; // if (dashIndex >= 0) { // main = version.substring(0, dashIndex); // rest = version.substring(dashIndex+1); // } // // String[] groups = main.split("\\."); // // StringBuilder result = new StringBuilder(); // StringBuilder additional = new StringBuilder(); // // int semGroups = 0; // for (int i = 0; i < groups.length; i++) { // Pair<Integer, String> pair = digitalize(groups[i]); // if (pair.getFirst() > 0 || semGroups < 3) { // if (semGroups != 0) { // result.append("."); // } // result.append(pair.getFirst()); // semGroups++; // } // if (!pair.getSecond().isEmpty()) { // if (additional.length() > 0 ) additional.append("_"); // additional.append(pair.getSecond().replaceAll("\\.", "_")); // } // } // // if (semGroups == 0) { // result.append("0.0.0"); // } else { // while (semGroups++ < 3) { // result.append(".0"); // } // } // // String delimiter = "."; // if (additional.length() > 0) { // result.append(delimiter).append(additional); // delimiter = "-"; // } // // if (rest.length() > 0) { // result.append(delimiter).append(rest.replaceAll("\\.", "_")); // } // // return result.toString(); // } // // public static Pair<Integer, String> digitalize (String string) { // // int i = 0; // while (i < string.length() && Character.isDigit(string.charAt(i))) i++; // // if (i == 0) { // return new Pair<Integer, String>(0, string.trim()); // } // // Integer number = Integer.parseInt(string.substring(0, i)); // String rest = string.substring(i).trim(); // // return new Pair<Integer, String>(number, rest); // } // // // }
import org.junit.Assert; import org.junit.Test; import com.commsen.em.maven.util.Version;
package com.commsen.en.maven.util; public class VersionTest { @Test public void semanticVersioning () { // more than 3 digits
// Path: em.common/src/main/java/com/commsen/em/maven/util/Version.java // public class Version { // // // public static String semantic (String version) { // // if (version == null || version.trim().isEmpty()) return "0.0.0"; // // int dashIndex = version.indexOf("-"); // String main = version; // String rest = ""; // if (dashIndex >= 0) { // main = version.substring(0, dashIndex); // rest = version.substring(dashIndex+1); // } // // String[] groups = main.split("\\."); // // StringBuilder result = new StringBuilder(); // StringBuilder additional = new StringBuilder(); // // int semGroups = 0; // for (int i = 0; i < groups.length; i++) { // Pair<Integer, String> pair = digitalize(groups[i]); // if (pair.getFirst() > 0 || semGroups < 3) { // if (semGroups != 0) { // result.append("."); // } // result.append(pair.getFirst()); // semGroups++; // } // if (!pair.getSecond().isEmpty()) { // if (additional.length() > 0 ) additional.append("_"); // additional.append(pair.getSecond().replaceAll("\\.", "_")); // } // } // // if (semGroups == 0) { // result.append("0.0.0"); // } else { // while (semGroups++ < 3) { // result.append(".0"); // } // } // // String delimiter = "."; // if (additional.length() > 0) { // result.append(delimiter).append(additional); // delimiter = "-"; // } // // if (rest.length() > 0) { // result.append(delimiter).append(rest.replaceAll("\\.", "_")); // } // // return result.toString(); // } // // public static Pair<Integer, String> digitalize (String string) { // // int i = 0; // while (i < string.length() && Character.isDigit(string.charAt(i))) i++; // // if (i == 0) { // return new Pair<Integer, String>(0, string.trim()); // } // // Integer number = Integer.parseInt(string.substring(0, i)); // String rest = string.substring(i).trim(); // // return new Pair<Integer, String>(number, rest); // } // // // } // Path: em-maven-extension/src/test/java/com/commsen/en/maven/util/VersionTest.java import org.junit.Assert; import org.junit.Test; import com.commsen.em.maven.util.Version; package com.commsen.en.maven.util; public class VersionTest { @Test public void semanticVersioning () { // more than 3 digits
Assert.assertEquals("1.2.3.4", Version.semantic("1.2.3.4"));
jwtk/jjwt
api/src/main/java/io/jsonwebtoken/JwtParser.java
// Path: api/src/main/java/io/jsonwebtoken/io/Decoder.java // public interface Decoder<T, R> { // // R decode(T t) throws DecodingException; // } // // Path: api/src/main/java/io/jsonwebtoken/io/Deserializer.java // public interface Deserializer<T> { // // T deserialize(byte[] bytes) throws DeserializationException; // } // // Path: api/src/main/java/io/jsonwebtoken/security/SignatureException.java // public class SignatureException extends io.jsonwebtoken.SignatureException { // // public SignatureException(String message) { // super(message); // } // // public SignatureException(String message, Throwable cause) { // super(message, cause); // } // }
import io.jsonwebtoken.io.Decoder; import io.jsonwebtoken.io.Deserializer; import io.jsonwebtoken.security.SignatureException; import java.security.Key; import java.util.Date; import java.util.Map;
* <p>However, if you want to use a compression algorithm other than {@code DEF} or {@code GZIP}, you must implement * your own {@link CompressionCodecResolver} and specify that via this method and also when * {@link io.jsonwebtoken.JwtBuilder#compressWith(CompressionCodec) building} JWTs.</p> * * @param compressionCodecResolver the compression codec resolver used to decompress the JWT body. * @return the parser for method chaining. * @since 0.6.0 * @deprecated see {@link JwtParserBuilder#setCompressionCodecResolver(CompressionCodecResolver)}. * To construct a JwtParser use the corresponding builder via {@link Jwts#parserBuilder()}. This will construct an * immutable JwtParser. * <p><b>NOTE: this method will be removed before version 1.0</b> */ @Deprecated JwtParser setCompressionCodecResolver(CompressionCodecResolver compressionCodecResolver); /** * Perform Base64Url decoding with the specified Decoder * * <p>JJWT uses a spec-compliant decoder that works on all supported JDK versions, but you may call this method * to specify a different decoder if you desire.</p> * * @param base64UrlDecoder the decoder to use when Base64Url-decoding * @return the parser for method chaining. * @since 0.10.0 * @deprecated see {@link JwtParserBuilder#base64UrlDecodeWith(Decoder)}. * To construct a JwtParser use the corresponding builder via {@link Jwts#parserBuilder()}. This will construct an * immutable JwtParser. * <p><b>NOTE: this method will be removed before version 1.0</b> */ @Deprecated
// Path: api/src/main/java/io/jsonwebtoken/io/Decoder.java // public interface Decoder<T, R> { // // R decode(T t) throws DecodingException; // } // // Path: api/src/main/java/io/jsonwebtoken/io/Deserializer.java // public interface Deserializer<T> { // // T deserialize(byte[] bytes) throws DeserializationException; // } // // Path: api/src/main/java/io/jsonwebtoken/security/SignatureException.java // public class SignatureException extends io.jsonwebtoken.SignatureException { // // public SignatureException(String message) { // super(message); // } // // public SignatureException(String message, Throwable cause) { // super(message, cause); // } // } // Path: api/src/main/java/io/jsonwebtoken/JwtParser.java import io.jsonwebtoken.io.Decoder; import io.jsonwebtoken.io.Deserializer; import io.jsonwebtoken.security.SignatureException; import java.security.Key; import java.util.Date; import java.util.Map; * <p>However, if you want to use a compression algorithm other than {@code DEF} or {@code GZIP}, you must implement * your own {@link CompressionCodecResolver} and specify that via this method and also when * {@link io.jsonwebtoken.JwtBuilder#compressWith(CompressionCodec) building} JWTs.</p> * * @param compressionCodecResolver the compression codec resolver used to decompress the JWT body. * @return the parser for method chaining. * @since 0.6.0 * @deprecated see {@link JwtParserBuilder#setCompressionCodecResolver(CompressionCodecResolver)}. * To construct a JwtParser use the corresponding builder via {@link Jwts#parserBuilder()}. This will construct an * immutable JwtParser. * <p><b>NOTE: this method will be removed before version 1.0</b> */ @Deprecated JwtParser setCompressionCodecResolver(CompressionCodecResolver compressionCodecResolver); /** * Perform Base64Url decoding with the specified Decoder * * <p>JJWT uses a spec-compliant decoder that works on all supported JDK versions, but you may call this method * to specify a different decoder if you desire.</p> * * @param base64UrlDecoder the decoder to use when Base64Url-decoding * @return the parser for method chaining. * @since 0.10.0 * @deprecated see {@link JwtParserBuilder#base64UrlDecodeWith(Decoder)}. * To construct a JwtParser use the corresponding builder via {@link Jwts#parserBuilder()}. This will construct an * immutable JwtParser. * <p><b>NOTE: this method will be removed before version 1.0</b> */ @Deprecated
JwtParser base64UrlDecodeWith(Decoder<String, byte[]> base64UrlDecoder);
jwtk/jjwt
api/src/main/java/io/jsonwebtoken/JwtParser.java
// Path: api/src/main/java/io/jsonwebtoken/io/Decoder.java // public interface Decoder<T, R> { // // R decode(T t) throws DecodingException; // } // // Path: api/src/main/java/io/jsonwebtoken/io/Deserializer.java // public interface Deserializer<T> { // // T deserialize(byte[] bytes) throws DeserializationException; // } // // Path: api/src/main/java/io/jsonwebtoken/security/SignatureException.java // public class SignatureException extends io.jsonwebtoken.SignatureException { // // public SignatureException(String message) { // super(message); // } // // public SignatureException(String message, Throwable cause) { // super(message, cause); // } // }
import io.jsonwebtoken.io.Decoder; import io.jsonwebtoken.io.Deserializer; import io.jsonwebtoken.security.SignatureException; import java.security.Key; import java.util.Date; import java.util.Map;
* @param base64UrlDecoder the decoder to use when Base64Url-decoding * @return the parser for method chaining. * @since 0.10.0 * @deprecated see {@link JwtParserBuilder#base64UrlDecodeWith(Decoder)}. * To construct a JwtParser use the corresponding builder via {@link Jwts#parserBuilder()}. This will construct an * immutable JwtParser. * <p><b>NOTE: this method will be removed before version 1.0</b> */ @Deprecated JwtParser base64UrlDecodeWith(Decoder<String, byte[]> base64UrlDecoder); /** * Uses the specified deserializer to convert JSON Strings (UTF-8 byte arrays) into Java Map objects. This is * used by the parser after Base64Url-decoding to convert JWT/JWS/JWT JSON headers and claims into Java Map * objects. * * <p>If this method is not called, JJWT will use whatever deserializer it can find at runtime, checking for the * presence of well-known implementations such Jackson, Gson, and org.json. If one of these is not found * in the runtime classpath, an exception will be thrown when one of the various {@code parse}* methods is * invoked.</p> * * @param deserializer the deserializer to use when converting JSON Strings (UTF-8 byte arrays) into Map objects. * @return the parser for method chaining. * @since 0.10.0 * @deprecated see {@link JwtParserBuilder#deserializeJsonWith(Deserializer)} )}. * To construct a JwtParser use the corresponding builder via {@link Jwts#parserBuilder()}. This will construct an * immutable JwtParser. * <p><b>NOTE: this method will be removed before version 1.0</b> */ @Deprecated
// Path: api/src/main/java/io/jsonwebtoken/io/Decoder.java // public interface Decoder<T, R> { // // R decode(T t) throws DecodingException; // } // // Path: api/src/main/java/io/jsonwebtoken/io/Deserializer.java // public interface Deserializer<T> { // // T deserialize(byte[] bytes) throws DeserializationException; // } // // Path: api/src/main/java/io/jsonwebtoken/security/SignatureException.java // public class SignatureException extends io.jsonwebtoken.SignatureException { // // public SignatureException(String message) { // super(message); // } // // public SignatureException(String message, Throwable cause) { // super(message, cause); // } // } // Path: api/src/main/java/io/jsonwebtoken/JwtParser.java import io.jsonwebtoken.io.Decoder; import io.jsonwebtoken.io.Deserializer; import io.jsonwebtoken.security.SignatureException; import java.security.Key; import java.util.Date; import java.util.Map; * @param base64UrlDecoder the decoder to use when Base64Url-decoding * @return the parser for method chaining. * @since 0.10.0 * @deprecated see {@link JwtParserBuilder#base64UrlDecodeWith(Decoder)}. * To construct a JwtParser use the corresponding builder via {@link Jwts#parserBuilder()}. This will construct an * immutable JwtParser. * <p><b>NOTE: this method will be removed before version 1.0</b> */ @Deprecated JwtParser base64UrlDecodeWith(Decoder<String, byte[]> base64UrlDecoder); /** * Uses the specified deserializer to convert JSON Strings (UTF-8 byte arrays) into Java Map objects. This is * used by the parser after Base64Url-decoding to convert JWT/JWS/JWT JSON headers and claims into Java Map * objects. * * <p>If this method is not called, JJWT will use whatever deserializer it can find at runtime, checking for the * presence of well-known implementations such Jackson, Gson, and org.json. If one of these is not found * in the runtime classpath, an exception will be thrown when one of the various {@code parse}* methods is * invoked.</p> * * @param deserializer the deserializer to use when converting JSON Strings (UTF-8 byte arrays) into Map objects. * @return the parser for method chaining. * @since 0.10.0 * @deprecated see {@link JwtParserBuilder#deserializeJsonWith(Deserializer)} )}. * To construct a JwtParser use the corresponding builder via {@link Jwts#parserBuilder()}. This will construct an * immutable JwtParser. * <p><b>NOTE: this method will be removed before version 1.0</b> */ @Deprecated
JwtParser deserializeJsonWith(Deserializer<Map<String,?>> deserializer);
jwtk/jjwt
api/src/main/java/io/jsonwebtoken/JwtParser.java
// Path: api/src/main/java/io/jsonwebtoken/io/Decoder.java // public interface Decoder<T, R> { // // R decode(T t) throws DecodingException; // } // // Path: api/src/main/java/io/jsonwebtoken/io/Deserializer.java // public interface Deserializer<T> { // // T deserialize(byte[] bytes) throws DeserializationException; // } // // Path: api/src/main/java/io/jsonwebtoken/security/SignatureException.java // public class SignatureException extends io.jsonwebtoken.SignatureException { // // public SignatureException(String message) { // super(message); // } // // public SignatureException(String message, Throwable cause) { // super(message, cause); // } // }
import io.jsonwebtoken.io.Decoder; import io.jsonwebtoken.io.Deserializer; import io.jsonwebtoken.security.SignatureException; import java.security.Key; import java.util.Date; import java.util.Map;
* @return {@code true} if the specified JWT compact string represents a signed JWT (aka a 'JWS'), {@code false} * otherwise. */ boolean isSigned(String jwt); /** * Parses the specified compact serialized JWT string based on the builder's current configuration state and * returns the resulting JWT or JWS instance. * <p> * <p>This method returns a JWT or JWS based on the parsed string. Because it may be cumbersome to determine if it * is a JWT or JWS, or if the body/payload is a Claims or String with {@code instanceof} checks, the * {@link #parse(String, JwtHandler) parse(String,JwtHandler)} method allows for a type-safe callback approach that * may help reduce code or instanceof checks.</p> * * @param jwt the compact serialized JWT to parse * @return the specified compact serialized JWT string based on the builder's current configuration state. * @throws MalformedJwtException if the specified JWT was incorrectly constructed (and therefore invalid). * Invalid * JWTs should not be trusted and should be discarded. * @throws SignatureException if a JWS signature was discovered, but could not be verified. JWTs that fail * signature validation should not be trusted and should be discarded. * @throws ExpiredJwtException if the specified JWT is a Claims JWT and the Claims has an expiration time * before the time this method is invoked. * @throws IllegalArgumentException if the specified string is {@code null} or empty or only whitespace. * @see #parse(String, JwtHandler) * @see #parsePlaintextJwt(String) * @see #parseClaimsJwt(String) * @see #parsePlaintextJws(String) * @see #parseClaimsJws(String) */
// Path: api/src/main/java/io/jsonwebtoken/io/Decoder.java // public interface Decoder<T, R> { // // R decode(T t) throws DecodingException; // } // // Path: api/src/main/java/io/jsonwebtoken/io/Deserializer.java // public interface Deserializer<T> { // // T deserialize(byte[] bytes) throws DeserializationException; // } // // Path: api/src/main/java/io/jsonwebtoken/security/SignatureException.java // public class SignatureException extends io.jsonwebtoken.SignatureException { // // public SignatureException(String message) { // super(message); // } // // public SignatureException(String message, Throwable cause) { // super(message, cause); // } // } // Path: api/src/main/java/io/jsonwebtoken/JwtParser.java import io.jsonwebtoken.io.Decoder; import io.jsonwebtoken.io.Deserializer; import io.jsonwebtoken.security.SignatureException; import java.security.Key; import java.util.Date; import java.util.Map; * @return {@code true} if the specified JWT compact string represents a signed JWT (aka a 'JWS'), {@code false} * otherwise. */ boolean isSigned(String jwt); /** * Parses the specified compact serialized JWT string based on the builder's current configuration state and * returns the resulting JWT or JWS instance. * <p> * <p>This method returns a JWT or JWS based on the parsed string. Because it may be cumbersome to determine if it * is a JWT or JWS, or if the body/payload is a Claims or String with {@code instanceof} checks, the * {@link #parse(String, JwtHandler) parse(String,JwtHandler)} method allows for a type-safe callback approach that * may help reduce code or instanceof checks.</p> * * @param jwt the compact serialized JWT to parse * @return the specified compact serialized JWT string based on the builder's current configuration state. * @throws MalformedJwtException if the specified JWT was incorrectly constructed (and therefore invalid). * Invalid * JWTs should not be trusted and should be discarded. * @throws SignatureException if a JWS signature was discovered, but could not be verified. JWTs that fail * signature validation should not be trusted and should be discarded. * @throws ExpiredJwtException if the specified JWT is a Claims JWT and the Claims has an expiration time * before the time this method is invoked. * @throws IllegalArgumentException if the specified string is {@code null} or empty or only whitespace. * @see #parse(String, JwtHandler) * @see #parsePlaintextJwt(String) * @see #parseClaimsJwt(String) * @see #parsePlaintextJws(String) * @see #parseClaimsJws(String) */
Jwt parse(String jwt) throws ExpiredJwtException, MalformedJwtException, SignatureException, IllegalArgumentException;
jwtk/jjwt
impl/src/main/java/io/jsonwebtoken/impl/AndroidBase64Codec.java
// Path: api/src/main/java/io/jsonwebtoken/io/Decoders.java // public final class Decoders { // // public static final Decoder<String, byte[]> BASE64 = new ExceptionPropagatingDecoder<>(new Base64Decoder()); // public static final Decoder<String, byte[]> BASE64URL = new ExceptionPropagatingDecoder<>(new Base64UrlDecoder()); // // private Decoders() { //prevent instantiation // } // } // // Path: api/src/main/java/io/jsonwebtoken/io/Encoders.java // public final class Encoders { // // public static final Encoder<byte[], String> BASE64 = new ExceptionPropagatingEncoder<>(new Base64Encoder()); // public static final Encoder<byte[], String> BASE64URL = new ExceptionPropagatingEncoder<>(new Base64UrlEncoder()); // // private Encoders() { //prevent instantiation // } // }
import io.jsonwebtoken.io.Decoders; import io.jsonwebtoken.io.Encoders;
/* * Copyright (C) 2015 jsonwebtoken.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 io.jsonwebtoken.impl; /** * @deprecated since 0.10.0 - will be removed before 1.0.0. Use {@code io.jsonwebtoken.io.Encoders#BASE64} * or {@code io.jsonwebtoken.io.Decoders#BASE64} instead. */ @Deprecated public class AndroidBase64Codec extends AbstractTextCodec { @Override public String encode(byte[] data) {
// Path: api/src/main/java/io/jsonwebtoken/io/Decoders.java // public final class Decoders { // // public static final Decoder<String, byte[]> BASE64 = new ExceptionPropagatingDecoder<>(new Base64Decoder()); // public static final Decoder<String, byte[]> BASE64URL = new ExceptionPropagatingDecoder<>(new Base64UrlDecoder()); // // private Decoders() { //prevent instantiation // } // } // // Path: api/src/main/java/io/jsonwebtoken/io/Encoders.java // public final class Encoders { // // public static final Encoder<byte[], String> BASE64 = new ExceptionPropagatingEncoder<>(new Base64Encoder()); // public static final Encoder<byte[], String> BASE64URL = new ExceptionPropagatingEncoder<>(new Base64UrlEncoder()); // // private Encoders() { //prevent instantiation // } // } // Path: impl/src/main/java/io/jsonwebtoken/impl/AndroidBase64Codec.java import io.jsonwebtoken.io.Decoders; import io.jsonwebtoken.io.Encoders; /* * Copyright (C) 2015 jsonwebtoken.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 io.jsonwebtoken.impl; /** * @deprecated since 0.10.0 - will be removed before 1.0.0. Use {@code io.jsonwebtoken.io.Encoders#BASE64} * or {@code io.jsonwebtoken.io.Decoders#BASE64} instead. */ @Deprecated public class AndroidBase64Codec extends AbstractTextCodec { @Override public String encode(byte[] data) {
return Encoders.BASE64.encode(data);
jwtk/jjwt
impl/src/main/java/io/jsonwebtoken/impl/AndroidBase64Codec.java
// Path: api/src/main/java/io/jsonwebtoken/io/Decoders.java // public final class Decoders { // // public static final Decoder<String, byte[]> BASE64 = new ExceptionPropagatingDecoder<>(new Base64Decoder()); // public static final Decoder<String, byte[]> BASE64URL = new ExceptionPropagatingDecoder<>(new Base64UrlDecoder()); // // private Decoders() { //prevent instantiation // } // } // // Path: api/src/main/java/io/jsonwebtoken/io/Encoders.java // public final class Encoders { // // public static final Encoder<byte[], String> BASE64 = new ExceptionPropagatingEncoder<>(new Base64Encoder()); // public static final Encoder<byte[], String> BASE64URL = new ExceptionPropagatingEncoder<>(new Base64UrlEncoder()); // // private Encoders() { //prevent instantiation // } // }
import io.jsonwebtoken.io.Decoders; import io.jsonwebtoken.io.Encoders;
/* * Copyright (C) 2015 jsonwebtoken.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 io.jsonwebtoken.impl; /** * @deprecated since 0.10.0 - will be removed before 1.0.0. Use {@code io.jsonwebtoken.io.Encoders#BASE64} * or {@code io.jsonwebtoken.io.Decoders#BASE64} instead. */ @Deprecated public class AndroidBase64Codec extends AbstractTextCodec { @Override public String encode(byte[] data) { return Encoders.BASE64.encode(data); } @Override public byte[] decode(String encoded) {
// Path: api/src/main/java/io/jsonwebtoken/io/Decoders.java // public final class Decoders { // // public static final Decoder<String, byte[]> BASE64 = new ExceptionPropagatingDecoder<>(new Base64Decoder()); // public static final Decoder<String, byte[]> BASE64URL = new ExceptionPropagatingDecoder<>(new Base64UrlDecoder()); // // private Decoders() { //prevent instantiation // } // } // // Path: api/src/main/java/io/jsonwebtoken/io/Encoders.java // public final class Encoders { // // public static final Encoder<byte[], String> BASE64 = new ExceptionPropagatingEncoder<>(new Base64Encoder()); // public static final Encoder<byte[], String> BASE64URL = new ExceptionPropagatingEncoder<>(new Base64UrlEncoder()); // // private Encoders() { //prevent instantiation // } // } // Path: impl/src/main/java/io/jsonwebtoken/impl/AndroidBase64Codec.java import io.jsonwebtoken.io.Decoders; import io.jsonwebtoken.io.Encoders; /* * Copyright (C) 2015 jsonwebtoken.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 io.jsonwebtoken.impl; /** * @deprecated since 0.10.0 - will be removed before 1.0.0. Use {@code io.jsonwebtoken.io.Encoders#BASE64} * or {@code io.jsonwebtoken.io.Decoders#BASE64} instead. */ @Deprecated public class AndroidBase64Codec extends AbstractTextCodec { @Override public String encode(byte[] data) { return Encoders.BASE64.encode(data); } @Override public byte[] decode(String encoded) {
return Decoders.BASE64.decode(encoded);
jwtk/jjwt
impl/src/main/java/io/jsonwebtoken/impl/Base64UrlCodec.java
// Path: api/src/main/java/io/jsonwebtoken/io/Decoders.java // public final class Decoders { // // public static final Decoder<String, byte[]> BASE64 = new ExceptionPropagatingDecoder<>(new Base64Decoder()); // public static final Decoder<String, byte[]> BASE64URL = new ExceptionPropagatingDecoder<>(new Base64UrlDecoder()); // // private Decoders() { //prevent instantiation // } // } // // Path: api/src/main/java/io/jsonwebtoken/io/Encoders.java // public final class Encoders { // // public static final Encoder<byte[], String> BASE64 = new ExceptionPropagatingEncoder<>(new Base64Encoder()); // public static final Encoder<byte[], String> BASE64URL = new ExceptionPropagatingEncoder<>(new Base64UrlEncoder()); // // private Encoders() { //prevent instantiation // } // }
import io.jsonwebtoken.io.Decoders; import io.jsonwebtoken.io.Encoders;
/* * Copyright (C) 2014 jsonwebtoken.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 io.jsonwebtoken.impl; /** * @deprecated since 0.10.0 - will be removed before 1.0.0. Use {@link Encoders#BASE64URL Encoder.BASE64URL} * or {@link Decoders#BASE64URL Decoder.BASE64URL} instead. */ @Deprecated public class Base64UrlCodec extends AbstractTextCodec { @Override public String encode(byte[] data) {
// Path: api/src/main/java/io/jsonwebtoken/io/Decoders.java // public final class Decoders { // // public static final Decoder<String, byte[]> BASE64 = new ExceptionPropagatingDecoder<>(new Base64Decoder()); // public static final Decoder<String, byte[]> BASE64URL = new ExceptionPropagatingDecoder<>(new Base64UrlDecoder()); // // private Decoders() { //prevent instantiation // } // } // // Path: api/src/main/java/io/jsonwebtoken/io/Encoders.java // public final class Encoders { // // public static final Encoder<byte[], String> BASE64 = new ExceptionPropagatingEncoder<>(new Base64Encoder()); // public static final Encoder<byte[], String> BASE64URL = new ExceptionPropagatingEncoder<>(new Base64UrlEncoder()); // // private Encoders() { //prevent instantiation // } // } // Path: impl/src/main/java/io/jsonwebtoken/impl/Base64UrlCodec.java import io.jsonwebtoken.io.Decoders; import io.jsonwebtoken.io.Encoders; /* * Copyright (C) 2014 jsonwebtoken.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 io.jsonwebtoken.impl; /** * @deprecated since 0.10.0 - will be removed before 1.0.0. Use {@link Encoders#BASE64URL Encoder.BASE64URL} * or {@link Decoders#BASE64URL Decoder.BASE64URL} instead. */ @Deprecated public class Base64UrlCodec extends AbstractTextCodec { @Override public String encode(byte[] data) {
return Encoders.BASE64URL.encode(data);
jwtk/jjwt
impl/src/main/java/io/jsonwebtoken/impl/Base64UrlCodec.java
// Path: api/src/main/java/io/jsonwebtoken/io/Decoders.java // public final class Decoders { // // public static final Decoder<String, byte[]> BASE64 = new ExceptionPropagatingDecoder<>(new Base64Decoder()); // public static final Decoder<String, byte[]> BASE64URL = new ExceptionPropagatingDecoder<>(new Base64UrlDecoder()); // // private Decoders() { //prevent instantiation // } // } // // Path: api/src/main/java/io/jsonwebtoken/io/Encoders.java // public final class Encoders { // // public static final Encoder<byte[], String> BASE64 = new ExceptionPropagatingEncoder<>(new Base64Encoder()); // public static final Encoder<byte[], String> BASE64URL = new ExceptionPropagatingEncoder<>(new Base64UrlEncoder()); // // private Encoders() { //prevent instantiation // } // }
import io.jsonwebtoken.io.Decoders; import io.jsonwebtoken.io.Encoders;
/* * Copyright (C) 2014 jsonwebtoken.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 io.jsonwebtoken.impl; /** * @deprecated since 0.10.0 - will be removed before 1.0.0. Use {@link Encoders#BASE64URL Encoder.BASE64URL} * or {@link Decoders#BASE64URL Decoder.BASE64URL} instead. */ @Deprecated public class Base64UrlCodec extends AbstractTextCodec { @Override public String encode(byte[] data) { return Encoders.BASE64URL.encode(data); } @Override public byte[] decode(String encoded) {
// Path: api/src/main/java/io/jsonwebtoken/io/Decoders.java // public final class Decoders { // // public static final Decoder<String, byte[]> BASE64 = new ExceptionPropagatingDecoder<>(new Base64Decoder()); // public static final Decoder<String, byte[]> BASE64URL = new ExceptionPropagatingDecoder<>(new Base64UrlDecoder()); // // private Decoders() { //prevent instantiation // } // } // // Path: api/src/main/java/io/jsonwebtoken/io/Encoders.java // public final class Encoders { // // public static final Encoder<byte[], String> BASE64 = new ExceptionPropagatingEncoder<>(new Base64Encoder()); // public static final Encoder<byte[], String> BASE64URL = new ExceptionPropagatingEncoder<>(new Base64UrlEncoder()); // // private Encoders() { //prevent instantiation // } // } // Path: impl/src/main/java/io/jsonwebtoken/impl/Base64UrlCodec.java import io.jsonwebtoken.io.Decoders; import io.jsonwebtoken.io.Encoders; /* * Copyright (C) 2014 jsonwebtoken.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 io.jsonwebtoken.impl; /** * @deprecated since 0.10.0 - will be removed before 1.0.0. Use {@link Encoders#BASE64URL Encoder.BASE64URL} * or {@link Decoders#BASE64URL Decoder.BASE64URL} instead. */ @Deprecated public class Base64UrlCodec extends AbstractTextCodec { @Override public String encode(byte[] data) { return Encoders.BASE64URL.encode(data); } @Override public byte[] decode(String encoded) {
return Decoders.BASE64URL.decode(encoded);
jwtk/jjwt
impl/src/main/java/io/jsonwebtoken/impl/Base64Codec.java
// Path: api/src/main/java/io/jsonwebtoken/io/Decoders.java // public final class Decoders { // // public static final Decoder<String, byte[]> BASE64 = new ExceptionPropagatingDecoder<>(new Base64Decoder()); // public static final Decoder<String, byte[]> BASE64URL = new ExceptionPropagatingDecoder<>(new Base64UrlDecoder()); // // private Decoders() { //prevent instantiation // } // } // // Path: api/src/main/java/io/jsonwebtoken/io/Encoders.java // public final class Encoders { // // public static final Encoder<byte[], String> BASE64 = new ExceptionPropagatingEncoder<>(new Base64Encoder()); // public static final Encoder<byte[], String> BASE64URL = new ExceptionPropagatingEncoder<>(new Base64UrlEncoder()); // // private Encoders() { //prevent instantiation // } // }
import io.jsonwebtoken.io.Decoders; import io.jsonwebtoken.io.Encoders;
/* * Copyright (C) 2014 jsonwebtoken.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 io.jsonwebtoken.impl; /** * @deprecated since 0.10.0 - will be removed before 1.0.0. Use {@code io.jsonwebtoken.io.Encoders#BASE64} * or {@code io.jsonwebtoken.io.Decoders#BASE64} */ @Deprecated public class Base64Codec extends AbstractTextCodec { public String encode(byte[] data) {
// Path: api/src/main/java/io/jsonwebtoken/io/Decoders.java // public final class Decoders { // // public static final Decoder<String, byte[]> BASE64 = new ExceptionPropagatingDecoder<>(new Base64Decoder()); // public static final Decoder<String, byte[]> BASE64URL = new ExceptionPropagatingDecoder<>(new Base64UrlDecoder()); // // private Decoders() { //prevent instantiation // } // } // // Path: api/src/main/java/io/jsonwebtoken/io/Encoders.java // public final class Encoders { // // public static final Encoder<byte[], String> BASE64 = new ExceptionPropagatingEncoder<>(new Base64Encoder()); // public static final Encoder<byte[], String> BASE64URL = new ExceptionPropagatingEncoder<>(new Base64UrlEncoder()); // // private Encoders() { //prevent instantiation // } // } // Path: impl/src/main/java/io/jsonwebtoken/impl/Base64Codec.java import io.jsonwebtoken.io.Decoders; import io.jsonwebtoken.io.Encoders; /* * Copyright (C) 2014 jsonwebtoken.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 io.jsonwebtoken.impl; /** * @deprecated since 0.10.0 - will be removed before 1.0.0. Use {@code io.jsonwebtoken.io.Encoders#BASE64} * or {@code io.jsonwebtoken.io.Decoders#BASE64} */ @Deprecated public class Base64Codec extends AbstractTextCodec { public String encode(byte[] data) {
return Encoders.BASE64.encode(data);
jwtk/jjwt
impl/src/main/java/io/jsonwebtoken/impl/Base64Codec.java
// Path: api/src/main/java/io/jsonwebtoken/io/Decoders.java // public final class Decoders { // // public static final Decoder<String, byte[]> BASE64 = new ExceptionPropagatingDecoder<>(new Base64Decoder()); // public static final Decoder<String, byte[]> BASE64URL = new ExceptionPropagatingDecoder<>(new Base64UrlDecoder()); // // private Decoders() { //prevent instantiation // } // } // // Path: api/src/main/java/io/jsonwebtoken/io/Encoders.java // public final class Encoders { // // public static final Encoder<byte[], String> BASE64 = new ExceptionPropagatingEncoder<>(new Base64Encoder()); // public static final Encoder<byte[], String> BASE64URL = new ExceptionPropagatingEncoder<>(new Base64UrlEncoder()); // // private Encoders() { //prevent instantiation // } // }
import io.jsonwebtoken.io.Decoders; import io.jsonwebtoken.io.Encoders;
/* * Copyright (C) 2014 jsonwebtoken.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 io.jsonwebtoken.impl; /** * @deprecated since 0.10.0 - will be removed before 1.0.0. Use {@code io.jsonwebtoken.io.Encoders#BASE64} * or {@code io.jsonwebtoken.io.Decoders#BASE64} */ @Deprecated public class Base64Codec extends AbstractTextCodec { public String encode(byte[] data) { return Encoders.BASE64.encode(data); } @Override public byte[] decode(String encoded) {
// Path: api/src/main/java/io/jsonwebtoken/io/Decoders.java // public final class Decoders { // // public static final Decoder<String, byte[]> BASE64 = new ExceptionPropagatingDecoder<>(new Base64Decoder()); // public static final Decoder<String, byte[]> BASE64URL = new ExceptionPropagatingDecoder<>(new Base64UrlDecoder()); // // private Decoders() { //prevent instantiation // } // } // // Path: api/src/main/java/io/jsonwebtoken/io/Encoders.java // public final class Encoders { // // public static final Encoder<byte[], String> BASE64 = new ExceptionPropagatingEncoder<>(new Base64Encoder()); // public static final Encoder<byte[], String> BASE64URL = new ExceptionPropagatingEncoder<>(new Base64UrlEncoder()); // // private Encoders() { //prevent instantiation // } // } // Path: impl/src/main/java/io/jsonwebtoken/impl/Base64Codec.java import io.jsonwebtoken.io.Decoders; import io.jsonwebtoken.io.Encoders; /* * Copyright (C) 2014 jsonwebtoken.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 io.jsonwebtoken.impl; /** * @deprecated since 0.10.0 - will be removed before 1.0.0. Use {@code io.jsonwebtoken.io.Encoders#BASE64} * or {@code io.jsonwebtoken.io.Decoders#BASE64} */ @Deprecated public class Base64Codec extends AbstractTextCodec { public String encode(byte[] data) { return Encoders.BASE64.encode(data); } @Override public byte[] decode(String encoded) {
return Decoders.BASE64.decode(encoded);
DaanVanYperen/odb-little-fortune-planet
components/src/net/mostlyoriginal/game/component/Planet.java
// Path: components/src/net/mostlyoriginal/game/component/G.java // public static final int GRADIENT_SCALE = 5; // // Path: components/src/net/mostlyoriginal/game/component/G.java // public static final int SIMULATION_HEIGHT = 220 + 50; // // Path: components/src/net/mostlyoriginal/game/component/G.java // public static final int SIMULATION_WIDTH = 220 + 50;
import com.artemis.Component; import static net.mostlyoriginal.game.component.G.GRADIENT_SCALE; import static net.mostlyoriginal.game.component.G.SIMULATION_HEIGHT; import static net.mostlyoriginal.game.component.G.SIMULATION_WIDTH;
package net.mostlyoriginal.game.component; /** * @author Daan van Yperen */ public class Planet extends Component { public Planet() { }
// Path: components/src/net/mostlyoriginal/game/component/G.java // public static final int GRADIENT_SCALE = 5; // // Path: components/src/net/mostlyoriginal/game/component/G.java // public static final int SIMULATION_HEIGHT = 220 + 50; // // Path: components/src/net/mostlyoriginal/game/component/G.java // public static final int SIMULATION_WIDTH = 220 + 50; // Path: components/src/net/mostlyoriginal/game/component/Planet.java import com.artemis.Component; import static net.mostlyoriginal.game.component.G.GRADIENT_SCALE; import static net.mostlyoriginal.game.component.G.SIMULATION_HEIGHT; import static net.mostlyoriginal.game.component.G.SIMULATION_WIDTH; package net.mostlyoriginal.game.component; /** * @author Daan van Yperen */ public class Planet extends Component { public Planet() { }
public PlanetCell[][] grid = new PlanetCell[SIMULATION_HEIGHT][SIMULATION_WIDTH];
DaanVanYperen/odb-little-fortune-planet
components/src/net/mostlyoriginal/game/component/Planet.java
// Path: components/src/net/mostlyoriginal/game/component/G.java // public static final int GRADIENT_SCALE = 5; // // Path: components/src/net/mostlyoriginal/game/component/G.java // public static final int SIMULATION_HEIGHT = 220 + 50; // // Path: components/src/net/mostlyoriginal/game/component/G.java // public static final int SIMULATION_WIDTH = 220 + 50;
import com.artemis.Component; import static net.mostlyoriginal.game.component.G.GRADIENT_SCALE; import static net.mostlyoriginal.game.component.G.SIMULATION_HEIGHT; import static net.mostlyoriginal.game.component.G.SIMULATION_WIDTH;
package net.mostlyoriginal.game.component; /** * @author Daan van Yperen */ public class Planet extends Component { public Planet() { }
// Path: components/src/net/mostlyoriginal/game/component/G.java // public static final int GRADIENT_SCALE = 5; // // Path: components/src/net/mostlyoriginal/game/component/G.java // public static final int SIMULATION_HEIGHT = 220 + 50; // // Path: components/src/net/mostlyoriginal/game/component/G.java // public static final int SIMULATION_WIDTH = 220 + 50; // Path: components/src/net/mostlyoriginal/game/component/Planet.java import com.artemis.Component; import static net.mostlyoriginal.game.component.G.GRADIENT_SCALE; import static net.mostlyoriginal.game.component.G.SIMULATION_HEIGHT; import static net.mostlyoriginal.game.component.G.SIMULATION_WIDTH; package net.mostlyoriginal.game.component; /** * @author Daan van Yperen */ public class Planet extends Component { public Planet() { }
public PlanetCell[][] grid = new PlanetCell[SIMULATION_HEIGHT][SIMULATION_WIDTH];
DaanVanYperen/odb-little-fortune-planet
components/src/net/mostlyoriginal/game/component/Planet.java
// Path: components/src/net/mostlyoriginal/game/component/G.java // public static final int GRADIENT_SCALE = 5; // // Path: components/src/net/mostlyoriginal/game/component/G.java // public static final int SIMULATION_HEIGHT = 220 + 50; // // Path: components/src/net/mostlyoriginal/game/component/G.java // public static final int SIMULATION_WIDTH = 220 + 50;
import com.artemis.Component; import static net.mostlyoriginal.game.component.G.GRADIENT_SCALE; import static net.mostlyoriginal.game.component.G.SIMULATION_HEIGHT; import static net.mostlyoriginal.game.component.G.SIMULATION_WIDTH;
package net.mostlyoriginal.game.component; /** * @author Daan van Yperen */ public class Planet extends Component { public Planet() { } public PlanetCell[][] grid = new PlanetCell[SIMULATION_HEIGHT][SIMULATION_WIDTH]; public int[][] dirtColor = new int[SIMULATION_HEIGHT][SIMULATION_WIDTH];
// Path: components/src/net/mostlyoriginal/game/component/G.java // public static final int GRADIENT_SCALE = 5; // // Path: components/src/net/mostlyoriginal/game/component/G.java // public static final int SIMULATION_HEIGHT = 220 + 50; // // Path: components/src/net/mostlyoriginal/game/component/G.java // public static final int SIMULATION_WIDTH = 220 + 50; // Path: components/src/net/mostlyoriginal/game/component/Planet.java import com.artemis.Component; import static net.mostlyoriginal.game.component.G.GRADIENT_SCALE; import static net.mostlyoriginal.game.component.G.SIMULATION_HEIGHT; import static net.mostlyoriginal.game.component.G.SIMULATION_WIDTH; package net.mostlyoriginal.game.component; /** * @author Daan van Yperen */ public class Planet extends Component { public Planet() { } public PlanetCell[][] grid = new PlanetCell[SIMULATION_HEIGHT][SIMULATION_WIDTH]; public int[][] dirtColor = new int[SIMULATION_HEIGHT][SIMULATION_WIDTH];
public StatusMask[][] mask = new StatusMask[SIMULATION_HEIGHT/ GRADIENT_SCALE][SIMULATION_WIDTH / GRADIENT_SCALE];
DaanVanYperen/odb-little-fortune-planet
core/src/net/mostlyoriginal/game/system/planet/cells/OrganicCellSimulator.java
// Path: components/src/net/mostlyoriginal/game/component/PlanetCell.java // public class PlanetCell { // public static final int SPACE_AIR_STARTS_AT_DEPTH = 20; // public int x; // public int y; // public int color = 0; // public int down = -1; // public float height = 0; // public CellType type = CellType.STATIC; // // // public CellType nextType = null; // public int nextColor = -1; // // public static int[][] directions = { // {-1, -1}, // {0, -1}, // {1, -1}, // {1, 0}, // {1, 1}, // {0, 1}, // {-1, 1}, // {-1, 0} // }; // // public int sleep; // // public int up() { // return (down + 4) % 8; // } // // public int left() { // return (down + 6) % 8; // } // // public int right() { // return (down + 2) % 8; // } // // public int upL() { // return (down + 3) % 8; // } // // public int downL() { // return (down + 7) % 8; // } // // public int downR() { // return (down + 1) % 8; // } // // public int upR() { // return (down + 5) % 8; // } // // public void activateNextType() { // if (nextType != null) { // type = nextType; // nextType = null; // sleep=0; // } // if (nextColor != -1) { // color = nextColor; // nextColor = -1; // } // } // // public float depth() { // return ((G.SIMULATION_WIDTH / 2) - height); // } // // public enum CellType { // STATIC(null, false), // LAVA(5f, true), // WATER(1f, true), // AIR(0f, true), // ICE(null, false), // STEAM(-0.5f, true), // LAVA_CRUST(5f, true), // CLOUD(-0.7f, false), // FIRE(-0.7f, false), // NOTHING(-100f,false), // ORGANIC(null, false), ORGANIC_SPORE(-0.7f, false); // // public final Float density; // private boolean flows; // // CellType(Float density, boolean flows) { // this.density = density; // this.flows = flows; // } // // public boolean flows() { // return flows; // } // // public boolean isLighter(CellType type) { // return type.density != null && density != null && type.density < density; // } // } // // public boolean isSpaceAir() { // return depth() < SPACE_AIR_STARTS_AT_DEPTH && type == PlanetCell.CellType.AIR; // } // } // // Path: components/src/net/mostlyoriginal/game/component/StatusMask.java // public class StatusMask { // public static final float ARID_TEMPERATURE = 300; // public static float MAX_TEMPERATURE = 300; // public float temperature=0; // // public void reset() { // temperature=0; // } // }
import net.mostlyoriginal.game.component.PlanetCell; import net.mostlyoriginal.game.component.StatusMask;
package net.mostlyoriginal.game.system.planet.cells; /** * @author Daan van Yperen */ public class OrganicCellSimulator implements CellSimulator { @Override public void color(CellDecorator c, float delta) { c.cell.color = c.planet.cellColor[c.cell.type.ordinal()]; } @Override public void process(CellDecorator c, float delta) { // spread.
// Path: components/src/net/mostlyoriginal/game/component/PlanetCell.java // public class PlanetCell { // public static final int SPACE_AIR_STARTS_AT_DEPTH = 20; // public int x; // public int y; // public int color = 0; // public int down = -1; // public float height = 0; // public CellType type = CellType.STATIC; // // // public CellType nextType = null; // public int nextColor = -1; // // public static int[][] directions = { // {-1, -1}, // {0, -1}, // {1, -1}, // {1, 0}, // {1, 1}, // {0, 1}, // {-1, 1}, // {-1, 0} // }; // // public int sleep; // // public int up() { // return (down + 4) % 8; // } // // public int left() { // return (down + 6) % 8; // } // // public int right() { // return (down + 2) % 8; // } // // public int upL() { // return (down + 3) % 8; // } // // public int downL() { // return (down + 7) % 8; // } // // public int downR() { // return (down + 1) % 8; // } // // public int upR() { // return (down + 5) % 8; // } // // public void activateNextType() { // if (nextType != null) { // type = nextType; // nextType = null; // sleep=0; // } // if (nextColor != -1) { // color = nextColor; // nextColor = -1; // } // } // // public float depth() { // return ((G.SIMULATION_WIDTH / 2) - height); // } // // public enum CellType { // STATIC(null, false), // LAVA(5f, true), // WATER(1f, true), // AIR(0f, true), // ICE(null, false), // STEAM(-0.5f, true), // LAVA_CRUST(5f, true), // CLOUD(-0.7f, false), // FIRE(-0.7f, false), // NOTHING(-100f,false), // ORGANIC(null, false), ORGANIC_SPORE(-0.7f, false); // // public final Float density; // private boolean flows; // // CellType(Float density, boolean flows) { // this.density = density; // this.flows = flows; // } // // public boolean flows() { // return flows; // } // // public boolean isLighter(CellType type) { // return type.density != null && density != null && type.density < density; // } // } // // public boolean isSpaceAir() { // return depth() < SPACE_AIR_STARTS_AT_DEPTH && type == PlanetCell.CellType.AIR; // } // } // // Path: components/src/net/mostlyoriginal/game/component/StatusMask.java // public class StatusMask { // public static final float ARID_TEMPERATURE = 300; // public static float MAX_TEMPERATURE = 300; // public float temperature=0; // // public void reset() { // temperature=0; // } // } // Path: core/src/net/mostlyoriginal/game/system/planet/cells/OrganicCellSimulator.java import net.mostlyoriginal.game.component.PlanetCell; import net.mostlyoriginal.game.component.StatusMask; package net.mostlyoriginal.game.system.planet.cells; /** * @author Daan van Yperen */ public class OrganicCellSimulator implements CellSimulator { @Override public void color(CellDecorator c, float delta) { c.cell.color = c.planet.cellColor[c.cell.type.ordinal()]; } @Override public void process(CellDecorator c, float delta) { // spread.
PlanetCell target = c.getRandomNeighbour(PlanetCell.CellType.AIR, 3);
DaanVanYperen/odb-little-fortune-planet
core/src/net/mostlyoriginal/game/system/common/FluidIteratingSystem.java
// Path: core/src/net/mostlyoriginal/game/api/EBag.java // public class EBag implements ImmutableBag<E> { // // private final int[] entities; // private final int size; // // public EBag(int[] entities, int size) { // this.entities = entities; // this.size = size; // } // // public EBag(IntBag bag) { // this(bag.getData(), bag.size()); // } // // @Override // public java.util.Iterator<E> iterator() { // return new EBagIterator(entities, size); // } // // @Override // public E get(int index) { // return E.E(entities[index]); // } // // @Override // public int size() { // return size; // } // // @Override // public boolean isEmpty() { // return size == 0; // } // // @Override // public boolean contains(E value) { // for (int i = 0; this.size > i; ++i) { // if (value == E.E(entities[i])) { // return true; // } // } // return false; // } // // public static class EBagIterator implements Iterator<E> { // private final int[] entities; // private final int size; // private int cursor; // // private EBagIterator(int[] entities, int size) { // this.entities = entities; // this.size = size; // } // // @Override // public boolean hasNext() { // return this.cursor < size; // } // // @Override // public E next() { // if (this.cursor == size) { // throw new NoSuchElementException("Iterated past last element"); // } else { // return E.E(entities[this.cursor++]); // } // } // // @Override // public void remove() { // throw new UnsupportedOperationException(); // } // } // }
import com.artemis.Aspect; import com.artemis.Component; import com.artemis.E; import com.artemis.systems.IteratingSystem; import net.mostlyoriginal.game.api.EBag; import java.util.Iterator; import static com.artemis.E.E;
package net.mostlyoriginal.game.system.common; /** * @author Daan van Yperen */ public abstract class FluidIteratingSystem extends IteratingSystem { public FluidIteratingSystem(Aspect.Builder aspect) { super(aspect); } @Override protected void process(int id) { process(E(id)); } protected abstract void process(E e);
// Path: core/src/net/mostlyoriginal/game/api/EBag.java // public class EBag implements ImmutableBag<E> { // // private final int[] entities; // private final int size; // // public EBag(int[] entities, int size) { // this.entities = entities; // this.size = size; // } // // public EBag(IntBag bag) { // this(bag.getData(), bag.size()); // } // // @Override // public java.util.Iterator<E> iterator() { // return new EBagIterator(entities, size); // } // // @Override // public E get(int index) { // return E.E(entities[index]); // } // // @Override // public int size() { // return size; // } // // @Override // public boolean isEmpty() { // return size == 0; // } // // @Override // public boolean contains(E value) { // for (int i = 0; this.size > i; ++i) { // if (value == E.E(entities[i])) { // return true; // } // } // return false; // } // // public static class EBagIterator implements Iterator<E> { // private final int[] entities; // private final int size; // private int cursor; // // private EBagIterator(int[] entities, int size) { // this.entities = entities; // this.size = size; // } // // @Override // public boolean hasNext() { // return this.cursor < size; // } // // @Override // public E next() { // if (this.cursor == size) { // throw new NoSuchElementException("Iterated past last element"); // } else { // return E.E(entities[this.cursor++]); // } // } // // @Override // public void remove() { // throw new UnsupportedOperationException(); // } // } // } // Path: core/src/net/mostlyoriginal/game/system/common/FluidIteratingSystem.java import com.artemis.Aspect; import com.artemis.Component; import com.artemis.E; import com.artemis.systems.IteratingSystem; import net.mostlyoriginal.game.api.EBag; import java.util.Iterator; import static com.artemis.E.E; package net.mostlyoriginal.game.system.common; /** * @author Daan van Yperen */ public abstract class FluidIteratingSystem extends IteratingSystem { public FluidIteratingSystem(Aspect.Builder aspect) { super(aspect); } @Override protected void process(int id) { process(E(id)); } protected abstract void process(E e);
protected EBag allEntitiesMatching(Aspect.Builder scope) {
DaanVanYperen/odb-little-fortune-planet
core/src/net/mostlyoriginal/game/system/planet/cells/SteamCellSimulator.java
// Path: components/src/net/mostlyoriginal/game/component/PlanetCell.java // public class PlanetCell { // public static final int SPACE_AIR_STARTS_AT_DEPTH = 20; // public int x; // public int y; // public int color = 0; // public int down = -1; // public float height = 0; // public CellType type = CellType.STATIC; // // // public CellType nextType = null; // public int nextColor = -1; // // public static int[][] directions = { // {-1, -1}, // {0, -1}, // {1, -1}, // {1, 0}, // {1, 1}, // {0, 1}, // {-1, 1}, // {-1, 0} // }; // // public int sleep; // // public int up() { // return (down + 4) % 8; // } // // public int left() { // return (down + 6) % 8; // } // // public int right() { // return (down + 2) % 8; // } // // public int upL() { // return (down + 3) % 8; // } // // public int downL() { // return (down + 7) % 8; // } // // public int downR() { // return (down + 1) % 8; // } // // public int upR() { // return (down + 5) % 8; // } // // public void activateNextType() { // if (nextType != null) { // type = nextType; // nextType = null; // sleep=0; // } // if (nextColor != -1) { // color = nextColor; // nextColor = -1; // } // } // // public float depth() { // return ((G.SIMULATION_WIDTH / 2) - height); // } // // public enum CellType { // STATIC(null, false), // LAVA(5f, true), // WATER(1f, true), // AIR(0f, true), // ICE(null, false), // STEAM(-0.5f, true), // LAVA_CRUST(5f, true), // CLOUD(-0.7f, false), // FIRE(-0.7f, false), // NOTHING(-100f,false), // ORGANIC(null, false), ORGANIC_SPORE(-0.7f, false); // // public final Float density; // private boolean flows; // // CellType(Float density, boolean flows) { // this.density = density; // this.flows = flows; // } // // public boolean flows() { // return flows; // } // // public boolean isLighter(CellType type) { // return type.density != null && density != null && type.density < density; // } // } // // public boolean isSpaceAir() { // return depth() < SPACE_AIR_STARTS_AT_DEPTH && type == PlanetCell.CellType.AIR; // } // }
import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.math.MathUtils; import net.mostlyoriginal.game.component.PlanetCell;
package net.mostlyoriginal.game.system.planet.cells; /** * @author Daan van Yperen */ public class SteamCellSimulator implements CellSimulator { @Override public void color(CellDecorator c, float delta) {
// Path: components/src/net/mostlyoriginal/game/component/PlanetCell.java // public class PlanetCell { // public static final int SPACE_AIR_STARTS_AT_DEPTH = 20; // public int x; // public int y; // public int color = 0; // public int down = -1; // public float height = 0; // public CellType type = CellType.STATIC; // // // public CellType nextType = null; // public int nextColor = -1; // // public static int[][] directions = { // {-1, -1}, // {0, -1}, // {1, -1}, // {1, 0}, // {1, 1}, // {0, 1}, // {-1, 1}, // {-1, 0} // }; // // public int sleep; // // public int up() { // return (down + 4) % 8; // } // // public int left() { // return (down + 6) % 8; // } // // public int right() { // return (down + 2) % 8; // } // // public int upL() { // return (down + 3) % 8; // } // // public int downL() { // return (down + 7) % 8; // } // // public int downR() { // return (down + 1) % 8; // } // // public int upR() { // return (down + 5) % 8; // } // // public void activateNextType() { // if (nextType != null) { // type = nextType; // nextType = null; // sleep=0; // } // if (nextColor != -1) { // color = nextColor; // nextColor = -1; // } // } // // public float depth() { // return ((G.SIMULATION_WIDTH / 2) - height); // } // // public enum CellType { // STATIC(null, false), // LAVA(5f, true), // WATER(1f, true), // AIR(0f, true), // ICE(null, false), // STEAM(-0.5f, true), // LAVA_CRUST(5f, true), // CLOUD(-0.7f, false), // FIRE(-0.7f, false), // NOTHING(-100f,false), // ORGANIC(null, false), ORGANIC_SPORE(-0.7f, false); // // public final Float density; // private boolean flows; // // CellType(Float density, boolean flows) { // this.density = density; // this.flows = flows; // } // // public boolean flows() { // return flows; // } // // public boolean isLighter(CellType type) { // return type.density != null && density != null && type.density < density; // } // } // // public boolean isSpaceAir() { // return depth() < SPACE_AIR_STARTS_AT_DEPTH && type == PlanetCell.CellType.AIR; // } // } // Path: core/src/net/mostlyoriginal/game/system/planet/cells/SteamCellSimulator.java import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.math.MathUtils; import net.mostlyoriginal.game.component.PlanetCell; package net.mostlyoriginal.game.system.planet.cells; /** * @author Daan van Yperen */ public class SteamCellSimulator implements CellSimulator { @Override public void color(CellDecorator c, float delta) {
c.cell.color = c.planet.cellColor[PlanetCell.CellType.STEAM.ordinal()];
DaanVanYperen/odb-little-fortune-planet
core/src/net/mostlyoriginal/game/system/planet/cells/CloudCellSimulator.java
// Path: components/src/net/mostlyoriginal/game/component/PlanetCell.java // public class PlanetCell { // public static final int SPACE_AIR_STARTS_AT_DEPTH = 20; // public int x; // public int y; // public int color = 0; // public int down = -1; // public float height = 0; // public CellType type = CellType.STATIC; // // // public CellType nextType = null; // public int nextColor = -1; // // public static int[][] directions = { // {-1, -1}, // {0, -1}, // {1, -1}, // {1, 0}, // {1, 1}, // {0, 1}, // {-1, 1}, // {-1, 0} // }; // // public int sleep; // // public int up() { // return (down + 4) % 8; // } // // public int left() { // return (down + 6) % 8; // } // // public int right() { // return (down + 2) % 8; // } // // public int upL() { // return (down + 3) % 8; // } // // public int downL() { // return (down + 7) % 8; // } // // public int downR() { // return (down + 1) % 8; // } // // public int upR() { // return (down + 5) % 8; // } // // public void activateNextType() { // if (nextType != null) { // type = nextType; // nextType = null; // sleep=0; // } // if (nextColor != -1) { // color = nextColor; // nextColor = -1; // } // } // // public float depth() { // return ((G.SIMULATION_WIDTH / 2) - height); // } // // public enum CellType { // STATIC(null, false), // LAVA(5f, true), // WATER(1f, true), // AIR(0f, true), // ICE(null, false), // STEAM(-0.5f, true), // LAVA_CRUST(5f, true), // CLOUD(-0.7f, false), // FIRE(-0.7f, false), // NOTHING(-100f,false), // ORGANIC(null, false), ORGANIC_SPORE(-0.7f, false); // // public final Float density; // private boolean flows; // // CellType(Float density, boolean flows) { // this.density = density; // this.flows = flows; // } // // public boolean flows() { // return flows; // } // // public boolean isLighter(CellType type) { // return type.density != null && density != null && type.density < density; // } // } // // public boolean isSpaceAir() { // return depth() < SPACE_AIR_STARTS_AT_DEPTH && type == PlanetCell.CellType.AIR; // } // }
import com.badlogic.gdx.math.MathUtils; import net.mostlyoriginal.game.component.PlanetCell;
package net.mostlyoriginal.game.system.planet.cells; /** * @author Daan van Yperen */ public class CloudCellSimulator implements CellSimulator { @Override public void color(CellDecorator c, float delta) {
// Path: components/src/net/mostlyoriginal/game/component/PlanetCell.java // public class PlanetCell { // public static final int SPACE_AIR_STARTS_AT_DEPTH = 20; // public int x; // public int y; // public int color = 0; // public int down = -1; // public float height = 0; // public CellType type = CellType.STATIC; // // // public CellType nextType = null; // public int nextColor = -1; // // public static int[][] directions = { // {-1, -1}, // {0, -1}, // {1, -1}, // {1, 0}, // {1, 1}, // {0, 1}, // {-1, 1}, // {-1, 0} // }; // // public int sleep; // // public int up() { // return (down + 4) % 8; // } // // public int left() { // return (down + 6) % 8; // } // // public int right() { // return (down + 2) % 8; // } // // public int upL() { // return (down + 3) % 8; // } // // public int downL() { // return (down + 7) % 8; // } // // public int downR() { // return (down + 1) % 8; // } // // public int upR() { // return (down + 5) % 8; // } // // public void activateNextType() { // if (nextType != null) { // type = nextType; // nextType = null; // sleep=0; // } // if (nextColor != -1) { // color = nextColor; // nextColor = -1; // } // } // // public float depth() { // return ((G.SIMULATION_WIDTH / 2) - height); // } // // public enum CellType { // STATIC(null, false), // LAVA(5f, true), // WATER(1f, true), // AIR(0f, true), // ICE(null, false), // STEAM(-0.5f, true), // LAVA_CRUST(5f, true), // CLOUD(-0.7f, false), // FIRE(-0.7f, false), // NOTHING(-100f,false), // ORGANIC(null, false), ORGANIC_SPORE(-0.7f, false); // // public final Float density; // private boolean flows; // // CellType(Float density, boolean flows) { // this.density = density; // this.flows = flows; // } // // public boolean flows() { // return flows; // } // // public boolean isLighter(CellType type) { // return type.density != null && density != null && type.density < density; // } // } // // public boolean isSpaceAir() { // return depth() < SPACE_AIR_STARTS_AT_DEPTH && type == PlanetCell.CellType.AIR; // } // } // Path: core/src/net/mostlyoriginal/game/system/planet/cells/CloudCellSimulator.java import com.badlogic.gdx.math.MathUtils; import net.mostlyoriginal.game.component.PlanetCell; package net.mostlyoriginal.game.system.planet.cells; /** * @author Daan van Yperen */ public class CloudCellSimulator implements CellSimulator { @Override public void color(CellDecorator c, float delta) {
c.cell.color = c.planet.cellColor[PlanetCell.CellType.CLOUD.ordinal()];
DaanVanYperen/odb-little-fortune-planet
core/src/net/mostlyoriginal/game/GdxArtemisGame.java
// Path: core/src/net/mostlyoriginal/game/screen/GameScreen.java // public class GameScreen extends WorldScreen { // // public static final String BACKGROUND_COLOR_HEX = "0000FF"; // // @Override // protected World createWorld() { // RenderBatchingSystem renderBatchingSystem; // return new World(new WorldConfigurationBuilder() // .dependsOn(EntityLinkManager.class, ProfilerPlugin.class, OperationsPlugin.class) // .with( // new SuperMapper(), // new TagManager(), // // new GroupManager(), // new CardSystem(), // new CardSortSystem(), // new CardScriptSystem(), // new CollisionSystem(), // new TransitionSystem(GdxArtemisGame.getInstance()), // // new MyCameraSystem(G.CAMERA_ZOOM), // new GameScreenAssetSystem(), // new GameScreenSetupSystem(), // // new MouseCursorSystem(), // new MouseClickSystem(), // new PlanetCreationSystem(), // // new DrawingSystem(), // // new PlanetStencilSystem(), // new PlanetMaskSystem(), // new PlanetSimulationSystem(), // // // new PlanetCoordSystem(), // new OrientToGravitySystem(), // new WanderSystem(), // new GravitySystem(), // new PhysicsSystem(), // // new DeathSystem(), // new GhostSystem(), // new ExplosiveSystem(), // // new StarEffectSystem(), // // new ToolSystem(), // new AchievementSystem(), // // new PlanetBackgroundRenderSystem(), // // renderBatchingSystem = new RenderBatchingSystem(), // new MyAnimRenderSystem(renderBatchingSystem), // new PlanetRenderSystem(renderBatchingSystem), // new PlanetRenderGravityDebugSystem(), // new PlanetRenderTemperatureDebugSystem() // ).build()); // } // // } // // Path: core/src/net/mostlyoriginal/game/screen/detection/OdbFeatureScreen.java // public class OdbFeatureScreen extends WorldScreen { // // protected World createWorld() { // // final RenderBatchingSystem renderBatchingSystem; // // return new World(new WorldConfigurationBuilder() // .dependsOn(OperationsPlugin.class) // .with(WorldConfigurationBuilder.Priority.HIGH, // // supportive // new SuperMapper(), // new TagManager(), // new CameraSystem(1), // new FeatureScreenAssetSystem(), // new OdbFeatureDetectionSystem() // ).with(WorldConfigurationBuilder.Priority.LOW, // // processing // new TransitionSystem(GdxArtemisGame.getInstance()), // // animation // new ClearScreenSystem(Color.valueOf("969291")), // renderBatchingSystem = new RenderBatchingSystem(), // new AnimRenderSystem(renderBatchingSystem), // new FeatureScreenSetupSystem() // ).build()); // } // // }
import com.badlogic.gdx.Game; import net.mostlyoriginal.game.screen.GameScreen; import net.mostlyoriginal.game.screen.detection.OdbFeatureScreen;
package net.mostlyoriginal.game; public class GdxArtemisGame extends Game { private static GdxArtemisGame instance; @Override public void create() { instance = this; restart(); } public void restart() {
// Path: core/src/net/mostlyoriginal/game/screen/GameScreen.java // public class GameScreen extends WorldScreen { // // public static final String BACKGROUND_COLOR_HEX = "0000FF"; // // @Override // protected World createWorld() { // RenderBatchingSystem renderBatchingSystem; // return new World(new WorldConfigurationBuilder() // .dependsOn(EntityLinkManager.class, ProfilerPlugin.class, OperationsPlugin.class) // .with( // new SuperMapper(), // new TagManager(), // // new GroupManager(), // new CardSystem(), // new CardSortSystem(), // new CardScriptSystem(), // new CollisionSystem(), // new TransitionSystem(GdxArtemisGame.getInstance()), // // new MyCameraSystem(G.CAMERA_ZOOM), // new GameScreenAssetSystem(), // new GameScreenSetupSystem(), // // new MouseCursorSystem(), // new MouseClickSystem(), // new PlanetCreationSystem(), // // new DrawingSystem(), // // new PlanetStencilSystem(), // new PlanetMaskSystem(), // new PlanetSimulationSystem(), // // // new PlanetCoordSystem(), // new OrientToGravitySystem(), // new WanderSystem(), // new GravitySystem(), // new PhysicsSystem(), // // new DeathSystem(), // new GhostSystem(), // new ExplosiveSystem(), // // new StarEffectSystem(), // // new ToolSystem(), // new AchievementSystem(), // // new PlanetBackgroundRenderSystem(), // // renderBatchingSystem = new RenderBatchingSystem(), // new MyAnimRenderSystem(renderBatchingSystem), // new PlanetRenderSystem(renderBatchingSystem), // new PlanetRenderGravityDebugSystem(), // new PlanetRenderTemperatureDebugSystem() // ).build()); // } // // } // // Path: core/src/net/mostlyoriginal/game/screen/detection/OdbFeatureScreen.java // public class OdbFeatureScreen extends WorldScreen { // // protected World createWorld() { // // final RenderBatchingSystem renderBatchingSystem; // // return new World(new WorldConfigurationBuilder() // .dependsOn(OperationsPlugin.class) // .with(WorldConfigurationBuilder.Priority.HIGH, // // supportive // new SuperMapper(), // new TagManager(), // new CameraSystem(1), // new FeatureScreenAssetSystem(), // new OdbFeatureDetectionSystem() // ).with(WorldConfigurationBuilder.Priority.LOW, // // processing // new TransitionSystem(GdxArtemisGame.getInstance()), // // animation // new ClearScreenSystem(Color.valueOf("969291")), // renderBatchingSystem = new RenderBatchingSystem(), // new AnimRenderSystem(renderBatchingSystem), // new FeatureScreenSetupSystem() // ).build()); // } // // } // Path: core/src/net/mostlyoriginal/game/GdxArtemisGame.java import com.badlogic.gdx.Game; import net.mostlyoriginal.game.screen.GameScreen; import net.mostlyoriginal.game.screen.detection.OdbFeatureScreen; package net.mostlyoriginal.game; public class GdxArtemisGame extends Game { private static GdxArtemisGame instance; @Override public void create() { instance = this; restart(); } public void restart() {
setScreen(new GameScreen());