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
dirk/hummingbird2
src/main/java/org/hummingbirdlang/objects/Function.java
// Path: src/main/java/org/hummingbirdlang/runtime/bindings/Bindings.java // public final class Bindings { // private Map<String, Binding> bindings; // // public Bindings() { // this.bindings = new HashMap<>(); // } // // public Bindings(BuiltinScope builtinScope) throws NameNotFoundException { // this(); // // Bootstrap builtins into frame. // for (String name : builtinScope) { // Type type = builtinScope.get(name); // if (type instanceof FunctionType) { // Object function = new Function((FunctionType)type, null); // this.bindings.put(name, new BuiltinBinding(name, function)); // } else { // System.out.println("Skipping bootstrap of builtin " + name + ": " + type.toString()); // } // } // } // // public boolean contains(String name) { // return this.bindings.containsKey(name); // } // // public Binding get(String name) { // return this.bindings.get(name); // } // // public Object getValue(String name) { // Binding binding = this.get(name); // return binding.get(); // } // // public void add(String name, Binding binding) { // this.bindings.put(name, binding); // } // // public static final BindingsIdentifier IDENTIFIER = new BindingsIdentifier(); // // private static final class BindingsIdentifier { // private BindingsIdentifier() { // } // } // } // // Path: src/main/java/org/hummingbirdlang/types/FunctionType.java // public final class FunctionType extends ConcreteType { // private final Type[] parameterTypes; // private final Type returnType; // private final String name; // private final CallTarget callTarget; // // Scope where the function was declared. // private Scope declarationScope; // // Scope inside the function (ie. of its block). // private Scope ownScope; // // public FunctionType( // Type[] parameterTypes, // Type returnType, // String name, // CallTarget callTarget // ) { // this.parameterTypes = parameterTypes; // this.returnType = returnType; // this.name = name; // this.callTarget = callTarget; // } // // public Type[] getParameterTypes() { // return this.parameterTypes; // } // // public Type getReturnType() { // return this.returnType; // } // // public String getName() { // return this.name; // } // // public CallTarget getCallTarget() { // return this.callTarget; // } // // public Scope getOwnScope() { // if (this.ownScope != null && !this.ownScope.isClosed()) { // throw new RuntimeException("Scope not yet closed"); // } // return this.ownScope; // } // // public void setOwnScope(Scope scope) { // if (this.ownScope != null) { // throw new RuntimeException("Cannot re-set scope"); // } // this.ownScope = scope; // } // // public Scope getDeclarationScope() { // if (this.declarationScope != null && !this.declarationScope.isClosed()) { // throw new RuntimeException("Scope not yet closed"); // } // return this.declarationScope; // } // // public void setDeclarationScope(Scope declarationScope) { // if (this.declarationScope != null) { // throw new RuntimeException("Cannot re-set scope"); // } // this.declarationScope = declarationScope; // } // // @Override // public Property getProperty(String name) throws PropertyNotFoundException { // throw new PropertyNotFoundException("Not yet implemented"); // } // }
import com.oracle.truffle.api.CallTarget; import org.hummingbirdlang.runtime.bindings.Bindings; import org.hummingbirdlang.types.FunctionType;
package org.hummingbirdlang.objects; public final class Function { private final FunctionType type;
// Path: src/main/java/org/hummingbirdlang/runtime/bindings/Bindings.java // public final class Bindings { // private Map<String, Binding> bindings; // // public Bindings() { // this.bindings = new HashMap<>(); // } // // public Bindings(BuiltinScope builtinScope) throws NameNotFoundException { // this(); // // Bootstrap builtins into frame. // for (String name : builtinScope) { // Type type = builtinScope.get(name); // if (type instanceof FunctionType) { // Object function = new Function((FunctionType)type, null); // this.bindings.put(name, new BuiltinBinding(name, function)); // } else { // System.out.println("Skipping bootstrap of builtin " + name + ": " + type.toString()); // } // } // } // // public boolean contains(String name) { // return this.bindings.containsKey(name); // } // // public Binding get(String name) { // return this.bindings.get(name); // } // // public Object getValue(String name) { // Binding binding = this.get(name); // return binding.get(); // } // // public void add(String name, Binding binding) { // this.bindings.put(name, binding); // } // // public static final BindingsIdentifier IDENTIFIER = new BindingsIdentifier(); // // private static final class BindingsIdentifier { // private BindingsIdentifier() { // } // } // } // // Path: src/main/java/org/hummingbirdlang/types/FunctionType.java // public final class FunctionType extends ConcreteType { // private final Type[] parameterTypes; // private final Type returnType; // private final String name; // private final CallTarget callTarget; // // Scope where the function was declared. // private Scope declarationScope; // // Scope inside the function (ie. of its block). // private Scope ownScope; // // public FunctionType( // Type[] parameterTypes, // Type returnType, // String name, // CallTarget callTarget // ) { // this.parameterTypes = parameterTypes; // this.returnType = returnType; // this.name = name; // this.callTarget = callTarget; // } // // public Type[] getParameterTypes() { // return this.parameterTypes; // } // // public Type getReturnType() { // return this.returnType; // } // // public String getName() { // return this.name; // } // // public CallTarget getCallTarget() { // return this.callTarget; // } // // public Scope getOwnScope() { // if (this.ownScope != null && !this.ownScope.isClosed()) { // throw new RuntimeException("Scope not yet closed"); // } // return this.ownScope; // } // // public void setOwnScope(Scope scope) { // if (this.ownScope != null) { // throw new RuntimeException("Cannot re-set scope"); // } // this.ownScope = scope; // } // // public Scope getDeclarationScope() { // if (this.declarationScope != null && !this.declarationScope.isClosed()) { // throw new RuntimeException("Scope not yet closed"); // } // return this.declarationScope; // } // // public void setDeclarationScope(Scope declarationScope) { // if (this.declarationScope != null) { // throw new RuntimeException("Cannot re-set scope"); // } // this.declarationScope = declarationScope; // } // // @Override // public Property getProperty(String name) throws PropertyNotFoundException { // throw new PropertyNotFoundException("Not yet implemented"); // } // } // Path: src/main/java/org/hummingbirdlang/objects/Function.java import com.oracle.truffle.api.CallTarget; import org.hummingbirdlang.runtime.bindings.Bindings; import org.hummingbirdlang.types.FunctionType; package org.hummingbirdlang.objects; public final class Function { private final FunctionType type;
private final Bindings bindings;
dirk/hummingbird2
src/main/java/org/hummingbirdlang/types/composite/TypeReferenceType.java
// Path: src/main/java/org/hummingbirdlang/types/CompositeType.java // public abstract class CompositeType extends Type { // } // // Path: src/main/java/org/hummingbirdlang/types/Property.java // public abstract class Property { // // The type of the thing of which this is a property. For example in // // `foo.bar` where `foo: Foo`, the parent would be the type `Foo`. // private final Type parent; // // The name of the property, in the previous example `bar`. // private final String name; // // protected Property(Type parent, String name) { // this.parent = parent; // this.name = name; // } // // // Returns the type of the property (right now just `MethodType`). // public abstract Type getType(); // } // // Path: src/main/java/org/hummingbirdlang/types/PropertyNotFoundException.java // public class PropertyNotFoundException extends TypeException { // public PropertyNotFoundException(String message) { // super(message); // } // // public PropertyNotFoundException(Type type, String name) { // super("Unknown property " + name + " of " + type.toString()); // } // } // // Path: src/main/java/org/hummingbirdlang/types/Type.java // public abstract class Type { // public abstract Property getProperty(String name) throws PropertyNotFoundException; // // public void assertEquals(Type otherType) throws TypeMismatchException { // // Rudimentary pointer comparison by default. // if (this != otherType) { // throw new TypeMismatchException(this, otherType); // } // } // // /** // * Returns whether or not this type is equal to another type. // */ // public boolean equals(Type otherType) { // try { // this.assertEquals(otherType); // } catch (TypeMismatchException exception) { // return false; // } // return true; // } // }
import org.hummingbirdlang.types.CompositeType; import org.hummingbirdlang.types.Property; import org.hummingbirdlang.types.PropertyNotFoundException; import org.hummingbirdlang.types.Type;
package org.hummingbirdlang.types.composite; /** * When we describe a variable like `foo = "bar"` the type of `foo` is * `String`, but to describe types themselves we need an intermediate * container to hold the reference to that underlying type. That's * the function of the type reference type. */ public class TypeReferenceType extends CompositeType { private Type type; public TypeReferenceType(Type type) { this.type = type; } public Type getType() { return this.type; } @Override
// Path: src/main/java/org/hummingbirdlang/types/CompositeType.java // public abstract class CompositeType extends Type { // } // // Path: src/main/java/org/hummingbirdlang/types/Property.java // public abstract class Property { // // The type of the thing of which this is a property. For example in // // `foo.bar` where `foo: Foo`, the parent would be the type `Foo`. // private final Type parent; // // The name of the property, in the previous example `bar`. // private final String name; // // protected Property(Type parent, String name) { // this.parent = parent; // this.name = name; // } // // // Returns the type of the property (right now just `MethodType`). // public abstract Type getType(); // } // // Path: src/main/java/org/hummingbirdlang/types/PropertyNotFoundException.java // public class PropertyNotFoundException extends TypeException { // public PropertyNotFoundException(String message) { // super(message); // } // // public PropertyNotFoundException(Type type, String name) { // super("Unknown property " + name + " of " + type.toString()); // } // } // // Path: src/main/java/org/hummingbirdlang/types/Type.java // public abstract class Type { // public abstract Property getProperty(String name) throws PropertyNotFoundException; // // public void assertEquals(Type otherType) throws TypeMismatchException { // // Rudimentary pointer comparison by default. // if (this != otherType) { // throw new TypeMismatchException(this, otherType); // } // } // // /** // * Returns whether or not this type is equal to another type. // */ // public boolean equals(Type otherType) { // try { // this.assertEquals(otherType); // } catch (TypeMismatchException exception) { // return false; // } // return true; // } // } // Path: src/main/java/org/hummingbirdlang/types/composite/TypeReferenceType.java import org.hummingbirdlang.types.CompositeType; import org.hummingbirdlang.types.Property; import org.hummingbirdlang.types.PropertyNotFoundException; import org.hummingbirdlang.types.Type; package org.hummingbirdlang.types.composite; /** * When we describe a variable like `foo = "bar"` the type of `foo` is * `String`, but to describe types themselves we need an intermediate * container to hold the reference to that underlying type. That's * the function of the type reference type. */ public class TypeReferenceType extends CompositeType { private Type type; public TypeReferenceType(Type type) { this.type = type; } public Type getType() { return this.type; } @Override
public Property getProperty(String name) throws PropertyNotFoundException {
dirk/hummingbird2
src/main/java/org/hummingbirdlang/types/composite/TypeReferenceType.java
// Path: src/main/java/org/hummingbirdlang/types/CompositeType.java // public abstract class CompositeType extends Type { // } // // Path: src/main/java/org/hummingbirdlang/types/Property.java // public abstract class Property { // // The type of the thing of which this is a property. For example in // // `foo.bar` where `foo: Foo`, the parent would be the type `Foo`. // private final Type parent; // // The name of the property, in the previous example `bar`. // private final String name; // // protected Property(Type parent, String name) { // this.parent = parent; // this.name = name; // } // // // Returns the type of the property (right now just `MethodType`). // public abstract Type getType(); // } // // Path: src/main/java/org/hummingbirdlang/types/PropertyNotFoundException.java // public class PropertyNotFoundException extends TypeException { // public PropertyNotFoundException(String message) { // super(message); // } // // public PropertyNotFoundException(Type type, String name) { // super("Unknown property " + name + " of " + type.toString()); // } // } // // Path: src/main/java/org/hummingbirdlang/types/Type.java // public abstract class Type { // public abstract Property getProperty(String name) throws PropertyNotFoundException; // // public void assertEquals(Type otherType) throws TypeMismatchException { // // Rudimentary pointer comparison by default. // if (this != otherType) { // throw new TypeMismatchException(this, otherType); // } // } // // /** // * Returns whether or not this type is equal to another type. // */ // public boolean equals(Type otherType) { // try { // this.assertEquals(otherType); // } catch (TypeMismatchException exception) { // return false; // } // return true; // } // }
import org.hummingbirdlang.types.CompositeType; import org.hummingbirdlang.types.Property; import org.hummingbirdlang.types.PropertyNotFoundException; import org.hummingbirdlang.types.Type;
package org.hummingbirdlang.types.composite; /** * When we describe a variable like `foo = "bar"` the type of `foo` is * `String`, but to describe types themselves we need an intermediate * container to hold the reference to that underlying type. That's * the function of the type reference type. */ public class TypeReferenceType extends CompositeType { private Type type; public TypeReferenceType(Type type) { this.type = type; } public Type getType() { return this.type; } @Override
// Path: src/main/java/org/hummingbirdlang/types/CompositeType.java // public abstract class CompositeType extends Type { // } // // Path: src/main/java/org/hummingbirdlang/types/Property.java // public abstract class Property { // // The type of the thing of which this is a property. For example in // // `foo.bar` where `foo: Foo`, the parent would be the type `Foo`. // private final Type parent; // // The name of the property, in the previous example `bar`. // private final String name; // // protected Property(Type parent, String name) { // this.parent = parent; // this.name = name; // } // // // Returns the type of the property (right now just `MethodType`). // public abstract Type getType(); // } // // Path: src/main/java/org/hummingbirdlang/types/PropertyNotFoundException.java // public class PropertyNotFoundException extends TypeException { // public PropertyNotFoundException(String message) { // super(message); // } // // public PropertyNotFoundException(Type type, String name) { // super("Unknown property " + name + " of " + type.toString()); // } // } // // Path: src/main/java/org/hummingbirdlang/types/Type.java // public abstract class Type { // public abstract Property getProperty(String name) throws PropertyNotFoundException; // // public void assertEquals(Type otherType) throws TypeMismatchException { // // Rudimentary pointer comparison by default. // if (this != otherType) { // throw new TypeMismatchException(this, otherType); // } // } // // /** // * Returns whether or not this type is equal to another type. // */ // public boolean equals(Type otherType) { // try { // this.assertEquals(otherType); // } catch (TypeMismatchException exception) { // return false; // } // return true; // } // } // Path: src/main/java/org/hummingbirdlang/types/composite/TypeReferenceType.java import org.hummingbirdlang.types.CompositeType; import org.hummingbirdlang.types.Property; import org.hummingbirdlang.types.PropertyNotFoundException; import org.hummingbirdlang.types.Type; package org.hummingbirdlang.types.composite; /** * When we describe a variable like `foo = "bar"` the type of `foo` is * `String`, but to describe types themselves we need an intermediate * container to hold the reference to that underlying type. That's * the function of the type reference type. */ public class TypeReferenceType extends CompositeType { private Type type; public TypeReferenceType(Type type) { this.type = type; } public Type getType() { return this.type; } @Override
public Property getProperty(String name) throws PropertyNotFoundException {
dirk/hummingbird2
src/main/java/org/hummingbirdlang/nodes/builtins/HBBuiltinRootNode.java
// Path: src/main/java/org/hummingbirdlang/HBLanguage.java // @TruffleLanguage.Registration(name = "Hummingbird", version = "0.1", mimeType = HBLanguage.MIME_TYPE) // public final class HBLanguage extends TruffleLanguage<HBContext> { // public static final String MIME_TYPE = "application/x-hummingbird"; // // public HBLanguage() { // } // // @Override // protected HBContext createContext(Env env) { // BufferedReader in = new BufferedReader(new InputStreamReader(env.in())); // PrintWriter out = new PrintWriter(env.out(), true); // return new HBContext(env, in, out); // } // // @Override // protected CallTarget parse(ParsingRequest request) throws Exception { // Source source = request.getSource(); // HBSourceRootNode program = ParserWrapper.parse(this, source); // // System.out.println(program.toString()); // // // Bootstrap the builtin node targets and the builtin types in the // // type-system. // BuiltinNodes builtinNodes = BuiltinNodes.bootstrap(this); // Index index = Index.bootstrap(builtinNodes); // // InferenceVisitor visitor = new InferenceVisitor(index); // program.accept(visitor); // // return Truffle.getRuntime().createCallTarget(program); // } // // // TODO: Fully remove this deprecated implementation.: // // // // @Override // // protected CallTarget parse(Source source, Node node, String... argumentNames) throws Exception { // // Object program = ParserWrapper.parse(source); // // System.out.println(program.toString()); // // return null; // // } // // // Called when some other language is seeking for a global symbol. // @Override // protected Object findExportedSymbol(HBContext context, String globalName, boolean onlyExplicit) { // return null; // } // // @Override // protected Object getLanguageGlobal(HBContext context) { // // Context is the highest level global. // return context; // } // // @Override // protected boolean isObjectOfLanguage(Object object) { // return false; // } // } // // Path: src/main/java/org/hummingbirdlang/nodes/HBNode.java // @NodeInfo(language = "HB") // public abstract class HBNode extends Node { // // Execute with a generic unspecialized return value. // public abstract Object executeGeneric(VirtualFrame frame); // // // Execute without a return value. // public void executeVoid(VirtualFrame frame) { // executeGeneric(frame); // } // }
import org.hummingbirdlang.HBLanguage; import org.hummingbirdlang.nodes.HBNode; import com.oracle.truffle.api.frame.FrameDescriptor; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.nodes.RootNode; import com.oracle.truffle.api.nodes.Node.Child;
package org.hummingbirdlang.nodes.builtins; public class HBBuiltinRootNode extends RootNode { @Child private HBNode bodyNode;
// Path: src/main/java/org/hummingbirdlang/HBLanguage.java // @TruffleLanguage.Registration(name = "Hummingbird", version = "0.1", mimeType = HBLanguage.MIME_TYPE) // public final class HBLanguage extends TruffleLanguage<HBContext> { // public static final String MIME_TYPE = "application/x-hummingbird"; // // public HBLanguage() { // } // // @Override // protected HBContext createContext(Env env) { // BufferedReader in = new BufferedReader(new InputStreamReader(env.in())); // PrintWriter out = new PrintWriter(env.out(), true); // return new HBContext(env, in, out); // } // // @Override // protected CallTarget parse(ParsingRequest request) throws Exception { // Source source = request.getSource(); // HBSourceRootNode program = ParserWrapper.parse(this, source); // // System.out.println(program.toString()); // // // Bootstrap the builtin node targets and the builtin types in the // // type-system. // BuiltinNodes builtinNodes = BuiltinNodes.bootstrap(this); // Index index = Index.bootstrap(builtinNodes); // // InferenceVisitor visitor = new InferenceVisitor(index); // program.accept(visitor); // // return Truffle.getRuntime().createCallTarget(program); // } // // // TODO: Fully remove this deprecated implementation.: // // // // @Override // // protected CallTarget parse(Source source, Node node, String... argumentNames) throws Exception { // // Object program = ParserWrapper.parse(source); // // System.out.println(program.toString()); // // return null; // // } // // // Called when some other language is seeking for a global symbol. // @Override // protected Object findExportedSymbol(HBContext context, String globalName, boolean onlyExplicit) { // return null; // } // // @Override // protected Object getLanguageGlobal(HBContext context) { // // Context is the highest level global. // return context; // } // // @Override // protected boolean isObjectOfLanguage(Object object) { // return false; // } // } // // Path: src/main/java/org/hummingbirdlang/nodes/HBNode.java // @NodeInfo(language = "HB") // public abstract class HBNode extends Node { // // Execute with a generic unspecialized return value. // public abstract Object executeGeneric(VirtualFrame frame); // // // Execute without a return value. // public void executeVoid(VirtualFrame frame) { // executeGeneric(frame); // } // } // Path: src/main/java/org/hummingbirdlang/nodes/builtins/HBBuiltinRootNode.java import org.hummingbirdlang.HBLanguage; import org.hummingbirdlang.nodes.HBNode; import com.oracle.truffle.api.frame.FrameDescriptor; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.nodes.RootNode; import com.oracle.truffle.api.nodes.Node.Child; package org.hummingbirdlang.nodes.builtins; public class HBBuiltinRootNode extends RootNode { @Child private HBNode bodyNode;
public HBBuiltinRootNode(HBLanguage language, FrameDescriptor frameDescriptor, HBNode bodyNode) {
dirk/hummingbird2
src/main/java/org/hummingbirdlang/nodes/HBVarDeclarationNode.java
// Path: src/main/java/org/hummingbirdlang/types/realize/InferenceVisitor.java // public final class InferenceVisitor { // private final Index index; // private BuiltinScope builtinScope; // private Scope currentScope; // // public InferenceVisitor(Index index) { // this.builtinScope = new BuiltinScope(index); // this.currentScope = new SourceScope(this.builtinScope); // this.index = index; // } // // private void pushScope() { // Scope parentScope = this.currentScope; // this.currentScope = new LocalScope(parentScope); // } // // private void popScope() { // this.currentScope = this.currentScope.getParent(); // } // // public void enter(HBSourceRootNode rootNode) { // rootNode.setBuiltinScope(this.builtinScope); // } // // public void leave(HBSourceRootNode rootNode) { // // Current scope should be the `SourceScope`. // if (!(this.currentScope instanceof SourceScope)) { // throw new RuntimeException("Did not return to SourceScope"); // } // this.currentScope.close(); // } // // public void enter(HBFunctionNode functionNode) { // // TODO: Actually set and/or infer parameter and return types. // FunctionType functionType = new FunctionType( // new Type[]{}, // new UnknownType(), // functionNode.getName(), // functionNode.getCallTarget() // ); // functionNode.setFunctionType(functionType); // functionType.setDeclarationScope(this.currentScope); // this.currentScope.setLocal(functionNode.getName(), functionType); // this.pushScope(); // functionType.setOwnScope(this.currentScope); // } // // public void leave(HBFunctionNode functionNode) { // this.currentScope.close(); // this.popScope(); // } // // public void enter(HBBlockNode blockNode) { // return; // } // // public void leave(HBBlockNode blockNode) { // return; // } // // public void visit(HBAssignmentNode assignmentNode) throws TypeMismatchException { // Type targetType = assignmentNode.getTargetNode().getType(); // Type valueType = assignmentNode.getValueNode().getType(); // targetType.assertEquals(valueType); // } // // public void visit(HBCallNode callNode) throws TypeMismatchException { // Type targetType = callNode.getTargetNode().getType(); // // Type[] parameterTypes; // Type returnType; // if (targetType instanceof FunctionType) { // FunctionType functionType = (FunctionType)targetType; // parameterTypes = functionType.getParameterTypes(); // returnType = functionType.getReturnType(); // } else if (targetType instanceof MethodType) { // MethodType methodType = (MethodType)targetType; // parameterTypes = methodType.getParameterTypes(); // returnType = methodType.getReturnType(); // } else { // throw new RuntimeException("Cannot call target of type: " + String.valueOf(targetType)); // } // // HBExpressionNode[] argumentNodes = callNode.getArgumentNodes(); // int expectedParameters = parameterTypes.length; // int actualArguments = argumentNodes.length; // if (expectedParameters != actualArguments) { // throw new TypeMismatchException("Argument count mismatch: expected " + expectedParameters + " got " + actualArguments); // } // // for (int index = 0; index < expectedParameters; index++) { // Type parameterType = parameterTypes[index]; // Type argumentType = argumentNodes[index].getType(); // if (!parameterType.equals(argumentType)) { // throw new TypeMismatchException("Argument " + (index + 1) + " mismatch: expected " + parameterType.toString() + " got " + String.valueOf(argumentType)); // } // } // // callNode.setType(returnType); // } // // public void visit(HBIdentifierNode identifierNode) throws NameNotFoundException { // Resolution resolution = this.currentScope.resolve(identifierNode.getName()); // identifierNode.setResolution(resolution); // } // // public void visit(HBIntegerLiteralNode literalNode) { // literalNode.setType(this.getIntegerType()); // } // // public void visit(HBLetDeclarationNode letNode) { // Type rightType = letNode.getRightNode().getType(); // String left = letNode.getLeft(); // this.currentScope.setLocal(left, rightType); // } // // public void visit(HBLogicalAndNode andNode) { // Type leftType = andNode.getLeftNode().getType(); // Type rightType = andNode.getRightNode().getType(); // // Type resultType; // if (!rightType.equals(BooleanType.SINGLETON)) { // resultType = new SumType(new Type[]{ BooleanType.SINGLETON, rightType, }); // } else { // resultType = BooleanType.SINGLETON; // } // andNode.setType(resultType); // } // // public void visit(HBPropertyNode propertyNode) throws PropertyNotFoundException { // Type targetType = propertyNode.getTargetNode().getType(); // Property property = targetType.getProperty(propertyNode.getPropertyName()); // propertyNode.setProperty(property); // propertyNode.setType(property.getType()); // } // // public void visit(HBReturnNode returnNode) { // Type returnType = NullType.SINGLETON; // HBExpressionNode expressionNode = returnNode.getExpressionNode(); // if (expressionNode != null) { // returnType = expressionNode.getType(); // } // returnNode.setReturnType(returnType); // } // // public void visit(HBStringLiteralNode literalNode) { // literalNode.setType(this.getStringType()); // } // // private StringType getStringType() { // Type type = this.index.getBuiltin().getType(StringType.BUILTIN_NAME); // return (StringType)type; // } // // private IntegerType getIntegerType() { // Type type = this.index.getBuiltin().getType(IntegerType.BUILTIN_NAME); // return (IntegerType)type; // } // }
import com.oracle.truffle.api.frame.VirtualFrame; import org.hummingbirdlang.types.realize.InferenceVisitor;
package org.hummingbirdlang.nodes; public class HBVarDeclarationNode extends HBStatementNode { private final String left; @Child private HBExpressionNode rightNode; public HBVarDeclarationNode(String left, HBExpressionNode rightNode) { this.left = left; this.rightNode = rightNode; }
// Path: src/main/java/org/hummingbirdlang/types/realize/InferenceVisitor.java // public final class InferenceVisitor { // private final Index index; // private BuiltinScope builtinScope; // private Scope currentScope; // // public InferenceVisitor(Index index) { // this.builtinScope = new BuiltinScope(index); // this.currentScope = new SourceScope(this.builtinScope); // this.index = index; // } // // private void pushScope() { // Scope parentScope = this.currentScope; // this.currentScope = new LocalScope(parentScope); // } // // private void popScope() { // this.currentScope = this.currentScope.getParent(); // } // // public void enter(HBSourceRootNode rootNode) { // rootNode.setBuiltinScope(this.builtinScope); // } // // public void leave(HBSourceRootNode rootNode) { // // Current scope should be the `SourceScope`. // if (!(this.currentScope instanceof SourceScope)) { // throw new RuntimeException("Did not return to SourceScope"); // } // this.currentScope.close(); // } // // public void enter(HBFunctionNode functionNode) { // // TODO: Actually set and/or infer parameter and return types. // FunctionType functionType = new FunctionType( // new Type[]{}, // new UnknownType(), // functionNode.getName(), // functionNode.getCallTarget() // ); // functionNode.setFunctionType(functionType); // functionType.setDeclarationScope(this.currentScope); // this.currentScope.setLocal(functionNode.getName(), functionType); // this.pushScope(); // functionType.setOwnScope(this.currentScope); // } // // public void leave(HBFunctionNode functionNode) { // this.currentScope.close(); // this.popScope(); // } // // public void enter(HBBlockNode blockNode) { // return; // } // // public void leave(HBBlockNode blockNode) { // return; // } // // public void visit(HBAssignmentNode assignmentNode) throws TypeMismatchException { // Type targetType = assignmentNode.getTargetNode().getType(); // Type valueType = assignmentNode.getValueNode().getType(); // targetType.assertEquals(valueType); // } // // public void visit(HBCallNode callNode) throws TypeMismatchException { // Type targetType = callNode.getTargetNode().getType(); // // Type[] parameterTypes; // Type returnType; // if (targetType instanceof FunctionType) { // FunctionType functionType = (FunctionType)targetType; // parameterTypes = functionType.getParameterTypes(); // returnType = functionType.getReturnType(); // } else if (targetType instanceof MethodType) { // MethodType methodType = (MethodType)targetType; // parameterTypes = methodType.getParameterTypes(); // returnType = methodType.getReturnType(); // } else { // throw new RuntimeException("Cannot call target of type: " + String.valueOf(targetType)); // } // // HBExpressionNode[] argumentNodes = callNode.getArgumentNodes(); // int expectedParameters = parameterTypes.length; // int actualArguments = argumentNodes.length; // if (expectedParameters != actualArguments) { // throw new TypeMismatchException("Argument count mismatch: expected " + expectedParameters + " got " + actualArguments); // } // // for (int index = 0; index < expectedParameters; index++) { // Type parameterType = parameterTypes[index]; // Type argumentType = argumentNodes[index].getType(); // if (!parameterType.equals(argumentType)) { // throw new TypeMismatchException("Argument " + (index + 1) + " mismatch: expected " + parameterType.toString() + " got " + String.valueOf(argumentType)); // } // } // // callNode.setType(returnType); // } // // public void visit(HBIdentifierNode identifierNode) throws NameNotFoundException { // Resolution resolution = this.currentScope.resolve(identifierNode.getName()); // identifierNode.setResolution(resolution); // } // // public void visit(HBIntegerLiteralNode literalNode) { // literalNode.setType(this.getIntegerType()); // } // // public void visit(HBLetDeclarationNode letNode) { // Type rightType = letNode.getRightNode().getType(); // String left = letNode.getLeft(); // this.currentScope.setLocal(left, rightType); // } // // public void visit(HBLogicalAndNode andNode) { // Type leftType = andNode.getLeftNode().getType(); // Type rightType = andNode.getRightNode().getType(); // // Type resultType; // if (!rightType.equals(BooleanType.SINGLETON)) { // resultType = new SumType(new Type[]{ BooleanType.SINGLETON, rightType, }); // } else { // resultType = BooleanType.SINGLETON; // } // andNode.setType(resultType); // } // // public void visit(HBPropertyNode propertyNode) throws PropertyNotFoundException { // Type targetType = propertyNode.getTargetNode().getType(); // Property property = targetType.getProperty(propertyNode.getPropertyName()); // propertyNode.setProperty(property); // propertyNode.setType(property.getType()); // } // // public void visit(HBReturnNode returnNode) { // Type returnType = NullType.SINGLETON; // HBExpressionNode expressionNode = returnNode.getExpressionNode(); // if (expressionNode != null) { // returnType = expressionNode.getType(); // } // returnNode.setReturnType(returnType); // } // // public void visit(HBStringLiteralNode literalNode) { // literalNode.setType(this.getStringType()); // } // // private StringType getStringType() { // Type type = this.index.getBuiltin().getType(StringType.BUILTIN_NAME); // return (StringType)type; // } // // private IntegerType getIntegerType() { // Type type = this.index.getBuiltin().getType(IntegerType.BUILTIN_NAME); // return (IntegerType)type; // } // } // Path: src/main/java/org/hummingbirdlang/nodes/HBVarDeclarationNode.java import com.oracle.truffle.api.frame.VirtualFrame; import org.hummingbirdlang.types.realize.InferenceVisitor; package org.hummingbirdlang.nodes; public class HBVarDeclarationNode extends HBStatementNode { private final String left; @Child private HBExpressionNode rightNode; public HBVarDeclarationNode(String left, HBExpressionNode rightNode) { this.left = left; this.rightNode = rightNode; }
public void accept(InferenceVisitor visitor) {
dirk/hummingbird2
src/main/java/org/hummingbirdlang/types/scope/LocalScope.java
// Path: src/main/java/org/hummingbirdlang/types/Type.java // public abstract class Type { // public abstract Property getProperty(String name) throws PropertyNotFoundException; // // public void assertEquals(Type otherType) throws TypeMismatchException { // // Rudimentary pointer comparison by default. // if (this != otherType) { // throw new TypeMismatchException(this, otherType); // } // } // // /** // * Returns whether or not this type is equal to another type. // */ // public boolean equals(Type otherType) { // try { // this.assertEquals(otherType); // } catch (TypeMismatchException exception) { // return false; // } // return true; // } // }
import java.util.HashMap; import java.util.Map; import org.hummingbirdlang.types.Type;
package org.hummingbirdlang.types.scope; /** * Defines a local scope, such as inside of a function. */ public class LocalScope extends AbstractScope implements Scope { private Scope parent; // Types of local variables.
// Path: src/main/java/org/hummingbirdlang/types/Type.java // public abstract class Type { // public abstract Property getProperty(String name) throws PropertyNotFoundException; // // public void assertEquals(Type otherType) throws TypeMismatchException { // // Rudimentary pointer comparison by default. // if (this != otherType) { // throw new TypeMismatchException(this, otherType); // } // } // // /** // * Returns whether or not this type is equal to another type. // */ // public boolean equals(Type otherType) { // try { // this.assertEquals(otherType); // } catch (TypeMismatchException exception) { // return false; // } // return true; // } // } // Path: src/main/java/org/hummingbirdlang/types/scope/LocalScope.java import java.util.HashMap; import java.util.Map; import org.hummingbirdlang.types.Type; package org.hummingbirdlang.types.scope; /** * Defines a local scope, such as inside of a function. */ public class LocalScope extends AbstractScope implements Scope { private Scope parent; // Types of local variables.
private Map<String, Type> types;
dirk/hummingbird2
src/main/java/org/hummingbirdlang/nodes/HBIndexerNode.java
// Path: src/main/java/org/hummingbirdlang/types/realize/InferenceVisitor.java // public final class InferenceVisitor { // private final Index index; // private BuiltinScope builtinScope; // private Scope currentScope; // // public InferenceVisitor(Index index) { // this.builtinScope = new BuiltinScope(index); // this.currentScope = new SourceScope(this.builtinScope); // this.index = index; // } // // private void pushScope() { // Scope parentScope = this.currentScope; // this.currentScope = new LocalScope(parentScope); // } // // private void popScope() { // this.currentScope = this.currentScope.getParent(); // } // // public void enter(HBSourceRootNode rootNode) { // rootNode.setBuiltinScope(this.builtinScope); // } // // public void leave(HBSourceRootNode rootNode) { // // Current scope should be the `SourceScope`. // if (!(this.currentScope instanceof SourceScope)) { // throw new RuntimeException("Did not return to SourceScope"); // } // this.currentScope.close(); // } // // public void enter(HBFunctionNode functionNode) { // // TODO: Actually set and/or infer parameter and return types. // FunctionType functionType = new FunctionType( // new Type[]{}, // new UnknownType(), // functionNode.getName(), // functionNode.getCallTarget() // ); // functionNode.setFunctionType(functionType); // functionType.setDeclarationScope(this.currentScope); // this.currentScope.setLocal(functionNode.getName(), functionType); // this.pushScope(); // functionType.setOwnScope(this.currentScope); // } // // public void leave(HBFunctionNode functionNode) { // this.currentScope.close(); // this.popScope(); // } // // public void enter(HBBlockNode blockNode) { // return; // } // // public void leave(HBBlockNode blockNode) { // return; // } // // public void visit(HBAssignmentNode assignmentNode) throws TypeMismatchException { // Type targetType = assignmentNode.getTargetNode().getType(); // Type valueType = assignmentNode.getValueNode().getType(); // targetType.assertEquals(valueType); // } // // public void visit(HBCallNode callNode) throws TypeMismatchException { // Type targetType = callNode.getTargetNode().getType(); // // Type[] parameterTypes; // Type returnType; // if (targetType instanceof FunctionType) { // FunctionType functionType = (FunctionType)targetType; // parameterTypes = functionType.getParameterTypes(); // returnType = functionType.getReturnType(); // } else if (targetType instanceof MethodType) { // MethodType methodType = (MethodType)targetType; // parameterTypes = methodType.getParameterTypes(); // returnType = methodType.getReturnType(); // } else { // throw new RuntimeException("Cannot call target of type: " + String.valueOf(targetType)); // } // // HBExpressionNode[] argumentNodes = callNode.getArgumentNodes(); // int expectedParameters = parameterTypes.length; // int actualArguments = argumentNodes.length; // if (expectedParameters != actualArguments) { // throw new TypeMismatchException("Argument count mismatch: expected " + expectedParameters + " got " + actualArguments); // } // // for (int index = 0; index < expectedParameters; index++) { // Type parameterType = parameterTypes[index]; // Type argumentType = argumentNodes[index].getType(); // if (!parameterType.equals(argumentType)) { // throw new TypeMismatchException("Argument " + (index + 1) + " mismatch: expected " + parameterType.toString() + " got " + String.valueOf(argumentType)); // } // } // // callNode.setType(returnType); // } // // public void visit(HBIdentifierNode identifierNode) throws NameNotFoundException { // Resolution resolution = this.currentScope.resolve(identifierNode.getName()); // identifierNode.setResolution(resolution); // } // // public void visit(HBIntegerLiteralNode literalNode) { // literalNode.setType(this.getIntegerType()); // } // // public void visit(HBLetDeclarationNode letNode) { // Type rightType = letNode.getRightNode().getType(); // String left = letNode.getLeft(); // this.currentScope.setLocal(left, rightType); // } // // public void visit(HBLogicalAndNode andNode) { // Type leftType = andNode.getLeftNode().getType(); // Type rightType = andNode.getRightNode().getType(); // // Type resultType; // if (!rightType.equals(BooleanType.SINGLETON)) { // resultType = new SumType(new Type[]{ BooleanType.SINGLETON, rightType, }); // } else { // resultType = BooleanType.SINGLETON; // } // andNode.setType(resultType); // } // // public void visit(HBPropertyNode propertyNode) throws PropertyNotFoundException { // Type targetType = propertyNode.getTargetNode().getType(); // Property property = targetType.getProperty(propertyNode.getPropertyName()); // propertyNode.setProperty(property); // propertyNode.setType(property.getType()); // } // // public void visit(HBReturnNode returnNode) { // Type returnType = NullType.SINGLETON; // HBExpressionNode expressionNode = returnNode.getExpressionNode(); // if (expressionNode != null) { // returnType = expressionNode.getType(); // } // returnNode.setReturnType(returnType); // } // // public void visit(HBStringLiteralNode literalNode) { // literalNode.setType(this.getStringType()); // } // // private StringType getStringType() { // Type type = this.index.getBuiltin().getType(StringType.BUILTIN_NAME); // return (StringType)type; // } // // private IntegerType getIntegerType() { // Type type = this.index.getBuiltin().getType(IntegerType.BUILTIN_NAME); // return (IntegerType)type; // } // }
import com.oracle.truffle.api.frame.VirtualFrame; import org.hummingbirdlang.types.realize.InferenceVisitor;
package org.hummingbirdlang.nodes; public class HBIndexerNode extends HBExpressionNode { @Child private HBExpressionNode targetNode; @Child private HBExpressionNode indexNode; public HBIndexerNode(HBExpressionNode targetNode, HBExpressionNode indexNode) { this.targetNode = targetNode; this.indexNode = indexNode; }
// Path: src/main/java/org/hummingbirdlang/types/realize/InferenceVisitor.java // public final class InferenceVisitor { // private final Index index; // private BuiltinScope builtinScope; // private Scope currentScope; // // public InferenceVisitor(Index index) { // this.builtinScope = new BuiltinScope(index); // this.currentScope = new SourceScope(this.builtinScope); // this.index = index; // } // // private void pushScope() { // Scope parentScope = this.currentScope; // this.currentScope = new LocalScope(parentScope); // } // // private void popScope() { // this.currentScope = this.currentScope.getParent(); // } // // public void enter(HBSourceRootNode rootNode) { // rootNode.setBuiltinScope(this.builtinScope); // } // // public void leave(HBSourceRootNode rootNode) { // // Current scope should be the `SourceScope`. // if (!(this.currentScope instanceof SourceScope)) { // throw new RuntimeException("Did not return to SourceScope"); // } // this.currentScope.close(); // } // // public void enter(HBFunctionNode functionNode) { // // TODO: Actually set and/or infer parameter and return types. // FunctionType functionType = new FunctionType( // new Type[]{}, // new UnknownType(), // functionNode.getName(), // functionNode.getCallTarget() // ); // functionNode.setFunctionType(functionType); // functionType.setDeclarationScope(this.currentScope); // this.currentScope.setLocal(functionNode.getName(), functionType); // this.pushScope(); // functionType.setOwnScope(this.currentScope); // } // // public void leave(HBFunctionNode functionNode) { // this.currentScope.close(); // this.popScope(); // } // // public void enter(HBBlockNode blockNode) { // return; // } // // public void leave(HBBlockNode blockNode) { // return; // } // // public void visit(HBAssignmentNode assignmentNode) throws TypeMismatchException { // Type targetType = assignmentNode.getTargetNode().getType(); // Type valueType = assignmentNode.getValueNode().getType(); // targetType.assertEquals(valueType); // } // // public void visit(HBCallNode callNode) throws TypeMismatchException { // Type targetType = callNode.getTargetNode().getType(); // // Type[] parameterTypes; // Type returnType; // if (targetType instanceof FunctionType) { // FunctionType functionType = (FunctionType)targetType; // parameterTypes = functionType.getParameterTypes(); // returnType = functionType.getReturnType(); // } else if (targetType instanceof MethodType) { // MethodType methodType = (MethodType)targetType; // parameterTypes = methodType.getParameterTypes(); // returnType = methodType.getReturnType(); // } else { // throw new RuntimeException("Cannot call target of type: " + String.valueOf(targetType)); // } // // HBExpressionNode[] argumentNodes = callNode.getArgumentNodes(); // int expectedParameters = parameterTypes.length; // int actualArguments = argumentNodes.length; // if (expectedParameters != actualArguments) { // throw new TypeMismatchException("Argument count mismatch: expected " + expectedParameters + " got " + actualArguments); // } // // for (int index = 0; index < expectedParameters; index++) { // Type parameterType = parameterTypes[index]; // Type argumentType = argumentNodes[index].getType(); // if (!parameterType.equals(argumentType)) { // throw new TypeMismatchException("Argument " + (index + 1) + " mismatch: expected " + parameterType.toString() + " got " + String.valueOf(argumentType)); // } // } // // callNode.setType(returnType); // } // // public void visit(HBIdentifierNode identifierNode) throws NameNotFoundException { // Resolution resolution = this.currentScope.resolve(identifierNode.getName()); // identifierNode.setResolution(resolution); // } // // public void visit(HBIntegerLiteralNode literalNode) { // literalNode.setType(this.getIntegerType()); // } // // public void visit(HBLetDeclarationNode letNode) { // Type rightType = letNode.getRightNode().getType(); // String left = letNode.getLeft(); // this.currentScope.setLocal(left, rightType); // } // // public void visit(HBLogicalAndNode andNode) { // Type leftType = andNode.getLeftNode().getType(); // Type rightType = andNode.getRightNode().getType(); // // Type resultType; // if (!rightType.equals(BooleanType.SINGLETON)) { // resultType = new SumType(new Type[]{ BooleanType.SINGLETON, rightType, }); // } else { // resultType = BooleanType.SINGLETON; // } // andNode.setType(resultType); // } // // public void visit(HBPropertyNode propertyNode) throws PropertyNotFoundException { // Type targetType = propertyNode.getTargetNode().getType(); // Property property = targetType.getProperty(propertyNode.getPropertyName()); // propertyNode.setProperty(property); // propertyNode.setType(property.getType()); // } // // public void visit(HBReturnNode returnNode) { // Type returnType = NullType.SINGLETON; // HBExpressionNode expressionNode = returnNode.getExpressionNode(); // if (expressionNode != null) { // returnType = expressionNode.getType(); // } // returnNode.setReturnType(returnType); // } // // public void visit(HBStringLiteralNode literalNode) { // literalNode.setType(this.getStringType()); // } // // private StringType getStringType() { // Type type = this.index.getBuiltin().getType(StringType.BUILTIN_NAME); // return (StringType)type; // } // // private IntegerType getIntegerType() { // Type type = this.index.getBuiltin().getType(IntegerType.BUILTIN_NAME); // return (IntegerType)type; // } // } // Path: src/main/java/org/hummingbirdlang/nodes/HBIndexerNode.java import com.oracle.truffle.api.frame.VirtualFrame; import org.hummingbirdlang.types.realize.InferenceVisitor; package org.hummingbirdlang.nodes; public class HBIndexerNode extends HBExpressionNode { @Child private HBExpressionNode targetNode; @Child private HBExpressionNode indexNode; public HBIndexerNode(HBExpressionNode targetNode, HBExpressionNode indexNode) { this.targetNode = targetNode; this.indexNode = indexNode; }
public void accept(InferenceVisitor visitor) {
timwhit/lego
product-web/src/main/java/com/whitney/product/web/controller/ProductController.java
// Path: common/src/main/java/com/whitney/common/util/MapperUtils.java // @Service // public class MapperUtils extends ModelMapper { // public MapperUtils() { // this.getConfiguration().setFieldMatchingEnabled(true).setFieldAccessLevel(org.modelmapper.config.Configuration.AccessLevel.PRIVATE); // } // } // // Path: product-service/src/main/java/com/whitney/product/domain/Product.java // public class Product { // private Long id; // private String description; // private BigDecimal amount; // private Integer inventory; // // public Product() {} // // public Product(Long id, String description, BigDecimal amount, Integer inventory) { // this.id = id; // this.description = description; // this.amount = amount; // this.inventory = inventory; // } // // public Long getId() { // return id; // } // // public String getDescription() { // return description; // } // // public BigDecimal getAmount() { // return amount; // } // // public Integer getInventory() { // return inventory; // } // } // // Path: product-service/src/main/java/com/whitney/product/service/ProductService.java // public interface ProductService { // Product get(Long id); // // Product create(Product product); // // void processCompletedSale(String data); // } // // Path: product-web/src/main/java/com/whitney/product/web/vo/ProductVO.java // public class ProductVO { // private Long id; // private String description; // private BigDecimal amount; // private Integer inventory; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public BigDecimal getAmount() { // return amount; // } // // public void setAmount(BigDecimal amount) { // this.amount = amount; // } // // public Integer getInventory() { // return inventory; // } // // public void setInventory(Integer inventory) { // this.inventory = inventory; // } // }
import com.whitney.common.util.MapperUtils; import com.whitney.product.domain.Product; import com.whitney.product.service.ProductService; import com.whitney.product.web.vo.ProductVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*;
package com.whitney.product.web.controller; @RestController @RequestMapping("/rest/product") public class ProductController { @Autowired
// Path: common/src/main/java/com/whitney/common/util/MapperUtils.java // @Service // public class MapperUtils extends ModelMapper { // public MapperUtils() { // this.getConfiguration().setFieldMatchingEnabled(true).setFieldAccessLevel(org.modelmapper.config.Configuration.AccessLevel.PRIVATE); // } // } // // Path: product-service/src/main/java/com/whitney/product/domain/Product.java // public class Product { // private Long id; // private String description; // private BigDecimal amount; // private Integer inventory; // // public Product() {} // // public Product(Long id, String description, BigDecimal amount, Integer inventory) { // this.id = id; // this.description = description; // this.amount = amount; // this.inventory = inventory; // } // // public Long getId() { // return id; // } // // public String getDescription() { // return description; // } // // public BigDecimal getAmount() { // return amount; // } // // public Integer getInventory() { // return inventory; // } // } // // Path: product-service/src/main/java/com/whitney/product/service/ProductService.java // public interface ProductService { // Product get(Long id); // // Product create(Product product); // // void processCompletedSale(String data); // } // // Path: product-web/src/main/java/com/whitney/product/web/vo/ProductVO.java // public class ProductVO { // private Long id; // private String description; // private BigDecimal amount; // private Integer inventory; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public BigDecimal getAmount() { // return amount; // } // // public void setAmount(BigDecimal amount) { // this.amount = amount; // } // // public Integer getInventory() { // return inventory; // } // // public void setInventory(Integer inventory) { // this.inventory = inventory; // } // } // Path: product-web/src/main/java/com/whitney/product/web/controller/ProductController.java import com.whitney.common.util.MapperUtils; import com.whitney.product.domain.Product; import com.whitney.product.service.ProductService; import com.whitney.product.web.vo.ProductVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; package com.whitney.product.web.controller; @RestController @RequestMapping("/rest/product") public class ProductController { @Autowired
private ProductService productService;
timwhit/lego
product-web/src/main/java/com/whitney/product/web/controller/ProductController.java
// Path: common/src/main/java/com/whitney/common/util/MapperUtils.java // @Service // public class MapperUtils extends ModelMapper { // public MapperUtils() { // this.getConfiguration().setFieldMatchingEnabled(true).setFieldAccessLevel(org.modelmapper.config.Configuration.AccessLevel.PRIVATE); // } // } // // Path: product-service/src/main/java/com/whitney/product/domain/Product.java // public class Product { // private Long id; // private String description; // private BigDecimal amount; // private Integer inventory; // // public Product() {} // // public Product(Long id, String description, BigDecimal amount, Integer inventory) { // this.id = id; // this.description = description; // this.amount = amount; // this.inventory = inventory; // } // // public Long getId() { // return id; // } // // public String getDescription() { // return description; // } // // public BigDecimal getAmount() { // return amount; // } // // public Integer getInventory() { // return inventory; // } // } // // Path: product-service/src/main/java/com/whitney/product/service/ProductService.java // public interface ProductService { // Product get(Long id); // // Product create(Product product); // // void processCompletedSale(String data); // } // // Path: product-web/src/main/java/com/whitney/product/web/vo/ProductVO.java // public class ProductVO { // private Long id; // private String description; // private BigDecimal amount; // private Integer inventory; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public BigDecimal getAmount() { // return amount; // } // // public void setAmount(BigDecimal amount) { // this.amount = amount; // } // // public Integer getInventory() { // return inventory; // } // // public void setInventory(Integer inventory) { // this.inventory = inventory; // } // }
import com.whitney.common.util.MapperUtils; import com.whitney.product.domain.Product; import com.whitney.product.service.ProductService; import com.whitney.product.web.vo.ProductVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*;
package com.whitney.product.web.controller; @RestController @RequestMapping("/rest/product") public class ProductController { @Autowired private ProductService productService; @Autowired
// Path: common/src/main/java/com/whitney/common/util/MapperUtils.java // @Service // public class MapperUtils extends ModelMapper { // public MapperUtils() { // this.getConfiguration().setFieldMatchingEnabled(true).setFieldAccessLevel(org.modelmapper.config.Configuration.AccessLevel.PRIVATE); // } // } // // Path: product-service/src/main/java/com/whitney/product/domain/Product.java // public class Product { // private Long id; // private String description; // private BigDecimal amount; // private Integer inventory; // // public Product() {} // // public Product(Long id, String description, BigDecimal amount, Integer inventory) { // this.id = id; // this.description = description; // this.amount = amount; // this.inventory = inventory; // } // // public Long getId() { // return id; // } // // public String getDescription() { // return description; // } // // public BigDecimal getAmount() { // return amount; // } // // public Integer getInventory() { // return inventory; // } // } // // Path: product-service/src/main/java/com/whitney/product/service/ProductService.java // public interface ProductService { // Product get(Long id); // // Product create(Product product); // // void processCompletedSale(String data); // } // // Path: product-web/src/main/java/com/whitney/product/web/vo/ProductVO.java // public class ProductVO { // private Long id; // private String description; // private BigDecimal amount; // private Integer inventory; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public BigDecimal getAmount() { // return amount; // } // // public void setAmount(BigDecimal amount) { // this.amount = amount; // } // // public Integer getInventory() { // return inventory; // } // // public void setInventory(Integer inventory) { // this.inventory = inventory; // } // } // Path: product-web/src/main/java/com/whitney/product/web/controller/ProductController.java import com.whitney.common.util.MapperUtils; import com.whitney.product.domain.Product; import com.whitney.product.service.ProductService; import com.whitney.product.web.vo.ProductVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; package com.whitney.product.web.controller; @RestController @RequestMapping("/rest/product") public class ProductController { @Autowired private ProductService productService; @Autowired
private MapperUtils mapper;
timwhit/lego
product-web/src/main/java/com/whitney/product/web/controller/ProductController.java
// Path: common/src/main/java/com/whitney/common/util/MapperUtils.java // @Service // public class MapperUtils extends ModelMapper { // public MapperUtils() { // this.getConfiguration().setFieldMatchingEnabled(true).setFieldAccessLevel(org.modelmapper.config.Configuration.AccessLevel.PRIVATE); // } // } // // Path: product-service/src/main/java/com/whitney/product/domain/Product.java // public class Product { // private Long id; // private String description; // private BigDecimal amount; // private Integer inventory; // // public Product() {} // // public Product(Long id, String description, BigDecimal amount, Integer inventory) { // this.id = id; // this.description = description; // this.amount = amount; // this.inventory = inventory; // } // // public Long getId() { // return id; // } // // public String getDescription() { // return description; // } // // public BigDecimal getAmount() { // return amount; // } // // public Integer getInventory() { // return inventory; // } // } // // Path: product-service/src/main/java/com/whitney/product/service/ProductService.java // public interface ProductService { // Product get(Long id); // // Product create(Product product); // // void processCompletedSale(String data); // } // // Path: product-web/src/main/java/com/whitney/product/web/vo/ProductVO.java // public class ProductVO { // private Long id; // private String description; // private BigDecimal amount; // private Integer inventory; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public BigDecimal getAmount() { // return amount; // } // // public void setAmount(BigDecimal amount) { // this.amount = amount; // } // // public Integer getInventory() { // return inventory; // } // // public void setInventory(Integer inventory) { // this.inventory = inventory; // } // }
import com.whitney.common.util.MapperUtils; import com.whitney.product.domain.Product; import com.whitney.product.service.ProductService; import com.whitney.product.web.vo.ProductVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*;
package com.whitney.product.web.controller; @RestController @RequestMapping("/rest/product") public class ProductController { @Autowired private ProductService productService; @Autowired private MapperUtils mapper; @RequestMapping(value = "/{productId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
// Path: common/src/main/java/com/whitney/common/util/MapperUtils.java // @Service // public class MapperUtils extends ModelMapper { // public MapperUtils() { // this.getConfiguration().setFieldMatchingEnabled(true).setFieldAccessLevel(org.modelmapper.config.Configuration.AccessLevel.PRIVATE); // } // } // // Path: product-service/src/main/java/com/whitney/product/domain/Product.java // public class Product { // private Long id; // private String description; // private BigDecimal amount; // private Integer inventory; // // public Product() {} // // public Product(Long id, String description, BigDecimal amount, Integer inventory) { // this.id = id; // this.description = description; // this.amount = amount; // this.inventory = inventory; // } // // public Long getId() { // return id; // } // // public String getDescription() { // return description; // } // // public BigDecimal getAmount() { // return amount; // } // // public Integer getInventory() { // return inventory; // } // } // // Path: product-service/src/main/java/com/whitney/product/service/ProductService.java // public interface ProductService { // Product get(Long id); // // Product create(Product product); // // void processCompletedSale(String data); // } // // Path: product-web/src/main/java/com/whitney/product/web/vo/ProductVO.java // public class ProductVO { // private Long id; // private String description; // private BigDecimal amount; // private Integer inventory; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public BigDecimal getAmount() { // return amount; // } // // public void setAmount(BigDecimal amount) { // this.amount = amount; // } // // public Integer getInventory() { // return inventory; // } // // public void setInventory(Integer inventory) { // this.inventory = inventory; // } // } // Path: product-web/src/main/java/com/whitney/product/web/controller/ProductController.java import com.whitney.common.util.MapperUtils; import com.whitney.product.domain.Product; import com.whitney.product.service.ProductService; import com.whitney.product.web.vo.ProductVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; package com.whitney.product.web.controller; @RestController @RequestMapping("/rest/product") public class ProductController { @Autowired private ProductService productService; @Autowired private MapperUtils mapper; @RequestMapping(value = "/{productId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ProductVO get(@PathVariable Long productId) {
timwhit/lego
product-web/src/main/java/com/whitney/product/web/controller/ProductController.java
// Path: common/src/main/java/com/whitney/common/util/MapperUtils.java // @Service // public class MapperUtils extends ModelMapper { // public MapperUtils() { // this.getConfiguration().setFieldMatchingEnabled(true).setFieldAccessLevel(org.modelmapper.config.Configuration.AccessLevel.PRIVATE); // } // } // // Path: product-service/src/main/java/com/whitney/product/domain/Product.java // public class Product { // private Long id; // private String description; // private BigDecimal amount; // private Integer inventory; // // public Product() {} // // public Product(Long id, String description, BigDecimal amount, Integer inventory) { // this.id = id; // this.description = description; // this.amount = amount; // this.inventory = inventory; // } // // public Long getId() { // return id; // } // // public String getDescription() { // return description; // } // // public BigDecimal getAmount() { // return amount; // } // // public Integer getInventory() { // return inventory; // } // } // // Path: product-service/src/main/java/com/whitney/product/service/ProductService.java // public interface ProductService { // Product get(Long id); // // Product create(Product product); // // void processCompletedSale(String data); // } // // Path: product-web/src/main/java/com/whitney/product/web/vo/ProductVO.java // public class ProductVO { // private Long id; // private String description; // private BigDecimal amount; // private Integer inventory; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public BigDecimal getAmount() { // return amount; // } // // public void setAmount(BigDecimal amount) { // this.amount = amount; // } // // public Integer getInventory() { // return inventory; // } // // public void setInventory(Integer inventory) { // this.inventory = inventory; // } // }
import com.whitney.common.util.MapperUtils; import com.whitney.product.domain.Product; import com.whitney.product.service.ProductService; import com.whitney.product.web.vo.ProductVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*;
package com.whitney.product.web.controller; @RestController @RequestMapping("/rest/product") public class ProductController { @Autowired private ProductService productService; @Autowired private MapperUtils mapper; @RequestMapping(value = "/{productId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ProductVO get(@PathVariable Long productId) { return this.mapper.map(this.productService.get(productId), ProductVO.class); } @RequestMapping(value = "/", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) public ProductVO create(@RequestBody ProductVO product) {
// Path: common/src/main/java/com/whitney/common/util/MapperUtils.java // @Service // public class MapperUtils extends ModelMapper { // public MapperUtils() { // this.getConfiguration().setFieldMatchingEnabled(true).setFieldAccessLevel(org.modelmapper.config.Configuration.AccessLevel.PRIVATE); // } // } // // Path: product-service/src/main/java/com/whitney/product/domain/Product.java // public class Product { // private Long id; // private String description; // private BigDecimal amount; // private Integer inventory; // // public Product() {} // // public Product(Long id, String description, BigDecimal amount, Integer inventory) { // this.id = id; // this.description = description; // this.amount = amount; // this.inventory = inventory; // } // // public Long getId() { // return id; // } // // public String getDescription() { // return description; // } // // public BigDecimal getAmount() { // return amount; // } // // public Integer getInventory() { // return inventory; // } // } // // Path: product-service/src/main/java/com/whitney/product/service/ProductService.java // public interface ProductService { // Product get(Long id); // // Product create(Product product); // // void processCompletedSale(String data); // } // // Path: product-web/src/main/java/com/whitney/product/web/vo/ProductVO.java // public class ProductVO { // private Long id; // private String description; // private BigDecimal amount; // private Integer inventory; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public BigDecimal getAmount() { // return amount; // } // // public void setAmount(BigDecimal amount) { // this.amount = amount; // } // // public Integer getInventory() { // return inventory; // } // // public void setInventory(Integer inventory) { // this.inventory = inventory; // } // } // Path: product-web/src/main/java/com/whitney/product/web/controller/ProductController.java import com.whitney.common.util.MapperUtils; import com.whitney.product.domain.Product; import com.whitney.product.service.ProductService; import com.whitney.product.web.vo.ProductVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; package com.whitney.product.web.controller; @RestController @RequestMapping("/rest/product") public class ProductController { @Autowired private ProductService productService; @Autowired private MapperUtils mapper; @RequestMapping(value = "/{productId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ProductVO get(@PathVariable Long productId) { return this.mapper.map(this.productService.get(productId), ProductVO.class); } @RequestMapping(value = "/", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) public ProductVO create(@RequestBody ProductVO product) {
Product createdProduct = this.productService.create(this.mapper.map(product, Product.class));
timwhit/lego
sales-web/src/main/java/com/whitney/sales/web/controller/SalesController.java
// Path: common/src/main/java/com/whitney/common/util/MapperUtils.java // @Service // public class MapperUtils extends ModelMapper { // public MapperUtils() { // this.getConfiguration().setFieldMatchingEnabled(true).setFieldAccessLevel(org.modelmapper.config.Configuration.AccessLevel.PRIVATE); // } // } // // Path: sales-service/src/main/java/com/whitney/sales/service/SalesService.java // public interface SalesService { // Sale get(Long id); // // Sale create(Sale sale); // } // // Path: sales-service/src/main/java/com/whitney/sales/service/domain/Sale.java // public class Sale { // private Long id; // private Long productId; // private Long userId; // private Integer quantity; // private BigDecimal amount; // // public Sale() {} // // public Sale(Long id, Long productId, Long userId, Integer quantity, BigDecimal amount) { // this.id = id; // this.productId = productId; // this.userId = userId; // this.quantity = quantity; // this.amount = amount; // } // // public Long getId() { // return id; // } // // public Long getProductId() { // return productId; // } // // public Long getUserId() { // return userId; // } // // public Integer getQuantity() { // return quantity; // } // // public BigDecimal getAmount() { // return amount; // } // } // // Path: sales-vo/src/main/java/com/whitney/sales/web/vo/SaleVO.java // public class SaleVO { // private Long id; // private Long productId; // private Long userId; // private Integer quantity; // private BigDecimal amount; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProductId() { // return productId; // } // // public void setProductId(Long productId) { // this.productId = productId; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public Integer getQuantity() { // return quantity; // } // // public void setQuantity(Integer quantity) { // this.quantity = quantity; // } // // public BigDecimal getAmount() { // return amount; // } // // public void setAmount(BigDecimal amount) { // this.amount = amount; // } // }
import com.whitney.common.util.MapperUtils; import com.whitney.sales.service.SalesService; import com.whitney.sales.service.domain.Sale; import com.whitney.sales.web.vo.SaleVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*;
package com.whitney.sales.web.controller; @RestController @RequestMapping("/rest/sales") public class SalesController { @Autowired
// Path: common/src/main/java/com/whitney/common/util/MapperUtils.java // @Service // public class MapperUtils extends ModelMapper { // public MapperUtils() { // this.getConfiguration().setFieldMatchingEnabled(true).setFieldAccessLevel(org.modelmapper.config.Configuration.AccessLevel.PRIVATE); // } // } // // Path: sales-service/src/main/java/com/whitney/sales/service/SalesService.java // public interface SalesService { // Sale get(Long id); // // Sale create(Sale sale); // } // // Path: sales-service/src/main/java/com/whitney/sales/service/domain/Sale.java // public class Sale { // private Long id; // private Long productId; // private Long userId; // private Integer quantity; // private BigDecimal amount; // // public Sale() {} // // public Sale(Long id, Long productId, Long userId, Integer quantity, BigDecimal amount) { // this.id = id; // this.productId = productId; // this.userId = userId; // this.quantity = quantity; // this.amount = amount; // } // // public Long getId() { // return id; // } // // public Long getProductId() { // return productId; // } // // public Long getUserId() { // return userId; // } // // public Integer getQuantity() { // return quantity; // } // // public BigDecimal getAmount() { // return amount; // } // } // // Path: sales-vo/src/main/java/com/whitney/sales/web/vo/SaleVO.java // public class SaleVO { // private Long id; // private Long productId; // private Long userId; // private Integer quantity; // private BigDecimal amount; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProductId() { // return productId; // } // // public void setProductId(Long productId) { // this.productId = productId; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public Integer getQuantity() { // return quantity; // } // // public void setQuantity(Integer quantity) { // this.quantity = quantity; // } // // public BigDecimal getAmount() { // return amount; // } // // public void setAmount(BigDecimal amount) { // this.amount = amount; // } // } // Path: sales-web/src/main/java/com/whitney/sales/web/controller/SalesController.java import com.whitney.common.util.MapperUtils; import com.whitney.sales.service.SalesService; import com.whitney.sales.service.domain.Sale; import com.whitney.sales.web.vo.SaleVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; package com.whitney.sales.web.controller; @RestController @RequestMapping("/rest/sales") public class SalesController { @Autowired
private SalesService salesService;
timwhit/lego
sales-web/src/main/java/com/whitney/sales/web/controller/SalesController.java
// Path: common/src/main/java/com/whitney/common/util/MapperUtils.java // @Service // public class MapperUtils extends ModelMapper { // public MapperUtils() { // this.getConfiguration().setFieldMatchingEnabled(true).setFieldAccessLevel(org.modelmapper.config.Configuration.AccessLevel.PRIVATE); // } // } // // Path: sales-service/src/main/java/com/whitney/sales/service/SalesService.java // public interface SalesService { // Sale get(Long id); // // Sale create(Sale sale); // } // // Path: sales-service/src/main/java/com/whitney/sales/service/domain/Sale.java // public class Sale { // private Long id; // private Long productId; // private Long userId; // private Integer quantity; // private BigDecimal amount; // // public Sale() {} // // public Sale(Long id, Long productId, Long userId, Integer quantity, BigDecimal amount) { // this.id = id; // this.productId = productId; // this.userId = userId; // this.quantity = quantity; // this.amount = amount; // } // // public Long getId() { // return id; // } // // public Long getProductId() { // return productId; // } // // public Long getUserId() { // return userId; // } // // public Integer getQuantity() { // return quantity; // } // // public BigDecimal getAmount() { // return amount; // } // } // // Path: sales-vo/src/main/java/com/whitney/sales/web/vo/SaleVO.java // public class SaleVO { // private Long id; // private Long productId; // private Long userId; // private Integer quantity; // private BigDecimal amount; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProductId() { // return productId; // } // // public void setProductId(Long productId) { // this.productId = productId; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public Integer getQuantity() { // return quantity; // } // // public void setQuantity(Integer quantity) { // this.quantity = quantity; // } // // public BigDecimal getAmount() { // return amount; // } // // public void setAmount(BigDecimal amount) { // this.amount = amount; // } // }
import com.whitney.common.util.MapperUtils; import com.whitney.sales.service.SalesService; import com.whitney.sales.service.domain.Sale; import com.whitney.sales.web.vo.SaleVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*;
package com.whitney.sales.web.controller; @RestController @RequestMapping("/rest/sales") public class SalesController { @Autowired private SalesService salesService; @Autowired
// Path: common/src/main/java/com/whitney/common/util/MapperUtils.java // @Service // public class MapperUtils extends ModelMapper { // public MapperUtils() { // this.getConfiguration().setFieldMatchingEnabled(true).setFieldAccessLevel(org.modelmapper.config.Configuration.AccessLevel.PRIVATE); // } // } // // Path: sales-service/src/main/java/com/whitney/sales/service/SalesService.java // public interface SalesService { // Sale get(Long id); // // Sale create(Sale sale); // } // // Path: sales-service/src/main/java/com/whitney/sales/service/domain/Sale.java // public class Sale { // private Long id; // private Long productId; // private Long userId; // private Integer quantity; // private BigDecimal amount; // // public Sale() {} // // public Sale(Long id, Long productId, Long userId, Integer quantity, BigDecimal amount) { // this.id = id; // this.productId = productId; // this.userId = userId; // this.quantity = quantity; // this.amount = amount; // } // // public Long getId() { // return id; // } // // public Long getProductId() { // return productId; // } // // public Long getUserId() { // return userId; // } // // public Integer getQuantity() { // return quantity; // } // // public BigDecimal getAmount() { // return amount; // } // } // // Path: sales-vo/src/main/java/com/whitney/sales/web/vo/SaleVO.java // public class SaleVO { // private Long id; // private Long productId; // private Long userId; // private Integer quantity; // private BigDecimal amount; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProductId() { // return productId; // } // // public void setProductId(Long productId) { // this.productId = productId; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public Integer getQuantity() { // return quantity; // } // // public void setQuantity(Integer quantity) { // this.quantity = quantity; // } // // public BigDecimal getAmount() { // return amount; // } // // public void setAmount(BigDecimal amount) { // this.amount = amount; // } // } // Path: sales-web/src/main/java/com/whitney/sales/web/controller/SalesController.java import com.whitney.common.util.MapperUtils; import com.whitney.sales.service.SalesService; import com.whitney.sales.service.domain.Sale; import com.whitney.sales.web.vo.SaleVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; package com.whitney.sales.web.controller; @RestController @RequestMapping("/rest/sales") public class SalesController { @Autowired private SalesService salesService; @Autowired
private MapperUtils mapper;
timwhit/lego
sales-web/src/main/java/com/whitney/sales/web/controller/SalesController.java
// Path: common/src/main/java/com/whitney/common/util/MapperUtils.java // @Service // public class MapperUtils extends ModelMapper { // public MapperUtils() { // this.getConfiguration().setFieldMatchingEnabled(true).setFieldAccessLevel(org.modelmapper.config.Configuration.AccessLevel.PRIVATE); // } // } // // Path: sales-service/src/main/java/com/whitney/sales/service/SalesService.java // public interface SalesService { // Sale get(Long id); // // Sale create(Sale sale); // } // // Path: sales-service/src/main/java/com/whitney/sales/service/domain/Sale.java // public class Sale { // private Long id; // private Long productId; // private Long userId; // private Integer quantity; // private BigDecimal amount; // // public Sale() {} // // public Sale(Long id, Long productId, Long userId, Integer quantity, BigDecimal amount) { // this.id = id; // this.productId = productId; // this.userId = userId; // this.quantity = quantity; // this.amount = amount; // } // // public Long getId() { // return id; // } // // public Long getProductId() { // return productId; // } // // public Long getUserId() { // return userId; // } // // public Integer getQuantity() { // return quantity; // } // // public BigDecimal getAmount() { // return amount; // } // } // // Path: sales-vo/src/main/java/com/whitney/sales/web/vo/SaleVO.java // public class SaleVO { // private Long id; // private Long productId; // private Long userId; // private Integer quantity; // private BigDecimal amount; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProductId() { // return productId; // } // // public void setProductId(Long productId) { // this.productId = productId; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public Integer getQuantity() { // return quantity; // } // // public void setQuantity(Integer quantity) { // this.quantity = quantity; // } // // public BigDecimal getAmount() { // return amount; // } // // public void setAmount(BigDecimal amount) { // this.amount = amount; // } // }
import com.whitney.common.util.MapperUtils; import com.whitney.sales.service.SalesService; import com.whitney.sales.service.domain.Sale; import com.whitney.sales.web.vo.SaleVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*;
package com.whitney.sales.web.controller; @RestController @RequestMapping("/rest/sales") public class SalesController { @Autowired private SalesService salesService; @Autowired private MapperUtils mapper; @RequestMapping(value = "/{salesId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
// Path: common/src/main/java/com/whitney/common/util/MapperUtils.java // @Service // public class MapperUtils extends ModelMapper { // public MapperUtils() { // this.getConfiguration().setFieldMatchingEnabled(true).setFieldAccessLevel(org.modelmapper.config.Configuration.AccessLevel.PRIVATE); // } // } // // Path: sales-service/src/main/java/com/whitney/sales/service/SalesService.java // public interface SalesService { // Sale get(Long id); // // Sale create(Sale sale); // } // // Path: sales-service/src/main/java/com/whitney/sales/service/domain/Sale.java // public class Sale { // private Long id; // private Long productId; // private Long userId; // private Integer quantity; // private BigDecimal amount; // // public Sale() {} // // public Sale(Long id, Long productId, Long userId, Integer quantity, BigDecimal amount) { // this.id = id; // this.productId = productId; // this.userId = userId; // this.quantity = quantity; // this.amount = amount; // } // // public Long getId() { // return id; // } // // public Long getProductId() { // return productId; // } // // public Long getUserId() { // return userId; // } // // public Integer getQuantity() { // return quantity; // } // // public BigDecimal getAmount() { // return amount; // } // } // // Path: sales-vo/src/main/java/com/whitney/sales/web/vo/SaleVO.java // public class SaleVO { // private Long id; // private Long productId; // private Long userId; // private Integer quantity; // private BigDecimal amount; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProductId() { // return productId; // } // // public void setProductId(Long productId) { // this.productId = productId; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public Integer getQuantity() { // return quantity; // } // // public void setQuantity(Integer quantity) { // this.quantity = quantity; // } // // public BigDecimal getAmount() { // return amount; // } // // public void setAmount(BigDecimal amount) { // this.amount = amount; // } // } // Path: sales-web/src/main/java/com/whitney/sales/web/controller/SalesController.java import com.whitney.common.util.MapperUtils; import com.whitney.sales.service.SalesService; import com.whitney.sales.service.domain.Sale; import com.whitney.sales.web.vo.SaleVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; package com.whitney.sales.web.controller; @RestController @RequestMapping("/rest/sales") public class SalesController { @Autowired private SalesService salesService; @Autowired private MapperUtils mapper; @RequestMapping(value = "/{salesId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public SaleVO get(@PathVariable Long salesId) {
timwhit/lego
sales-web/src/main/java/com/whitney/sales/web/controller/SalesController.java
// Path: common/src/main/java/com/whitney/common/util/MapperUtils.java // @Service // public class MapperUtils extends ModelMapper { // public MapperUtils() { // this.getConfiguration().setFieldMatchingEnabled(true).setFieldAccessLevel(org.modelmapper.config.Configuration.AccessLevel.PRIVATE); // } // } // // Path: sales-service/src/main/java/com/whitney/sales/service/SalesService.java // public interface SalesService { // Sale get(Long id); // // Sale create(Sale sale); // } // // Path: sales-service/src/main/java/com/whitney/sales/service/domain/Sale.java // public class Sale { // private Long id; // private Long productId; // private Long userId; // private Integer quantity; // private BigDecimal amount; // // public Sale() {} // // public Sale(Long id, Long productId, Long userId, Integer quantity, BigDecimal amount) { // this.id = id; // this.productId = productId; // this.userId = userId; // this.quantity = quantity; // this.amount = amount; // } // // public Long getId() { // return id; // } // // public Long getProductId() { // return productId; // } // // public Long getUserId() { // return userId; // } // // public Integer getQuantity() { // return quantity; // } // // public BigDecimal getAmount() { // return amount; // } // } // // Path: sales-vo/src/main/java/com/whitney/sales/web/vo/SaleVO.java // public class SaleVO { // private Long id; // private Long productId; // private Long userId; // private Integer quantity; // private BigDecimal amount; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProductId() { // return productId; // } // // public void setProductId(Long productId) { // this.productId = productId; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public Integer getQuantity() { // return quantity; // } // // public void setQuantity(Integer quantity) { // this.quantity = quantity; // } // // public BigDecimal getAmount() { // return amount; // } // // public void setAmount(BigDecimal amount) { // this.amount = amount; // } // }
import com.whitney.common.util.MapperUtils; import com.whitney.sales.service.SalesService; import com.whitney.sales.service.domain.Sale; import com.whitney.sales.web.vo.SaleVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*;
package com.whitney.sales.web.controller; @RestController @RequestMapping("/rest/sales") public class SalesController { @Autowired private SalesService salesService; @Autowired private MapperUtils mapper; @RequestMapping(value = "/{salesId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public SaleVO get(@PathVariable Long salesId) { return this.mapper.map(this.salesService.get(salesId), SaleVO.class); } @RequestMapping(value = "/", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) public SaleVO create(@RequestBody SaleVO sale) {
// Path: common/src/main/java/com/whitney/common/util/MapperUtils.java // @Service // public class MapperUtils extends ModelMapper { // public MapperUtils() { // this.getConfiguration().setFieldMatchingEnabled(true).setFieldAccessLevel(org.modelmapper.config.Configuration.AccessLevel.PRIVATE); // } // } // // Path: sales-service/src/main/java/com/whitney/sales/service/SalesService.java // public interface SalesService { // Sale get(Long id); // // Sale create(Sale sale); // } // // Path: sales-service/src/main/java/com/whitney/sales/service/domain/Sale.java // public class Sale { // private Long id; // private Long productId; // private Long userId; // private Integer quantity; // private BigDecimal amount; // // public Sale() {} // // public Sale(Long id, Long productId, Long userId, Integer quantity, BigDecimal amount) { // this.id = id; // this.productId = productId; // this.userId = userId; // this.quantity = quantity; // this.amount = amount; // } // // public Long getId() { // return id; // } // // public Long getProductId() { // return productId; // } // // public Long getUserId() { // return userId; // } // // public Integer getQuantity() { // return quantity; // } // // public BigDecimal getAmount() { // return amount; // } // } // // Path: sales-vo/src/main/java/com/whitney/sales/web/vo/SaleVO.java // public class SaleVO { // private Long id; // private Long productId; // private Long userId; // private Integer quantity; // private BigDecimal amount; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProductId() { // return productId; // } // // public void setProductId(Long productId) { // this.productId = productId; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public Integer getQuantity() { // return quantity; // } // // public void setQuantity(Integer quantity) { // this.quantity = quantity; // } // // public BigDecimal getAmount() { // return amount; // } // // public void setAmount(BigDecimal amount) { // this.amount = amount; // } // } // Path: sales-web/src/main/java/com/whitney/sales/web/controller/SalesController.java import com.whitney.common.util.MapperUtils; import com.whitney.sales.service.SalesService; import com.whitney.sales.service.domain.Sale; import com.whitney.sales.web.vo.SaleVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; package com.whitney.sales.web.controller; @RestController @RequestMapping("/rest/sales") public class SalesController { @Autowired private SalesService salesService; @Autowired private MapperUtils mapper; @RequestMapping(value = "/{salesId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public SaleVO get(@PathVariable Long salesId) { return this.mapper.map(this.salesService.get(salesId), SaleVO.class); } @RequestMapping(value = "/", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) public SaleVO create(@RequestBody SaleVO sale) {
Sale createdSale = this.salesService.create(this.mapper.map(sale, Sale.class));
timwhit/lego
sales-data-impl/src/main/java/com/whitney/sales/data/dao/ProductDAOImpl.java
// Path: product-web/src/main/java/com/whitney/product/web/vo/ProductVO.java // public class ProductVO { // private Long id; // private String description; // private BigDecimal amount; // private Integer inventory; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public BigDecimal getAmount() { // return amount; // } // // public void setAmount(BigDecimal amount) { // this.amount = amount; // } // // public Integer getInventory() { // return inventory; // } // // public void setInventory(Integer inventory) { // this.inventory = inventory; // } // }
import com.whitney.product.web.vo.ProductVO; import org.springframework.stereotype.Repository; import org.springframework.validation.annotation.Validated; import org.springframework.web.client.RestTemplate;
package com.whitney.sales.data.dao; @Validated @Repository public class ProductDAOImpl implements ProductDAO { private static final String URI = "http://localhost:8083/rest/product/{id}"; @Override
// Path: product-web/src/main/java/com/whitney/product/web/vo/ProductVO.java // public class ProductVO { // private Long id; // private String description; // private BigDecimal amount; // private Integer inventory; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public BigDecimal getAmount() { // return amount; // } // // public void setAmount(BigDecimal amount) { // this.amount = amount; // } // // public Integer getInventory() { // return inventory; // } // // public void setInventory(Integer inventory) { // this.inventory = inventory; // } // } // Path: sales-data-impl/src/main/java/com/whitney/sales/data/dao/ProductDAOImpl.java import com.whitney.product.web.vo.ProductVO; import org.springframework.stereotype.Repository; import org.springframework.validation.annotation.Validated; import org.springframework.web.client.RestTemplate; package com.whitney.sales.data.dao; @Validated @Repository public class ProductDAOImpl implements ProductDAO { private static final String URI = "http://localhost:8083/rest/product/{id}"; @Override
public ProductVO findById(Long productId) {
timwhit/lego
product-service-impl/src/main/java/com/whitney/product/service/ProductServiceImpl.java
// Path: common/src/main/java/com/whitney/common/messaging/MessageQueue.java // public class MessageQueue { // public static final String SALE_CREATED = "saleCreated"; // } // // Path: common/src/main/java/com/whitney/common/util/MapperUtils.java // @Service // public class MapperUtils extends ModelMapper { // public MapperUtils() { // this.getConfiguration().setFieldMatchingEnabled(true).setFieldAccessLevel(org.modelmapper.config.Configuration.AccessLevel.PRIVATE); // } // } // // Path: product-data/src/main/java/com/whitney/product/data/dao/ProductDAO.java // public interface ProductDAO extends JpaRepository<ProductDTO, Long> { // // } // // Path: product-data/src/main/java/com/whitney/product/data/dto/ProductDTO.java // @Entity // @Table(name = "PRODUCT") // public class ProductDTO { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "PRODUCT_ID") // private Long id; // @Column(name = "DESCRIPTION") // private String description; // @Column(name = "AMOUNT") // private BigDecimal amount; // @Column(name = "INVENTORY") // private Integer inventory; // @Column(name = "CREATED_DATE") // private LocalDateTime createdDate; // @Column(name = "CREATED_USER_ID") // private Long createdUserId; // @Column(name = "MODIFIED_DATE") // private LocalDateTime modifiedDate; // @Column(name = "MODIFIED_USER_ID") // private Long modifiedUserId; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public BigDecimal getAmount() { // return amount; // } // // public void setAmount(BigDecimal amount) { // this.amount = amount; // } // // public Integer getInventory() { // return inventory; // } // // public void setInventory(Integer inventory) { // this.inventory = inventory; // } // // public LocalDateTime getCreatedDate() { // return createdDate; // } // // public void setCreatedDate(LocalDateTime createdDate) { // this.createdDate = createdDate; // } // // public Long getCreatedUserId() { // return createdUserId; // } // // public void setCreatedUserId(Long createdUserId) { // this.createdUserId = createdUserId; // } // // public LocalDateTime getModifiedDate() { // return modifiedDate; // } // // public void setModifiedDate(LocalDateTime modifiedDate) { // this.modifiedDate = modifiedDate; // } // // public Long getModifiedUserId() { // return modifiedUserId; // } // // public void setModifiedUserId(Long modifiedUserId) { // this.modifiedUserId = modifiedUserId; // } // } // // Path: product-service/src/main/java/com/whitney/product/domain/Product.java // public class Product { // private Long id; // private String description; // private BigDecimal amount; // private Integer inventory; // // public Product() {} // // public Product(Long id, String description, BigDecimal amount, Integer inventory) { // this.id = id; // this.description = description; // this.amount = amount; // this.inventory = inventory; // } // // public Long getId() { // return id; // } // // public String getDescription() { // return description; // } // // public BigDecimal getAmount() { // return amount; // } // // public Integer getInventory() { // return inventory; // } // } // // Path: sales-vo/src/main/java/com/whitney/sales/web/vo/SaleVO.java // public class SaleVO { // private Long id; // private Long productId; // private Long userId; // private Integer quantity; // private BigDecimal amount; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProductId() { // return productId; // } // // public void setProductId(Long productId) { // this.productId = productId; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public Integer getQuantity() { // return quantity; // } // // public void setQuantity(Integer quantity) { // this.quantity = quantity; // } // // public BigDecimal getAmount() { // return amount; // } // // public void setAmount(BigDecimal amount) { // this.amount = amount; // } // }
import com.fasterxml.jackson.databind.ObjectMapper; import com.whitney.common.messaging.MessageQueue; import com.whitney.common.util.MapperUtils; import com.whitney.product.data.dao.ProductDAO; import com.whitney.product.data.dto.ProductDTO; import com.whitney.product.domain.Product; import com.whitney.sales.web.vo.SaleVO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.annotation.JmsListener; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; import java.io.IOException; import java.time.LocalDateTime;
package com.whitney.product.service; @Validated @Transactional @Service public class ProductServiceImpl implements ProductService { private static final Logger LOG = LoggerFactory.getLogger(ProductServiceImpl.class); @Autowired
// Path: common/src/main/java/com/whitney/common/messaging/MessageQueue.java // public class MessageQueue { // public static final String SALE_CREATED = "saleCreated"; // } // // Path: common/src/main/java/com/whitney/common/util/MapperUtils.java // @Service // public class MapperUtils extends ModelMapper { // public MapperUtils() { // this.getConfiguration().setFieldMatchingEnabled(true).setFieldAccessLevel(org.modelmapper.config.Configuration.AccessLevel.PRIVATE); // } // } // // Path: product-data/src/main/java/com/whitney/product/data/dao/ProductDAO.java // public interface ProductDAO extends JpaRepository<ProductDTO, Long> { // // } // // Path: product-data/src/main/java/com/whitney/product/data/dto/ProductDTO.java // @Entity // @Table(name = "PRODUCT") // public class ProductDTO { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "PRODUCT_ID") // private Long id; // @Column(name = "DESCRIPTION") // private String description; // @Column(name = "AMOUNT") // private BigDecimal amount; // @Column(name = "INVENTORY") // private Integer inventory; // @Column(name = "CREATED_DATE") // private LocalDateTime createdDate; // @Column(name = "CREATED_USER_ID") // private Long createdUserId; // @Column(name = "MODIFIED_DATE") // private LocalDateTime modifiedDate; // @Column(name = "MODIFIED_USER_ID") // private Long modifiedUserId; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public BigDecimal getAmount() { // return amount; // } // // public void setAmount(BigDecimal amount) { // this.amount = amount; // } // // public Integer getInventory() { // return inventory; // } // // public void setInventory(Integer inventory) { // this.inventory = inventory; // } // // public LocalDateTime getCreatedDate() { // return createdDate; // } // // public void setCreatedDate(LocalDateTime createdDate) { // this.createdDate = createdDate; // } // // public Long getCreatedUserId() { // return createdUserId; // } // // public void setCreatedUserId(Long createdUserId) { // this.createdUserId = createdUserId; // } // // public LocalDateTime getModifiedDate() { // return modifiedDate; // } // // public void setModifiedDate(LocalDateTime modifiedDate) { // this.modifiedDate = modifiedDate; // } // // public Long getModifiedUserId() { // return modifiedUserId; // } // // public void setModifiedUserId(Long modifiedUserId) { // this.modifiedUserId = modifiedUserId; // } // } // // Path: product-service/src/main/java/com/whitney/product/domain/Product.java // public class Product { // private Long id; // private String description; // private BigDecimal amount; // private Integer inventory; // // public Product() {} // // public Product(Long id, String description, BigDecimal amount, Integer inventory) { // this.id = id; // this.description = description; // this.amount = amount; // this.inventory = inventory; // } // // public Long getId() { // return id; // } // // public String getDescription() { // return description; // } // // public BigDecimal getAmount() { // return amount; // } // // public Integer getInventory() { // return inventory; // } // } // // Path: sales-vo/src/main/java/com/whitney/sales/web/vo/SaleVO.java // public class SaleVO { // private Long id; // private Long productId; // private Long userId; // private Integer quantity; // private BigDecimal amount; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProductId() { // return productId; // } // // public void setProductId(Long productId) { // this.productId = productId; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public Integer getQuantity() { // return quantity; // } // // public void setQuantity(Integer quantity) { // this.quantity = quantity; // } // // public BigDecimal getAmount() { // return amount; // } // // public void setAmount(BigDecimal amount) { // this.amount = amount; // } // } // Path: product-service-impl/src/main/java/com/whitney/product/service/ProductServiceImpl.java import com.fasterxml.jackson.databind.ObjectMapper; import com.whitney.common.messaging.MessageQueue; import com.whitney.common.util.MapperUtils; import com.whitney.product.data.dao.ProductDAO; import com.whitney.product.data.dto.ProductDTO; import com.whitney.product.domain.Product; import com.whitney.sales.web.vo.SaleVO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.annotation.JmsListener; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; import java.io.IOException; import java.time.LocalDateTime; package com.whitney.product.service; @Validated @Transactional @Service public class ProductServiceImpl implements ProductService { private static final Logger LOG = LoggerFactory.getLogger(ProductServiceImpl.class); @Autowired
private ProductDAO productDAO;
timwhit/lego
product-service-impl/src/main/java/com/whitney/product/service/ProductServiceImpl.java
// Path: common/src/main/java/com/whitney/common/messaging/MessageQueue.java // public class MessageQueue { // public static final String SALE_CREATED = "saleCreated"; // } // // Path: common/src/main/java/com/whitney/common/util/MapperUtils.java // @Service // public class MapperUtils extends ModelMapper { // public MapperUtils() { // this.getConfiguration().setFieldMatchingEnabled(true).setFieldAccessLevel(org.modelmapper.config.Configuration.AccessLevel.PRIVATE); // } // } // // Path: product-data/src/main/java/com/whitney/product/data/dao/ProductDAO.java // public interface ProductDAO extends JpaRepository<ProductDTO, Long> { // // } // // Path: product-data/src/main/java/com/whitney/product/data/dto/ProductDTO.java // @Entity // @Table(name = "PRODUCT") // public class ProductDTO { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "PRODUCT_ID") // private Long id; // @Column(name = "DESCRIPTION") // private String description; // @Column(name = "AMOUNT") // private BigDecimal amount; // @Column(name = "INVENTORY") // private Integer inventory; // @Column(name = "CREATED_DATE") // private LocalDateTime createdDate; // @Column(name = "CREATED_USER_ID") // private Long createdUserId; // @Column(name = "MODIFIED_DATE") // private LocalDateTime modifiedDate; // @Column(name = "MODIFIED_USER_ID") // private Long modifiedUserId; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public BigDecimal getAmount() { // return amount; // } // // public void setAmount(BigDecimal amount) { // this.amount = amount; // } // // public Integer getInventory() { // return inventory; // } // // public void setInventory(Integer inventory) { // this.inventory = inventory; // } // // public LocalDateTime getCreatedDate() { // return createdDate; // } // // public void setCreatedDate(LocalDateTime createdDate) { // this.createdDate = createdDate; // } // // public Long getCreatedUserId() { // return createdUserId; // } // // public void setCreatedUserId(Long createdUserId) { // this.createdUserId = createdUserId; // } // // public LocalDateTime getModifiedDate() { // return modifiedDate; // } // // public void setModifiedDate(LocalDateTime modifiedDate) { // this.modifiedDate = modifiedDate; // } // // public Long getModifiedUserId() { // return modifiedUserId; // } // // public void setModifiedUserId(Long modifiedUserId) { // this.modifiedUserId = modifiedUserId; // } // } // // Path: product-service/src/main/java/com/whitney/product/domain/Product.java // public class Product { // private Long id; // private String description; // private BigDecimal amount; // private Integer inventory; // // public Product() {} // // public Product(Long id, String description, BigDecimal amount, Integer inventory) { // this.id = id; // this.description = description; // this.amount = amount; // this.inventory = inventory; // } // // public Long getId() { // return id; // } // // public String getDescription() { // return description; // } // // public BigDecimal getAmount() { // return amount; // } // // public Integer getInventory() { // return inventory; // } // } // // Path: sales-vo/src/main/java/com/whitney/sales/web/vo/SaleVO.java // public class SaleVO { // private Long id; // private Long productId; // private Long userId; // private Integer quantity; // private BigDecimal amount; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProductId() { // return productId; // } // // public void setProductId(Long productId) { // this.productId = productId; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public Integer getQuantity() { // return quantity; // } // // public void setQuantity(Integer quantity) { // this.quantity = quantity; // } // // public BigDecimal getAmount() { // return amount; // } // // public void setAmount(BigDecimal amount) { // this.amount = amount; // } // }
import com.fasterxml.jackson.databind.ObjectMapper; import com.whitney.common.messaging.MessageQueue; import com.whitney.common.util.MapperUtils; import com.whitney.product.data.dao.ProductDAO; import com.whitney.product.data.dto.ProductDTO; import com.whitney.product.domain.Product; import com.whitney.sales.web.vo.SaleVO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.annotation.JmsListener; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; import java.io.IOException; import java.time.LocalDateTime;
package com.whitney.product.service; @Validated @Transactional @Service public class ProductServiceImpl implements ProductService { private static final Logger LOG = LoggerFactory.getLogger(ProductServiceImpl.class); @Autowired private ProductDAO productDAO; @Autowired
// Path: common/src/main/java/com/whitney/common/messaging/MessageQueue.java // public class MessageQueue { // public static final String SALE_CREATED = "saleCreated"; // } // // Path: common/src/main/java/com/whitney/common/util/MapperUtils.java // @Service // public class MapperUtils extends ModelMapper { // public MapperUtils() { // this.getConfiguration().setFieldMatchingEnabled(true).setFieldAccessLevel(org.modelmapper.config.Configuration.AccessLevel.PRIVATE); // } // } // // Path: product-data/src/main/java/com/whitney/product/data/dao/ProductDAO.java // public interface ProductDAO extends JpaRepository<ProductDTO, Long> { // // } // // Path: product-data/src/main/java/com/whitney/product/data/dto/ProductDTO.java // @Entity // @Table(name = "PRODUCT") // public class ProductDTO { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "PRODUCT_ID") // private Long id; // @Column(name = "DESCRIPTION") // private String description; // @Column(name = "AMOUNT") // private BigDecimal amount; // @Column(name = "INVENTORY") // private Integer inventory; // @Column(name = "CREATED_DATE") // private LocalDateTime createdDate; // @Column(name = "CREATED_USER_ID") // private Long createdUserId; // @Column(name = "MODIFIED_DATE") // private LocalDateTime modifiedDate; // @Column(name = "MODIFIED_USER_ID") // private Long modifiedUserId; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public BigDecimal getAmount() { // return amount; // } // // public void setAmount(BigDecimal amount) { // this.amount = amount; // } // // public Integer getInventory() { // return inventory; // } // // public void setInventory(Integer inventory) { // this.inventory = inventory; // } // // public LocalDateTime getCreatedDate() { // return createdDate; // } // // public void setCreatedDate(LocalDateTime createdDate) { // this.createdDate = createdDate; // } // // public Long getCreatedUserId() { // return createdUserId; // } // // public void setCreatedUserId(Long createdUserId) { // this.createdUserId = createdUserId; // } // // public LocalDateTime getModifiedDate() { // return modifiedDate; // } // // public void setModifiedDate(LocalDateTime modifiedDate) { // this.modifiedDate = modifiedDate; // } // // public Long getModifiedUserId() { // return modifiedUserId; // } // // public void setModifiedUserId(Long modifiedUserId) { // this.modifiedUserId = modifiedUserId; // } // } // // Path: product-service/src/main/java/com/whitney/product/domain/Product.java // public class Product { // private Long id; // private String description; // private BigDecimal amount; // private Integer inventory; // // public Product() {} // // public Product(Long id, String description, BigDecimal amount, Integer inventory) { // this.id = id; // this.description = description; // this.amount = amount; // this.inventory = inventory; // } // // public Long getId() { // return id; // } // // public String getDescription() { // return description; // } // // public BigDecimal getAmount() { // return amount; // } // // public Integer getInventory() { // return inventory; // } // } // // Path: sales-vo/src/main/java/com/whitney/sales/web/vo/SaleVO.java // public class SaleVO { // private Long id; // private Long productId; // private Long userId; // private Integer quantity; // private BigDecimal amount; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProductId() { // return productId; // } // // public void setProductId(Long productId) { // this.productId = productId; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public Integer getQuantity() { // return quantity; // } // // public void setQuantity(Integer quantity) { // this.quantity = quantity; // } // // public BigDecimal getAmount() { // return amount; // } // // public void setAmount(BigDecimal amount) { // this.amount = amount; // } // } // Path: product-service-impl/src/main/java/com/whitney/product/service/ProductServiceImpl.java import com.fasterxml.jackson.databind.ObjectMapper; import com.whitney.common.messaging.MessageQueue; import com.whitney.common.util.MapperUtils; import com.whitney.product.data.dao.ProductDAO; import com.whitney.product.data.dto.ProductDTO; import com.whitney.product.domain.Product; import com.whitney.sales.web.vo.SaleVO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.annotation.JmsListener; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; import java.io.IOException; import java.time.LocalDateTime; package com.whitney.product.service; @Validated @Transactional @Service public class ProductServiceImpl implements ProductService { private static final Logger LOG = LoggerFactory.getLogger(ProductServiceImpl.class); @Autowired private ProductDAO productDAO; @Autowired
private MapperUtils mapper;
timwhit/lego
product-service-impl/src/main/java/com/whitney/product/service/ProductServiceImpl.java
// Path: common/src/main/java/com/whitney/common/messaging/MessageQueue.java // public class MessageQueue { // public static final String SALE_CREATED = "saleCreated"; // } // // Path: common/src/main/java/com/whitney/common/util/MapperUtils.java // @Service // public class MapperUtils extends ModelMapper { // public MapperUtils() { // this.getConfiguration().setFieldMatchingEnabled(true).setFieldAccessLevel(org.modelmapper.config.Configuration.AccessLevel.PRIVATE); // } // } // // Path: product-data/src/main/java/com/whitney/product/data/dao/ProductDAO.java // public interface ProductDAO extends JpaRepository<ProductDTO, Long> { // // } // // Path: product-data/src/main/java/com/whitney/product/data/dto/ProductDTO.java // @Entity // @Table(name = "PRODUCT") // public class ProductDTO { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "PRODUCT_ID") // private Long id; // @Column(name = "DESCRIPTION") // private String description; // @Column(name = "AMOUNT") // private BigDecimal amount; // @Column(name = "INVENTORY") // private Integer inventory; // @Column(name = "CREATED_DATE") // private LocalDateTime createdDate; // @Column(name = "CREATED_USER_ID") // private Long createdUserId; // @Column(name = "MODIFIED_DATE") // private LocalDateTime modifiedDate; // @Column(name = "MODIFIED_USER_ID") // private Long modifiedUserId; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public BigDecimal getAmount() { // return amount; // } // // public void setAmount(BigDecimal amount) { // this.amount = amount; // } // // public Integer getInventory() { // return inventory; // } // // public void setInventory(Integer inventory) { // this.inventory = inventory; // } // // public LocalDateTime getCreatedDate() { // return createdDate; // } // // public void setCreatedDate(LocalDateTime createdDate) { // this.createdDate = createdDate; // } // // public Long getCreatedUserId() { // return createdUserId; // } // // public void setCreatedUserId(Long createdUserId) { // this.createdUserId = createdUserId; // } // // public LocalDateTime getModifiedDate() { // return modifiedDate; // } // // public void setModifiedDate(LocalDateTime modifiedDate) { // this.modifiedDate = modifiedDate; // } // // public Long getModifiedUserId() { // return modifiedUserId; // } // // public void setModifiedUserId(Long modifiedUserId) { // this.modifiedUserId = modifiedUserId; // } // } // // Path: product-service/src/main/java/com/whitney/product/domain/Product.java // public class Product { // private Long id; // private String description; // private BigDecimal amount; // private Integer inventory; // // public Product() {} // // public Product(Long id, String description, BigDecimal amount, Integer inventory) { // this.id = id; // this.description = description; // this.amount = amount; // this.inventory = inventory; // } // // public Long getId() { // return id; // } // // public String getDescription() { // return description; // } // // public BigDecimal getAmount() { // return amount; // } // // public Integer getInventory() { // return inventory; // } // } // // Path: sales-vo/src/main/java/com/whitney/sales/web/vo/SaleVO.java // public class SaleVO { // private Long id; // private Long productId; // private Long userId; // private Integer quantity; // private BigDecimal amount; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProductId() { // return productId; // } // // public void setProductId(Long productId) { // this.productId = productId; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public Integer getQuantity() { // return quantity; // } // // public void setQuantity(Integer quantity) { // this.quantity = quantity; // } // // public BigDecimal getAmount() { // return amount; // } // // public void setAmount(BigDecimal amount) { // this.amount = amount; // } // }
import com.fasterxml.jackson.databind.ObjectMapper; import com.whitney.common.messaging.MessageQueue; import com.whitney.common.util.MapperUtils; import com.whitney.product.data.dao.ProductDAO; import com.whitney.product.data.dto.ProductDTO; import com.whitney.product.domain.Product; import com.whitney.sales.web.vo.SaleVO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.annotation.JmsListener; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; import java.io.IOException; import java.time.LocalDateTime;
package com.whitney.product.service; @Validated @Transactional @Service public class ProductServiceImpl implements ProductService { private static final Logger LOG = LoggerFactory.getLogger(ProductServiceImpl.class); @Autowired private ProductDAO productDAO; @Autowired private MapperUtils mapper; @Autowired private ObjectMapper objectMapper; @Override
// Path: common/src/main/java/com/whitney/common/messaging/MessageQueue.java // public class MessageQueue { // public static final String SALE_CREATED = "saleCreated"; // } // // Path: common/src/main/java/com/whitney/common/util/MapperUtils.java // @Service // public class MapperUtils extends ModelMapper { // public MapperUtils() { // this.getConfiguration().setFieldMatchingEnabled(true).setFieldAccessLevel(org.modelmapper.config.Configuration.AccessLevel.PRIVATE); // } // } // // Path: product-data/src/main/java/com/whitney/product/data/dao/ProductDAO.java // public interface ProductDAO extends JpaRepository<ProductDTO, Long> { // // } // // Path: product-data/src/main/java/com/whitney/product/data/dto/ProductDTO.java // @Entity // @Table(name = "PRODUCT") // public class ProductDTO { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "PRODUCT_ID") // private Long id; // @Column(name = "DESCRIPTION") // private String description; // @Column(name = "AMOUNT") // private BigDecimal amount; // @Column(name = "INVENTORY") // private Integer inventory; // @Column(name = "CREATED_DATE") // private LocalDateTime createdDate; // @Column(name = "CREATED_USER_ID") // private Long createdUserId; // @Column(name = "MODIFIED_DATE") // private LocalDateTime modifiedDate; // @Column(name = "MODIFIED_USER_ID") // private Long modifiedUserId; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public BigDecimal getAmount() { // return amount; // } // // public void setAmount(BigDecimal amount) { // this.amount = amount; // } // // public Integer getInventory() { // return inventory; // } // // public void setInventory(Integer inventory) { // this.inventory = inventory; // } // // public LocalDateTime getCreatedDate() { // return createdDate; // } // // public void setCreatedDate(LocalDateTime createdDate) { // this.createdDate = createdDate; // } // // public Long getCreatedUserId() { // return createdUserId; // } // // public void setCreatedUserId(Long createdUserId) { // this.createdUserId = createdUserId; // } // // public LocalDateTime getModifiedDate() { // return modifiedDate; // } // // public void setModifiedDate(LocalDateTime modifiedDate) { // this.modifiedDate = modifiedDate; // } // // public Long getModifiedUserId() { // return modifiedUserId; // } // // public void setModifiedUserId(Long modifiedUserId) { // this.modifiedUserId = modifiedUserId; // } // } // // Path: product-service/src/main/java/com/whitney/product/domain/Product.java // public class Product { // private Long id; // private String description; // private BigDecimal amount; // private Integer inventory; // // public Product() {} // // public Product(Long id, String description, BigDecimal amount, Integer inventory) { // this.id = id; // this.description = description; // this.amount = amount; // this.inventory = inventory; // } // // public Long getId() { // return id; // } // // public String getDescription() { // return description; // } // // public BigDecimal getAmount() { // return amount; // } // // public Integer getInventory() { // return inventory; // } // } // // Path: sales-vo/src/main/java/com/whitney/sales/web/vo/SaleVO.java // public class SaleVO { // private Long id; // private Long productId; // private Long userId; // private Integer quantity; // private BigDecimal amount; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProductId() { // return productId; // } // // public void setProductId(Long productId) { // this.productId = productId; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public Integer getQuantity() { // return quantity; // } // // public void setQuantity(Integer quantity) { // this.quantity = quantity; // } // // public BigDecimal getAmount() { // return amount; // } // // public void setAmount(BigDecimal amount) { // this.amount = amount; // } // } // Path: product-service-impl/src/main/java/com/whitney/product/service/ProductServiceImpl.java import com.fasterxml.jackson.databind.ObjectMapper; import com.whitney.common.messaging.MessageQueue; import com.whitney.common.util.MapperUtils; import com.whitney.product.data.dao.ProductDAO; import com.whitney.product.data.dto.ProductDTO; import com.whitney.product.domain.Product; import com.whitney.sales.web.vo.SaleVO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.annotation.JmsListener; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; import java.io.IOException; import java.time.LocalDateTime; package com.whitney.product.service; @Validated @Transactional @Service public class ProductServiceImpl implements ProductService { private static final Logger LOG = LoggerFactory.getLogger(ProductServiceImpl.class); @Autowired private ProductDAO productDAO; @Autowired private MapperUtils mapper; @Autowired private ObjectMapper objectMapper; @Override
public Product get(Long id) {
timwhit/lego
parent-web/src/main/java/com/whitney/parent/Application.java
// Path: product-web/src/main/java/com/whitney/product/ProductApplication.java // @Configuration // @EnableAutoConfiguration // @EnableJms // @ComponentScan(value = { "com.whitney.product", "com.whitney.common" }) // public class ProductApplication extends AnnotationConfigEmbeddedWebApplicationContext { // // } // // Path: queue/src/main/java/com/whitney/queue/QueueApplication.java // @Configuration // @EnableAutoConfiguration(exclude = { WebMvcAutoConfiguration.class, LiquibaseAutoConfiguration.class, JpaRepositoriesAutoConfiguration.class, HibernateJpaAutoConfiguration.class }) // @ComponentScan(value = { "com.whitney.queue", "com.whitney.common" }) // public class QueueApplication extends AnnotationConfigApplicationContext { // // } // // Path: sales-web/src/main/java/com/whitney/sales/SalesApplication.java // @Configuration // @EnableAutoConfiguration // @EnableJms // @ComponentScan(value = { "com.whitney.sales", "com.whitney.common" }) // public class SalesApplication extends AnnotationConfigEmbeddedWebApplicationContext { // // } // // Path: support-web/src/main/java/com/whitney/support/SupportApplication.java // @Configuration // @EnableAutoConfiguration // @EnableJms // @ComponentScan(value = { "com.whitney.support", "com.whitney.common" }) // public class SupportApplication extends AnnotationConfigEmbeddedWebApplicationContext { // // }
import com.whitney.product.ProductApplication; import com.whitney.queue.QueueApplication; import com.whitney.sales.SalesApplication; import com.whitney.support.SupportApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.SimpleCommandLinePropertySource; import java.util.Optional;
package com.whitney.parent; @Configuration public class Application { public static final String SPRING_PROFILES_ACTIVE = "lego.profiles.active"; public static final String DEFAULT_PROFILE = "local"; public static void main(String[] args) throws Exception { SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args); String profile = Optional.ofNullable(source.getProperty(SPRING_PROFILES_ACTIVE)).orElse(DEFAULT_PROFILE);
// Path: product-web/src/main/java/com/whitney/product/ProductApplication.java // @Configuration // @EnableAutoConfiguration // @EnableJms // @ComponentScan(value = { "com.whitney.product", "com.whitney.common" }) // public class ProductApplication extends AnnotationConfigEmbeddedWebApplicationContext { // // } // // Path: queue/src/main/java/com/whitney/queue/QueueApplication.java // @Configuration // @EnableAutoConfiguration(exclude = { WebMvcAutoConfiguration.class, LiquibaseAutoConfiguration.class, JpaRepositoriesAutoConfiguration.class, HibernateJpaAutoConfiguration.class }) // @ComponentScan(value = { "com.whitney.queue", "com.whitney.common" }) // public class QueueApplication extends AnnotationConfigApplicationContext { // // } // // Path: sales-web/src/main/java/com/whitney/sales/SalesApplication.java // @Configuration // @EnableAutoConfiguration // @EnableJms // @ComponentScan(value = { "com.whitney.sales", "com.whitney.common" }) // public class SalesApplication extends AnnotationConfigEmbeddedWebApplicationContext { // // } // // Path: support-web/src/main/java/com/whitney/support/SupportApplication.java // @Configuration // @EnableAutoConfiguration // @EnableJms // @ComponentScan(value = { "com.whitney.support", "com.whitney.common" }) // public class SupportApplication extends AnnotationConfigEmbeddedWebApplicationContext { // // } // Path: parent-web/src/main/java/com/whitney/parent/Application.java import com.whitney.product.ProductApplication; import com.whitney.queue.QueueApplication; import com.whitney.sales.SalesApplication; import com.whitney.support.SupportApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.SimpleCommandLinePropertySource; import java.util.Optional; package com.whitney.parent; @Configuration public class Application { public static final String SPRING_PROFILES_ACTIVE = "lego.profiles.active"; public static final String DEFAULT_PROFILE = "local"; public static void main(String[] args) throws Exception { SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args); String profile = Optional.ofNullable(source.getProperty(SPRING_PROFILES_ACTIVE)).orElse(DEFAULT_PROFILE);
start(SalesApplication.class).profiles(profile + ".sales").run(args);
timwhit/lego
parent-web/src/main/java/com/whitney/parent/Application.java
// Path: product-web/src/main/java/com/whitney/product/ProductApplication.java // @Configuration // @EnableAutoConfiguration // @EnableJms // @ComponentScan(value = { "com.whitney.product", "com.whitney.common" }) // public class ProductApplication extends AnnotationConfigEmbeddedWebApplicationContext { // // } // // Path: queue/src/main/java/com/whitney/queue/QueueApplication.java // @Configuration // @EnableAutoConfiguration(exclude = { WebMvcAutoConfiguration.class, LiquibaseAutoConfiguration.class, JpaRepositoriesAutoConfiguration.class, HibernateJpaAutoConfiguration.class }) // @ComponentScan(value = { "com.whitney.queue", "com.whitney.common" }) // public class QueueApplication extends AnnotationConfigApplicationContext { // // } // // Path: sales-web/src/main/java/com/whitney/sales/SalesApplication.java // @Configuration // @EnableAutoConfiguration // @EnableJms // @ComponentScan(value = { "com.whitney.sales", "com.whitney.common" }) // public class SalesApplication extends AnnotationConfigEmbeddedWebApplicationContext { // // } // // Path: support-web/src/main/java/com/whitney/support/SupportApplication.java // @Configuration // @EnableAutoConfiguration // @EnableJms // @ComponentScan(value = { "com.whitney.support", "com.whitney.common" }) // public class SupportApplication extends AnnotationConfigEmbeddedWebApplicationContext { // // }
import com.whitney.product.ProductApplication; import com.whitney.queue.QueueApplication; import com.whitney.sales.SalesApplication; import com.whitney.support.SupportApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.SimpleCommandLinePropertySource; import java.util.Optional;
package com.whitney.parent; @Configuration public class Application { public static final String SPRING_PROFILES_ACTIVE = "lego.profiles.active"; public static final String DEFAULT_PROFILE = "local"; public static void main(String[] args) throws Exception { SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args); String profile = Optional.ofNullable(source.getProperty(SPRING_PROFILES_ACTIVE)).orElse(DEFAULT_PROFILE); start(SalesApplication.class).profiles(profile + ".sales").run(args);
// Path: product-web/src/main/java/com/whitney/product/ProductApplication.java // @Configuration // @EnableAutoConfiguration // @EnableJms // @ComponentScan(value = { "com.whitney.product", "com.whitney.common" }) // public class ProductApplication extends AnnotationConfigEmbeddedWebApplicationContext { // // } // // Path: queue/src/main/java/com/whitney/queue/QueueApplication.java // @Configuration // @EnableAutoConfiguration(exclude = { WebMvcAutoConfiguration.class, LiquibaseAutoConfiguration.class, JpaRepositoriesAutoConfiguration.class, HibernateJpaAutoConfiguration.class }) // @ComponentScan(value = { "com.whitney.queue", "com.whitney.common" }) // public class QueueApplication extends AnnotationConfigApplicationContext { // // } // // Path: sales-web/src/main/java/com/whitney/sales/SalesApplication.java // @Configuration // @EnableAutoConfiguration // @EnableJms // @ComponentScan(value = { "com.whitney.sales", "com.whitney.common" }) // public class SalesApplication extends AnnotationConfigEmbeddedWebApplicationContext { // // } // // Path: support-web/src/main/java/com/whitney/support/SupportApplication.java // @Configuration // @EnableAutoConfiguration // @EnableJms // @ComponentScan(value = { "com.whitney.support", "com.whitney.common" }) // public class SupportApplication extends AnnotationConfigEmbeddedWebApplicationContext { // // } // Path: parent-web/src/main/java/com/whitney/parent/Application.java import com.whitney.product.ProductApplication; import com.whitney.queue.QueueApplication; import com.whitney.sales.SalesApplication; import com.whitney.support.SupportApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.SimpleCommandLinePropertySource; import java.util.Optional; package com.whitney.parent; @Configuration public class Application { public static final String SPRING_PROFILES_ACTIVE = "lego.profiles.active"; public static final String DEFAULT_PROFILE = "local"; public static void main(String[] args) throws Exception { SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args); String profile = Optional.ofNullable(source.getProperty(SPRING_PROFILES_ACTIVE)).orElse(DEFAULT_PROFILE); start(SalesApplication.class).profiles(profile + ".sales").run(args);
start(SupportApplication.class).profiles(profile + ".support").run(args);
timwhit/lego
parent-web/src/main/java/com/whitney/parent/Application.java
// Path: product-web/src/main/java/com/whitney/product/ProductApplication.java // @Configuration // @EnableAutoConfiguration // @EnableJms // @ComponentScan(value = { "com.whitney.product", "com.whitney.common" }) // public class ProductApplication extends AnnotationConfigEmbeddedWebApplicationContext { // // } // // Path: queue/src/main/java/com/whitney/queue/QueueApplication.java // @Configuration // @EnableAutoConfiguration(exclude = { WebMvcAutoConfiguration.class, LiquibaseAutoConfiguration.class, JpaRepositoriesAutoConfiguration.class, HibernateJpaAutoConfiguration.class }) // @ComponentScan(value = { "com.whitney.queue", "com.whitney.common" }) // public class QueueApplication extends AnnotationConfigApplicationContext { // // } // // Path: sales-web/src/main/java/com/whitney/sales/SalesApplication.java // @Configuration // @EnableAutoConfiguration // @EnableJms // @ComponentScan(value = { "com.whitney.sales", "com.whitney.common" }) // public class SalesApplication extends AnnotationConfigEmbeddedWebApplicationContext { // // } // // Path: support-web/src/main/java/com/whitney/support/SupportApplication.java // @Configuration // @EnableAutoConfiguration // @EnableJms // @ComponentScan(value = { "com.whitney.support", "com.whitney.common" }) // public class SupportApplication extends AnnotationConfigEmbeddedWebApplicationContext { // // }
import com.whitney.product.ProductApplication; import com.whitney.queue.QueueApplication; import com.whitney.sales.SalesApplication; import com.whitney.support.SupportApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.SimpleCommandLinePropertySource; import java.util.Optional;
package com.whitney.parent; @Configuration public class Application { public static final String SPRING_PROFILES_ACTIVE = "lego.profiles.active"; public static final String DEFAULT_PROFILE = "local"; public static void main(String[] args) throws Exception { SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args); String profile = Optional.ofNullable(source.getProperty(SPRING_PROFILES_ACTIVE)).orElse(DEFAULT_PROFILE); start(SalesApplication.class).profiles(profile + ".sales").run(args); start(SupportApplication.class).profiles(profile + ".support").run(args);
// Path: product-web/src/main/java/com/whitney/product/ProductApplication.java // @Configuration // @EnableAutoConfiguration // @EnableJms // @ComponentScan(value = { "com.whitney.product", "com.whitney.common" }) // public class ProductApplication extends AnnotationConfigEmbeddedWebApplicationContext { // // } // // Path: queue/src/main/java/com/whitney/queue/QueueApplication.java // @Configuration // @EnableAutoConfiguration(exclude = { WebMvcAutoConfiguration.class, LiquibaseAutoConfiguration.class, JpaRepositoriesAutoConfiguration.class, HibernateJpaAutoConfiguration.class }) // @ComponentScan(value = { "com.whitney.queue", "com.whitney.common" }) // public class QueueApplication extends AnnotationConfigApplicationContext { // // } // // Path: sales-web/src/main/java/com/whitney/sales/SalesApplication.java // @Configuration // @EnableAutoConfiguration // @EnableJms // @ComponentScan(value = { "com.whitney.sales", "com.whitney.common" }) // public class SalesApplication extends AnnotationConfigEmbeddedWebApplicationContext { // // } // // Path: support-web/src/main/java/com/whitney/support/SupportApplication.java // @Configuration // @EnableAutoConfiguration // @EnableJms // @ComponentScan(value = { "com.whitney.support", "com.whitney.common" }) // public class SupportApplication extends AnnotationConfigEmbeddedWebApplicationContext { // // } // Path: parent-web/src/main/java/com/whitney/parent/Application.java import com.whitney.product.ProductApplication; import com.whitney.queue.QueueApplication; import com.whitney.sales.SalesApplication; import com.whitney.support.SupportApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.SimpleCommandLinePropertySource; import java.util.Optional; package com.whitney.parent; @Configuration public class Application { public static final String SPRING_PROFILES_ACTIVE = "lego.profiles.active"; public static final String DEFAULT_PROFILE = "local"; public static void main(String[] args) throws Exception { SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args); String profile = Optional.ofNullable(source.getProperty(SPRING_PROFILES_ACTIVE)).orElse(DEFAULT_PROFILE); start(SalesApplication.class).profiles(profile + ".sales").run(args); start(SupportApplication.class).profiles(profile + ".support").run(args);
start(ProductApplication.class).profiles(profile + ".product").run(args);
timwhit/lego
parent-web/src/main/java/com/whitney/parent/Application.java
// Path: product-web/src/main/java/com/whitney/product/ProductApplication.java // @Configuration // @EnableAutoConfiguration // @EnableJms // @ComponentScan(value = { "com.whitney.product", "com.whitney.common" }) // public class ProductApplication extends AnnotationConfigEmbeddedWebApplicationContext { // // } // // Path: queue/src/main/java/com/whitney/queue/QueueApplication.java // @Configuration // @EnableAutoConfiguration(exclude = { WebMvcAutoConfiguration.class, LiquibaseAutoConfiguration.class, JpaRepositoriesAutoConfiguration.class, HibernateJpaAutoConfiguration.class }) // @ComponentScan(value = { "com.whitney.queue", "com.whitney.common" }) // public class QueueApplication extends AnnotationConfigApplicationContext { // // } // // Path: sales-web/src/main/java/com/whitney/sales/SalesApplication.java // @Configuration // @EnableAutoConfiguration // @EnableJms // @ComponentScan(value = { "com.whitney.sales", "com.whitney.common" }) // public class SalesApplication extends AnnotationConfigEmbeddedWebApplicationContext { // // } // // Path: support-web/src/main/java/com/whitney/support/SupportApplication.java // @Configuration // @EnableAutoConfiguration // @EnableJms // @ComponentScan(value = { "com.whitney.support", "com.whitney.common" }) // public class SupportApplication extends AnnotationConfigEmbeddedWebApplicationContext { // // }
import com.whitney.product.ProductApplication; import com.whitney.queue.QueueApplication; import com.whitney.sales.SalesApplication; import com.whitney.support.SupportApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.SimpleCommandLinePropertySource; import java.util.Optional;
package com.whitney.parent; @Configuration public class Application { public static final String SPRING_PROFILES_ACTIVE = "lego.profiles.active"; public static final String DEFAULT_PROFILE = "local"; public static void main(String[] args) throws Exception { SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args); String profile = Optional.ofNullable(source.getProperty(SPRING_PROFILES_ACTIVE)).orElse(DEFAULT_PROFILE); start(SalesApplication.class).profiles(profile + ".sales").run(args); start(SupportApplication.class).profiles(profile + ".support").run(args); start(ProductApplication.class).profiles(profile + ".product").run(args);
// Path: product-web/src/main/java/com/whitney/product/ProductApplication.java // @Configuration // @EnableAutoConfiguration // @EnableJms // @ComponentScan(value = { "com.whitney.product", "com.whitney.common" }) // public class ProductApplication extends AnnotationConfigEmbeddedWebApplicationContext { // // } // // Path: queue/src/main/java/com/whitney/queue/QueueApplication.java // @Configuration // @EnableAutoConfiguration(exclude = { WebMvcAutoConfiguration.class, LiquibaseAutoConfiguration.class, JpaRepositoriesAutoConfiguration.class, HibernateJpaAutoConfiguration.class }) // @ComponentScan(value = { "com.whitney.queue", "com.whitney.common" }) // public class QueueApplication extends AnnotationConfigApplicationContext { // // } // // Path: sales-web/src/main/java/com/whitney/sales/SalesApplication.java // @Configuration // @EnableAutoConfiguration // @EnableJms // @ComponentScan(value = { "com.whitney.sales", "com.whitney.common" }) // public class SalesApplication extends AnnotationConfigEmbeddedWebApplicationContext { // // } // // Path: support-web/src/main/java/com/whitney/support/SupportApplication.java // @Configuration // @EnableAutoConfiguration // @EnableJms // @ComponentScan(value = { "com.whitney.support", "com.whitney.common" }) // public class SupportApplication extends AnnotationConfigEmbeddedWebApplicationContext { // // } // Path: parent-web/src/main/java/com/whitney/parent/Application.java import com.whitney.product.ProductApplication; import com.whitney.queue.QueueApplication; import com.whitney.sales.SalesApplication; import com.whitney.support.SupportApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.SimpleCommandLinePropertySource; import java.util.Optional; package com.whitney.parent; @Configuration public class Application { public static final String SPRING_PROFILES_ACTIVE = "lego.profiles.active"; public static final String DEFAULT_PROFILE = "local"; public static void main(String[] args) throws Exception { SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args); String profile = Optional.ofNullable(source.getProperty(SPRING_PROFILES_ACTIVE)).orElse(DEFAULT_PROFILE); start(SalesApplication.class).profiles(profile + ".sales").run(args); start(SupportApplication.class).profiles(profile + ".support").run(args); start(ProductApplication.class).profiles(profile + ".product").run(args);
start(QueueApplication.class).profiles(profile + ".queue").web(false).run(args);
timwhit/lego
support-web/src/main/java/com/whitney/support/web/controller/SupportController.java
// Path: common/src/main/java/com/whitney/common/util/MapperUtils.java // @Service // public class MapperUtils extends ModelMapper { // public MapperUtils() { // this.getConfiguration().setFieldMatchingEnabled(true).setFieldAccessLevel(org.modelmapper.config.Configuration.AccessLevel.PRIVATE); // } // } // // Path: support-service/src/main/java/com/whitney/support/domain/Support.java // public class Support { // private Long id; // private Long salesId; // private Long productId; // private Long userId; // private String description; // // public Support() {} // // public Support(Long id, Long salesId, Long productId, Long userId, String description) { // this.id = id; // this.salesId = salesId; // this.productId = productId; // this.userId = userId; // this.description = description; // } // // public Long getId() { // return id; // } // // public Long getSalesId() { // return salesId; // } // // public Long getProductId() { // return productId; // } // // public Long getUserId() { // return userId; // } // // public String getDescription() { // return description; // } // } // // Path: support-service/src/main/java/com/whitney/support/service/SupportService.java // public interface SupportService { // Support get(Long id); // // Support create(Support support); // } // // Path: support-web/src/main/java/com/whitney/support/web/vo/SupportVO.java // public class SupportVO { // private Long id; // private Long salesId; // private Long productId; // private Long userId; // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getSalesId() { // return salesId; // } // // public void setSalesId(Long salesId) { // this.salesId = salesId; // } // // public Long getProductId() { // return productId; // } // // public void setProductId(Long productId) { // this.productId = productId; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // }
import com.whitney.common.util.MapperUtils; import com.whitney.support.domain.Support; import com.whitney.support.service.SupportService; import com.whitney.support.web.vo.SupportVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*;
package com.whitney.support.web.controller; @RestController @RequestMapping("/rest/support") public class SupportController { @Autowired
// Path: common/src/main/java/com/whitney/common/util/MapperUtils.java // @Service // public class MapperUtils extends ModelMapper { // public MapperUtils() { // this.getConfiguration().setFieldMatchingEnabled(true).setFieldAccessLevel(org.modelmapper.config.Configuration.AccessLevel.PRIVATE); // } // } // // Path: support-service/src/main/java/com/whitney/support/domain/Support.java // public class Support { // private Long id; // private Long salesId; // private Long productId; // private Long userId; // private String description; // // public Support() {} // // public Support(Long id, Long salesId, Long productId, Long userId, String description) { // this.id = id; // this.salesId = salesId; // this.productId = productId; // this.userId = userId; // this.description = description; // } // // public Long getId() { // return id; // } // // public Long getSalesId() { // return salesId; // } // // public Long getProductId() { // return productId; // } // // public Long getUserId() { // return userId; // } // // public String getDescription() { // return description; // } // } // // Path: support-service/src/main/java/com/whitney/support/service/SupportService.java // public interface SupportService { // Support get(Long id); // // Support create(Support support); // } // // Path: support-web/src/main/java/com/whitney/support/web/vo/SupportVO.java // public class SupportVO { // private Long id; // private Long salesId; // private Long productId; // private Long userId; // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getSalesId() { // return salesId; // } // // public void setSalesId(Long salesId) { // this.salesId = salesId; // } // // public Long getProductId() { // return productId; // } // // public void setProductId(Long productId) { // this.productId = productId; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // Path: support-web/src/main/java/com/whitney/support/web/controller/SupportController.java import com.whitney.common.util.MapperUtils; import com.whitney.support.domain.Support; import com.whitney.support.service.SupportService; import com.whitney.support.web.vo.SupportVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; package com.whitney.support.web.controller; @RestController @RequestMapping("/rest/support") public class SupportController { @Autowired
private SupportService supportService;
timwhit/lego
support-web/src/main/java/com/whitney/support/web/controller/SupportController.java
// Path: common/src/main/java/com/whitney/common/util/MapperUtils.java // @Service // public class MapperUtils extends ModelMapper { // public MapperUtils() { // this.getConfiguration().setFieldMatchingEnabled(true).setFieldAccessLevel(org.modelmapper.config.Configuration.AccessLevel.PRIVATE); // } // } // // Path: support-service/src/main/java/com/whitney/support/domain/Support.java // public class Support { // private Long id; // private Long salesId; // private Long productId; // private Long userId; // private String description; // // public Support() {} // // public Support(Long id, Long salesId, Long productId, Long userId, String description) { // this.id = id; // this.salesId = salesId; // this.productId = productId; // this.userId = userId; // this.description = description; // } // // public Long getId() { // return id; // } // // public Long getSalesId() { // return salesId; // } // // public Long getProductId() { // return productId; // } // // public Long getUserId() { // return userId; // } // // public String getDescription() { // return description; // } // } // // Path: support-service/src/main/java/com/whitney/support/service/SupportService.java // public interface SupportService { // Support get(Long id); // // Support create(Support support); // } // // Path: support-web/src/main/java/com/whitney/support/web/vo/SupportVO.java // public class SupportVO { // private Long id; // private Long salesId; // private Long productId; // private Long userId; // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getSalesId() { // return salesId; // } // // public void setSalesId(Long salesId) { // this.salesId = salesId; // } // // public Long getProductId() { // return productId; // } // // public void setProductId(Long productId) { // this.productId = productId; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // }
import com.whitney.common.util.MapperUtils; import com.whitney.support.domain.Support; import com.whitney.support.service.SupportService; import com.whitney.support.web.vo.SupportVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*;
package com.whitney.support.web.controller; @RestController @RequestMapping("/rest/support") public class SupportController { @Autowired private SupportService supportService; @Autowired
// Path: common/src/main/java/com/whitney/common/util/MapperUtils.java // @Service // public class MapperUtils extends ModelMapper { // public MapperUtils() { // this.getConfiguration().setFieldMatchingEnabled(true).setFieldAccessLevel(org.modelmapper.config.Configuration.AccessLevel.PRIVATE); // } // } // // Path: support-service/src/main/java/com/whitney/support/domain/Support.java // public class Support { // private Long id; // private Long salesId; // private Long productId; // private Long userId; // private String description; // // public Support() {} // // public Support(Long id, Long salesId, Long productId, Long userId, String description) { // this.id = id; // this.salesId = salesId; // this.productId = productId; // this.userId = userId; // this.description = description; // } // // public Long getId() { // return id; // } // // public Long getSalesId() { // return salesId; // } // // public Long getProductId() { // return productId; // } // // public Long getUserId() { // return userId; // } // // public String getDescription() { // return description; // } // } // // Path: support-service/src/main/java/com/whitney/support/service/SupportService.java // public interface SupportService { // Support get(Long id); // // Support create(Support support); // } // // Path: support-web/src/main/java/com/whitney/support/web/vo/SupportVO.java // public class SupportVO { // private Long id; // private Long salesId; // private Long productId; // private Long userId; // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getSalesId() { // return salesId; // } // // public void setSalesId(Long salesId) { // this.salesId = salesId; // } // // public Long getProductId() { // return productId; // } // // public void setProductId(Long productId) { // this.productId = productId; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // Path: support-web/src/main/java/com/whitney/support/web/controller/SupportController.java import com.whitney.common.util.MapperUtils; import com.whitney.support.domain.Support; import com.whitney.support.service.SupportService; import com.whitney.support.web.vo.SupportVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; package com.whitney.support.web.controller; @RestController @RequestMapping("/rest/support") public class SupportController { @Autowired private SupportService supportService; @Autowired
private MapperUtils mapper;
timwhit/lego
support-web/src/main/java/com/whitney/support/web/controller/SupportController.java
// Path: common/src/main/java/com/whitney/common/util/MapperUtils.java // @Service // public class MapperUtils extends ModelMapper { // public MapperUtils() { // this.getConfiguration().setFieldMatchingEnabled(true).setFieldAccessLevel(org.modelmapper.config.Configuration.AccessLevel.PRIVATE); // } // } // // Path: support-service/src/main/java/com/whitney/support/domain/Support.java // public class Support { // private Long id; // private Long salesId; // private Long productId; // private Long userId; // private String description; // // public Support() {} // // public Support(Long id, Long salesId, Long productId, Long userId, String description) { // this.id = id; // this.salesId = salesId; // this.productId = productId; // this.userId = userId; // this.description = description; // } // // public Long getId() { // return id; // } // // public Long getSalesId() { // return salesId; // } // // public Long getProductId() { // return productId; // } // // public Long getUserId() { // return userId; // } // // public String getDescription() { // return description; // } // } // // Path: support-service/src/main/java/com/whitney/support/service/SupportService.java // public interface SupportService { // Support get(Long id); // // Support create(Support support); // } // // Path: support-web/src/main/java/com/whitney/support/web/vo/SupportVO.java // public class SupportVO { // private Long id; // private Long salesId; // private Long productId; // private Long userId; // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getSalesId() { // return salesId; // } // // public void setSalesId(Long salesId) { // this.salesId = salesId; // } // // public Long getProductId() { // return productId; // } // // public void setProductId(Long productId) { // this.productId = productId; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // }
import com.whitney.common.util.MapperUtils; import com.whitney.support.domain.Support; import com.whitney.support.service.SupportService; import com.whitney.support.web.vo.SupportVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*;
package com.whitney.support.web.controller; @RestController @RequestMapping("/rest/support") public class SupportController { @Autowired private SupportService supportService; @Autowired private MapperUtils mapper; @RequestMapping(value = "/{supportId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
// Path: common/src/main/java/com/whitney/common/util/MapperUtils.java // @Service // public class MapperUtils extends ModelMapper { // public MapperUtils() { // this.getConfiguration().setFieldMatchingEnabled(true).setFieldAccessLevel(org.modelmapper.config.Configuration.AccessLevel.PRIVATE); // } // } // // Path: support-service/src/main/java/com/whitney/support/domain/Support.java // public class Support { // private Long id; // private Long salesId; // private Long productId; // private Long userId; // private String description; // // public Support() {} // // public Support(Long id, Long salesId, Long productId, Long userId, String description) { // this.id = id; // this.salesId = salesId; // this.productId = productId; // this.userId = userId; // this.description = description; // } // // public Long getId() { // return id; // } // // public Long getSalesId() { // return salesId; // } // // public Long getProductId() { // return productId; // } // // public Long getUserId() { // return userId; // } // // public String getDescription() { // return description; // } // } // // Path: support-service/src/main/java/com/whitney/support/service/SupportService.java // public interface SupportService { // Support get(Long id); // // Support create(Support support); // } // // Path: support-web/src/main/java/com/whitney/support/web/vo/SupportVO.java // public class SupportVO { // private Long id; // private Long salesId; // private Long productId; // private Long userId; // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getSalesId() { // return salesId; // } // // public void setSalesId(Long salesId) { // this.salesId = salesId; // } // // public Long getProductId() { // return productId; // } // // public void setProductId(Long productId) { // this.productId = productId; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // Path: support-web/src/main/java/com/whitney/support/web/controller/SupportController.java import com.whitney.common.util.MapperUtils; import com.whitney.support.domain.Support; import com.whitney.support.service.SupportService; import com.whitney.support.web.vo.SupportVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; package com.whitney.support.web.controller; @RestController @RequestMapping("/rest/support") public class SupportController { @Autowired private SupportService supportService; @Autowired private MapperUtils mapper; @RequestMapping(value = "/{supportId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public SupportVO get(@PathVariable Long supportId) {
timwhit/lego
support-web/src/main/java/com/whitney/support/web/controller/SupportController.java
// Path: common/src/main/java/com/whitney/common/util/MapperUtils.java // @Service // public class MapperUtils extends ModelMapper { // public MapperUtils() { // this.getConfiguration().setFieldMatchingEnabled(true).setFieldAccessLevel(org.modelmapper.config.Configuration.AccessLevel.PRIVATE); // } // } // // Path: support-service/src/main/java/com/whitney/support/domain/Support.java // public class Support { // private Long id; // private Long salesId; // private Long productId; // private Long userId; // private String description; // // public Support() {} // // public Support(Long id, Long salesId, Long productId, Long userId, String description) { // this.id = id; // this.salesId = salesId; // this.productId = productId; // this.userId = userId; // this.description = description; // } // // public Long getId() { // return id; // } // // public Long getSalesId() { // return salesId; // } // // public Long getProductId() { // return productId; // } // // public Long getUserId() { // return userId; // } // // public String getDescription() { // return description; // } // } // // Path: support-service/src/main/java/com/whitney/support/service/SupportService.java // public interface SupportService { // Support get(Long id); // // Support create(Support support); // } // // Path: support-web/src/main/java/com/whitney/support/web/vo/SupportVO.java // public class SupportVO { // private Long id; // private Long salesId; // private Long productId; // private Long userId; // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getSalesId() { // return salesId; // } // // public void setSalesId(Long salesId) { // this.salesId = salesId; // } // // public Long getProductId() { // return productId; // } // // public void setProductId(Long productId) { // this.productId = productId; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // }
import com.whitney.common.util.MapperUtils; import com.whitney.support.domain.Support; import com.whitney.support.service.SupportService; import com.whitney.support.web.vo.SupportVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*;
package com.whitney.support.web.controller; @RestController @RequestMapping("/rest/support") public class SupportController { @Autowired private SupportService supportService; @Autowired private MapperUtils mapper; @RequestMapping(value = "/{supportId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public SupportVO get(@PathVariable Long supportId) { return this.mapper.map(this.supportService.get(supportId), SupportVO.class); } @RequestMapping(value = "/", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) public SupportVO create(@RequestBody SupportVO support) {
// Path: common/src/main/java/com/whitney/common/util/MapperUtils.java // @Service // public class MapperUtils extends ModelMapper { // public MapperUtils() { // this.getConfiguration().setFieldMatchingEnabled(true).setFieldAccessLevel(org.modelmapper.config.Configuration.AccessLevel.PRIVATE); // } // } // // Path: support-service/src/main/java/com/whitney/support/domain/Support.java // public class Support { // private Long id; // private Long salesId; // private Long productId; // private Long userId; // private String description; // // public Support() {} // // public Support(Long id, Long salesId, Long productId, Long userId, String description) { // this.id = id; // this.salesId = salesId; // this.productId = productId; // this.userId = userId; // this.description = description; // } // // public Long getId() { // return id; // } // // public Long getSalesId() { // return salesId; // } // // public Long getProductId() { // return productId; // } // // public Long getUserId() { // return userId; // } // // public String getDescription() { // return description; // } // } // // Path: support-service/src/main/java/com/whitney/support/service/SupportService.java // public interface SupportService { // Support get(Long id); // // Support create(Support support); // } // // Path: support-web/src/main/java/com/whitney/support/web/vo/SupportVO.java // public class SupportVO { // private Long id; // private Long salesId; // private Long productId; // private Long userId; // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getSalesId() { // return salesId; // } // // public void setSalesId(Long salesId) { // this.salesId = salesId; // } // // public Long getProductId() { // return productId; // } // // public void setProductId(Long productId) { // this.productId = productId; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // Path: support-web/src/main/java/com/whitney/support/web/controller/SupportController.java import com.whitney.common.util.MapperUtils; import com.whitney.support.domain.Support; import com.whitney.support.service.SupportService; import com.whitney.support.web.vo.SupportVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; package com.whitney.support.web.controller; @RestController @RequestMapping("/rest/support") public class SupportController { @Autowired private SupportService supportService; @Autowired private MapperUtils mapper; @RequestMapping(value = "/{supportId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public SupportVO get(@PathVariable Long supportId) { return this.mapper.map(this.supportService.get(supportId), SupportVO.class); } @RequestMapping(value = "/", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) public SupportVO create(@RequestBody SupportVO support) {
Support createdSupport = this.supportService.create(this.mapper.map(support, Support.class));
timwhit/lego
support-data-impl/src/main/java/com/whitney/support/data/dao/SalesDAOImpl.java
// Path: support-data/src/main/java/com/whitney/support/data/dto/SaleDTO.java // public class SaleDTO { // private Long id; // private Long productId; // private Long userId; // private Integer quantity; // private BigDecimal amount; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProductId() { // return productId; // } // // public void setProductId(Long productId) { // this.productId = productId; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public Integer getQuantity() { // return quantity; // } // // public void setQuantity(Integer quantity) { // this.quantity = quantity; // } // // public BigDecimal getAmount() { // return amount; // } // // public void setAmount(BigDecimal amount) { // this.amount = amount; // } // }
import com.whitney.support.data.dto.SaleDTO; import org.springframework.stereotype.Repository; import org.springframework.web.client.RestTemplate;
package com.whitney.support.data.dao; @Repository public class SalesDAOImpl implements SalesDAO { private static final String URI = "http://localhost:8081/rest/sales/{id}"; @Override
// Path: support-data/src/main/java/com/whitney/support/data/dto/SaleDTO.java // public class SaleDTO { // private Long id; // private Long productId; // private Long userId; // private Integer quantity; // private BigDecimal amount; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProductId() { // return productId; // } // // public void setProductId(Long productId) { // this.productId = productId; // } // // public Long getUserId() { // return userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // public Integer getQuantity() { // return quantity; // } // // public void setQuantity(Integer quantity) { // this.quantity = quantity; // } // // public BigDecimal getAmount() { // return amount; // } // // public void setAmount(BigDecimal amount) { // this.amount = amount; // } // } // Path: support-data-impl/src/main/java/com/whitney/support/data/dao/SalesDAOImpl.java import com.whitney.support.data.dto.SaleDTO; import org.springframework.stereotype.Repository; import org.springframework.web.client.RestTemplate; package com.whitney.support.data.dao; @Repository public class SalesDAOImpl implements SalesDAO { private static final String URI = "http://localhost:8081/rest/sales/{id}"; @Override
public SaleDTO findById(Long salesId) {
santiago-hollmann/sample-events
app/src/main/java/com/shollmann/events/api/model/CropMask.java
// Path: app/src/main/java/com/shollmann/events/api/model/TopLeft.java // public class TopLeft { // // @SerializedName("x") // @Expose // private Integer x; // @SerializedName("y") // @Expose // private Integer y; // // public Integer getX() { // return x; // } // // public void setX(Integer x) { // this.x = x; // } // // public Integer getY() { // return y; // } // // public void setY(Integer y) { // this.y = y; // } // // }
import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import com.shollmann.TopLeft;
package com.shollmann.events.api.model; public class CropMask { @SerializedName("top_left") @Expose
// Path: app/src/main/java/com/shollmann/events/api/model/TopLeft.java // public class TopLeft { // // @SerializedName("x") // @Expose // private Integer x; // @SerializedName("y") // @Expose // private Integer y; // // public Integer getX() { // return x; // } // // public void setX(Integer x) { // this.x = x; // } // // public Integer getY() { // return y; // } // // public void setY(Integer y) { // this.y = y; // } // // } // Path: app/src/main/java/com/shollmann/events/api/model/CropMask.java import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import com.shollmann.TopLeft; package com.shollmann.events.api.model; public class CropMask { @SerializedName("top_left") @Expose
private TopLeft topLeft;
santiago-hollmann/sample-events
app/src/main/java/com/shollmann/events/db/DbItem.java
// Path: app/src/main/java/com/shollmann/events/helper/DateUtils.java // public class DateUtils { // // private static final int MILLISECONDS_IN_A_DAY = 1000 * 60 * 60 * 24; // private static final int MILLISECONDS_IN_A_MINUTE = 1000 * 60; // // private static long getMillisForDate(java.util.Date date) { // return date.getTime(); // } // // public static int getDifferenceInDays(java.util.Date firstDate, java.util.Date secondDate) { // return getDifferenceInDays(firstDate.getTime(), secondDate.getTime()); // } // // private static int getDifferenceInDays(long firstDate, long secondDate) { // return Math.round((firstDate - secondDate) / MILLISECONDS_IN_A_DAY); // } // // private static int getDifferenceInMinutes(long firstDate, long secondDate) { // return Math.round((firstDate - secondDate) / MILLISECONDS_IN_A_MINUTE); // } // // public static String getDateFormatted(java.util.Date date, String format) { // SimpleDateFormat dateFormat = new SimpleDateFormat(format); // return dateFormat.format(date); // } // // public static int diffSeconds(long d1, long d2) { // long diff = Math.abs(d1 - d2); // diff = diff / (1000); // return (int) diff; // } // // public static int diffSeconds(long d1) { // return diffSeconds(System.currentTimeMillis(), d1); // } // // public static String formatDateTimeToDDMMYYYY(java.util.Date date) { // SimpleDateFormat dt = new SimpleDateFormat("dd/MM/yyyy"); // return dt.format(date.getTime()); // } // // public static String getCurrentMMYYYY() { // SimpleDateFormat dt = new SimpleDateFormat("MM/yyyy"); // return dt.format(Calendar.getInstance().getTime()); // } // // public static String formatTimeSpan(long seconds) { // // final DecimalFormat f = new DecimalFormat("0.#"); // // if (seconds >= 86400) { // 86400 = 60 * 60 * 24 = 1 day // return f.format(seconds / 86400.) + "d"; // } else if (seconds >= 3600) { // 3600 = 60 * 60 = 1 hour // return f.format(seconds / 3600.) + "h"; // } else if (seconds >= 60) { // 60 = 1 minute // return f.format(seconds / 60.) + "m"; // } else { // return seconds + "s"; // } // } // // public static String getEventDate(String dateNaiveIso8601) { // try { // Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(dateNaiveIso8601); // SimpleDateFormat formatter = new SimpleDateFormat("EEE, MMM d, ''yy"); // return formatter.format(date); // } catch (ParseException e) { // return Constants.EMPTY_STRING; // } // } // }
import com.shollmann.events.helper.DateUtils;
package com.shollmann.events.db; public class DbItem<T> { private T object; private long date; public DbItem(T object, long date) { this.object = object; this.date = date; } public T getObject() { return object; } public boolean isExpired(long ttl) {
// Path: app/src/main/java/com/shollmann/events/helper/DateUtils.java // public class DateUtils { // // private static final int MILLISECONDS_IN_A_DAY = 1000 * 60 * 60 * 24; // private static final int MILLISECONDS_IN_A_MINUTE = 1000 * 60; // // private static long getMillisForDate(java.util.Date date) { // return date.getTime(); // } // // public static int getDifferenceInDays(java.util.Date firstDate, java.util.Date secondDate) { // return getDifferenceInDays(firstDate.getTime(), secondDate.getTime()); // } // // private static int getDifferenceInDays(long firstDate, long secondDate) { // return Math.round((firstDate - secondDate) / MILLISECONDS_IN_A_DAY); // } // // private static int getDifferenceInMinutes(long firstDate, long secondDate) { // return Math.round((firstDate - secondDate) / MILLISECONDS_IN_A_MINUTE); // } // // public static String getDateFormatted(java.util.Date date, String format) { // SimpleDateFormat dateFormat = new SimpleDateFormat(format); // return dateFormat.format(date); // } // // public static int diffSeconds(long d1, long d2) { // long diff = Math.abs(d1 - d2); // diff = diff / (1000); // return (int) diff; // } // // public static int diffSeconds(long d1) { // return diffSeconds(System.currentTimeMillis(), d1); // } // // public static String formatDateTimeToDDMMYYYY(java.util.Date date) { // SimpleDateFormat dt = new SimpleDateFormat("dd/MM/yyyy"); // return dt.format(date.getTime()); // } // // public static String getCurrentMMYYYY() { // SimpleDateFormat dt = new SimpleDateFormat("MM/yyyy"); // return dt.format(Calendar.getInstance().getTime()); // } // // public static String formatTimeSpan(long seconds) { // // final DecimalFormat f = new DecimalFormat("0.#"); // // if (seconds >= 86400) { // 86400 = 60 * 60 * 24 = 1 day // return f.format(seconds / 86400.) + "d"; // } else if (seconds >= 3600) { // 3600 = 60 * 60 = 1 hour // return f.format(seconds / 3600.) + "h"; // } else if (seconds >= 60) { // 60 = 1 minute // return f.format(seconds / 60.) + "m"; // } else { // return seconds + "s"; // } // } // // public static String getEventDate(String dateNaiveIso8601) { // try { // Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(dateNaiveIso8601); // SimpleDateFormat formatter = new SimpleDateFormat("EEE, MMM d, ''yy"); // return formatter.format(date); // } catch (ParseException e) { // return Constants.EMPTY_STRING; // } // } // } // Path: app/src/main/java/com/shollmann/events/db/DbItem.java import com.shollmann.events.helper.DateUtils; package com.shollmann.events.db; public class DbItem<T> { private T object; private long date; public DbItem(T object, long date) { this.object = object; this.date = date; } public T getObject() { return object; } public boolean isExpired(long ttl) {
int seconds = DateUtils.diffSeconds(date);
santiago-hollmann/sample-events
app/src/main/java/com/shollmann/events/helper/PreferencesHelper.java
// Path: app/src/main/java/com/shollmann/events/ui/EventbriteApplication.java // public class EventbriteApplication extends Application { // private static EventbriteApplication instance; // private CachingDbHelper cachingDbHelper; // private EventbriteApi apiEventbrite; // // public static EventbriteApplication getApplication() { // return instance; // } // // @Override // public void onCreate() { // super.onCreate(); // this.instance = this; // this.apiEventbrite = (EventbriteApi) new EventbriteApi.Builder() // .baseUrl(Constants.EventbriteApi.URL) // .contract(EventbriteApiContract.class) // .build(); // this.cachingDbHelper = new CachingDbHelper(getApplicationContext()); // } // // public CachingDbHelper getCachingDbHelper() { // return cachingDbHelper; // } // // public EventbriteApi getApiEventbrite() { // return apiEventbrite; // } // }
import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.google.gson.Gson; import com.shollmann.events.ui.EventbriteApplication;
package com.shollmann.events.helper; public class PreferencesHelper { private final static Gson gson = new Gson(); private static final String LAST_SEARCH = "last_search"; static {
// Path: app/src/main/java/com/shollmann/events/ui/EventbriteApplication.java // public class EventbriteApplication extends Application { // private static EventbriteApplication instance; // private CachingDbHelper cachingDbHelper; // private EventbriteApi apiEventbrite; // // public static EventbriteApplication getApplication() { // return instance; // } // // @Override // public void onCreate() { // super.onCreate(); // this.instance = this; // this.apiEventbrite = (EventbriteApi) new EventbriteApi.Builder() // .baseUrl(Constants.EventbriteApi.URL) // .contract(EventbriteApiContract.class) // .build(); // this.cachingDbHelper = new CachingDbHelper(getApplicationContext()); // } // // public CachingDbHelper getCachingDbHelper() { // return cachingDbHelper; // } // // public EventbriteApi getApiEventbrite() { // return apiEventbrite; // } // } // Path: app/src/main/java/com/shollmann/events/helper/PreferencesHelper.java import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.google.gson.Gson; import com.shollmann.events.ui.EventbriteApplication; package com.shollmann.events.helper; public class PreferencesHelper { private final static Gson gson = new Gson(); private static final String LAST_SEARCH = "last_search"; static {
prefs = PreferenceManager.getDefaultSharedPreferences(EventbriteApplication.getApplication());
santiago-hollmann/sample-events
app/src/main/java/com/shollmann/events/helper/ResourcesHelper.java
// Path: app/src/main/java/com/shollmann/events/ui/EventbriteApplication.java // public class EventbriteApplication extends Application { // private static EventbriteApplication instance; // private CachingDbHelper cachingDbHelper; // private EventbriteApi apiEventbrite; // // public static EventbriteApplication getApplication() { // return instance; // } // // @Override // public void onCreate() { // super.onCreate(); // this.instance = this; // this.apiEventbrite = (EventbriteApi) new EventbriteApi.Builder() // .baseUrl(Constants.EventbriteApi.URL) // .contract(EventbriteApiContract.class) // .build(); // this.cachingDbHelper = new CachingDbHelper(getApplicationContext()); // } // // public CachingDbHelper getCachingDbHelper() { // return cachingDbHelper; // } // // public EventbriteApi getApiEventbrite() { // return apiEventbrite; // } // }
import android.annotation.TargetApi; import android.content.Context; import android.content.res.Resources; import android.graphics.Point; import android.graphics.drawable.Drawable; import android.os.Build; import android.util.DisplayMetrics; import android.util.TypedValue; import android.view.View; import android.view.WindowManager; import com.shollmann.events.ui.EventbriteApplication;
package com.shollmann.events.helper; public class ResourcesHelper { private static DisplayMetrics metrics = new DisplayMetrics(); private static Point screenSize = new Point(); static { setScreenSize(); } public static void setScreenSize() {
// Path: app/src/main/java/com/shollmann/events/ui/EventbriteApplication.java // public class EventbriteApplication extends Application { // private static EventbriteApplication instance; // private CachingDbHelper cachingDbHelper; // private EventbriteApi apiEventbrite; // // public static EventbriteApplication getApplication() { // return instance; // } // // @Override // public void onCreate() { // super.onCreate(); // this.instance = this; // this.apiEventbrite = (EventbriteApi) new EventbriteApi.Builder() // .baseUrl(Constants.EventbriteApi.URL) // .contract(EventbriteApiContract.class) // .build(); // this.cachingDbHelper = new CachingDbHelper(getApplicationContext()); // } // // public CachingDbHelper getCachingDbHelper() { // return cachingDbHelper; // } // // public EventbriteApi getApiEventbrite() { // return apiEventbrite; // } // } // Path: app/src/main/java/com/shollmann/events/helper/ResourcesHelper.java import android.annotation.TargetApi; import android.content.Context; import android.content.res.Resources; import android.graphics.Point; import android.graphics.drawable.Drawable; import android.os.Build; import android.util.DisplayMetrics; import android.util.TypedValue; import android.view.View; import android.view.WindowManager; import com.shollmann.events.ui.EventbriteApplication; package com.shollmann.events.helper; public class ResourcesHelper { private static DisplayMetrics metrics = new DisplayMetrics(); private static Point screenSize = new Point(); static { setScreenSize(); } public static void setScreenSize() {
((WindowManager) EventbriteApplication.getApplication().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay()
santiago-hollmann/sample-events
app/src/main/java/com/shollmann/events/api/baseapi/Api.java
// Path: app/src/main/java/com/shollmann/events/helper/Constants.java // public class Constants { // public static final String EMPTY_STRING = ""; // public static final String UTF_8 = "UTF-8"; // public static final String CACHE = "Cache"; // public static final String COORDINATES_FORMAT = "###.###"; // // public class Size { // public static final long ONE_KIBIBYTE = 1024; // public static final long ONE_MEBIBYTE = ONE_KIBIBYTE * 1024; // public static final long TWO_MEBIBYTES = ONE_MEBIBYTE * 2; // } // // public class EventbriteApi { // public static final String TOKEN = "VBEQ2ZP7SOEWDHH3PVOI"; // public static final String URL = "https://www.eventbriteapi.com"; // } // } // // Path: app/src/main/java/com/shollmann/events/ui/EventbriteApplication.java // public class EventbriteApplication extends Application { // private static EventbriteApplication instance; // private CachingDbHelper cachingDbHelper; // private EventbriteApi apiEventbrite; // // public static EventbriteApplication getApplication() { // return instance; // } // // @Override // public void onCreate() { // super.onCreate(); // this.instance = this; // this.apiEventbrite = (EventbriteApi) new EventbriteApi.Builder() // .baseUrl(Constants.EventbriteApi.URL) // .contract(EventbriteApiContract.class) // .build(); // this.cachingDbHelper = new CachingDbHelper(getApplicationContext()); // } // // public CachingDbHelper getCachingDbHelper() { // return cachingDbHelper; // } // // public EventbriteApi getApiEventbrite() { // return apiEventbrite; // } // }
import android.support.annotation.NonNull; import android.text.TextUtils; import com.shollmann.events.helper.Constants; import com.shollmann.events.ui.EventbriteApplication; import java.io.File; import java.io.IOException; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import okhttp3.HttpUrl; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Callback; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory;
package com.shollmann.events.api.baseapi; public class Api<T> { private static final long DEFAULT_TIMEOUT = 10;
// Path: app/src/main/java/com/shollmann/events/helper/Constants.java // public class Constants { // public static final String EMPTY_STRING = ""; // public static final String UTF_8 = "UTF-8"; // public static final String CACHE = "Cache"; // public static final String COORDINATES_FORMAT = "###.###"; // // public class Size { // public static final long ONE_KIBIBYTE = 1024; // public static final long ONE_MEBIBYTE = ONE_KIBIBYTE * 1024; // public static final long TWO_MEBIBYTES = ONE_MEBIBYTE * 2; // } // // public class EventbriteApi { // public static final String TOKEN = "VBEQ2ZP7SOEWDHH3PVOI"; // public static final String URL = "https://www.eventbriteapi.com"; // } // } // // Path: app/src/main/java/com/shollmann/events/ui/EventbriteApplication.java // public class EventbriteApplication extends Application { // private static EventbriteApplication instance; // private CachingDbHelper cachingDbHelper; // private EventbriteApi apiEventbrite; // // public static EventbriteApplication getApplication() { // return instance; // } // // @Override // public void onCreate() { // super.onCreate(); // this.instance = this; // this.apiEventbrite = (EventbriteApi) new EventbriteApi.Builder() // .baseUrl(Constants.EventbriteApi.URL) // .contract(EventbriteApiContract.class) // .build(); // this.cachingDbHelper = new CachingDbHelper(getApplicationContext()); // } // // public CachingDbHelper getCachingDbHelper() { // return cachingDbHelper; // } // // public EventbriteApi getApiEventbrite() { // return apiEventbrite; // } // } // Path: app/src/main/java/com/shollmann/events/api/baseapi/Api.java import android.support.annotation.NonNull; import android.text.TextUtils; import com.shollmann.events.helper.Constants; import com.shollmann.events.ui.EventbriteApplication; import java.io.File; import java.io.IOException; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import okhttp3.HttpUrl; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Callback; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; package com.shollmann.events.api.baseapi; public class Api<T> { private static final long DEFAULT_TIMEOUT = 10;
private static final long DEFAULT_CACHE_DIR_SIZE = Constants.Size.TWO_MEBIBYTES;
santiago-hollmann/sample-events
app/src/main/java/com/shollmann/events/api/baseapi/Api.java
// Path: app/src/main/java/com/shollmann/events/helper/Constants.java // public class Constants { // public static final String EMPTY_STRING = ""; // public static final String UTF_8 = "UTF-8"; // public static final String CACHE = "Cache"; // public static final String COORDINATES_FORMAT = "###.###"; // // public class Size { // public static final long ONE_KIBIBYTE = 1024; // public static final long ONE_MEBIBYTE = ONE_KIBIBYTE * 1024; // public static final long TWO_MEBIBYTES = ONE_MEBIBYTE * 2; // } // // public class EventbriteApi { // public static final String TOKEN = "VBEQ2ZP7SOEWDHH3PVOI"; // public static final String URL = "https://www.eventbriteapi.com"; // } // } // // Path: app/src/main/java/com/shollmann/events/ui/EventbriteApplication.java // public class EventbriteApplication extends Application { // private static EventbriteApplication instance; // private CachingDbHelper cachingDbHelper; // private EventbriteApi apiEventbrite; // // public static EventbriteApplication getApplication() { // return instance; // } // // @Override // public void onCreate() { // super.onCreate(); // this.instance = this; // this.apiEventbrite = (EventbriteApi) new EventbriteApi.Builder() // .baseUrl(Constants.EventbriteApi.URL) // .contract(EventbriteApiContract.class) // .build(); // this.cachingDbHelper = new CachingDbHelper(getApplicationContext()); // } // // public CachingDbHelper getCachingDbHelper() { // return cachingDbHelper; // } // // public EventbriteApi getApiEventbrite() { // return apiEventbrite; // } // }
import android.support.annotation.NonNull; import android.text.TextUtils; import com.shollmann.events.helper.Constants; import com.shollmann.events.ui.EventbriteApplication; import java.io.File; import java.io.IOException; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import okhttp3.HttpUrl; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Callback; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory;
package com.shollmann.events.api.baseapi; public class Api<T> { private static final long DEFAULT_TIMEOUT = 10; private static final long DEFAULT_CACHE_DIR_SIZE = Constants.Size.TWO_MEBIBYTES; private T service; private Map<CallId, BaseApiCall> ongoingCalls = new HashMap<>(); public Api(Builder builder) { service = buildApiService((T) builder.contract, builder.baseUrl, builder.timeOut, builder.cacheSize); } private okhttp3.Cache createHttpCache(long dirSize) { String cacheDirectoryName = this.getClass().getSimpleName() + Constants.CACHE;
// Path: app/src/main/java/com/shollmann/events/helper/Constants.java // public class Constants { // public static final String EMPTY_STRING = ""; // public static final String UTF_8 = "UTF-8"; // public static final String CACHE = "Cache"; // public static final String COORDINATES_FORMAT = "###.###"; // // public class Size { // public static final long ONE_KIBIBYTE = 1024; // public static final long ONE_MEBIBYTE = ONE_KIBIBYTE * 1024; // public static final long TWO_MEBIBYTES = ONE_MEBIBYTE * 2; // } // // public class EventbriteApi { // public static final String TOKEN = "VBEQ2ZP7SOEWDHH3PVOI"; // public static final String URL = "https://www.eventbriteapi.com"; // } // } // // Path: app/src/main/java/com/shollmann/events/ui/EventbriteApplication.java // public class EventbriteApplication extends Application { // private static EventbriteApplication instance; // private CachingDbHelper cachingDbHelper; // private EventbriteApi apiEventbrite; // // public static EventbriteApplication getApplication() { // return instance; // } // // @Override // public void onCreate() { // super.onCreate(); // this.instance = this; // this.apiEventbrite = (EventbriteApi) new EventbriteApi.Builder() // .baseUrl(Constants.EventbriteApi.URL) // .contract(EventbriteApiContract.class) // .build(); // this.cachingDbHelper = new CachingDbHelper(getApplicationContext()); // } // // public CachingDbHelper getCachingDbHelper() { // return cachingDbHelper; // } // // public EventbriteApi getApiEventbrite() { // return apiEventbrite; // } // } // Path: app/src/main/java/com/shollmann/events/api/baseapi/Api.java import android.support.annotation.NonNull; import android.text.TextUtils; import com.shollmann.events.helper.Constants; import com.shollmann.events.ui.EventbriteApplication; import java.io.File; import java.io.IOException; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import okhttp3.HttpUrl; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Callback; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; package com.shollmann.events.api.baseapi; public class Api<T> { private static final long DEFAULT_TIMEOUT = 10; private static final long DEFAULT_CACHE_DIR_SIZE = Constants.Size.TWO_MEBIBYTES; private T service; private Map<CallId, BaseApiCall> ongoingCalls = new HashMap<>(); public Api(Builder builder) { service = buildApiService((T) builder.contract, builder.baseUrl, builder.timeOut, builder.cacheSize); } private okhttp3.Cache createHttpCache(long dirSize) { String cacheDirectoryName = this.getClass().getSimpleName() + Constants.CACHE;
File cacheDirectory = new File(EventbriteApplication.getApplication().getCacheDir(), cacheDirectoryName);
santiago-hollmann/sample-events
app/src/main/java/com/shollmann/events/ui/EventbriteApplication.java
// Path: app/src/main/java/com/shollmann/events/api/EventbriteApi.java // public class EventbriteApi extends Api<EventbriteApiContract> { // // public EventbriteApi(Builder builder) { // super(builder); // } // // public void getEvents(String query, double lat, double lon, PaginatedEvents lastPageLoaded, CallId callId, Callback<PaginatedEvents> callback) throws IOException { // int pageNumber = lastPageLoaded != null ? lastPageLoaded.getPagination().getPageNumber() + 1 : 1; // Cache cache = new Cache.Builder() // .policy(Cache.Policy.CACHE_ELSE_NETWORK) // .ttl(Cache.Time.ONE_MINUTE) // .key(String.format("get_events_%1$s_%2$s_%3$s_%4$s", query, lat, lon, pageNumber)) // .build(); // // BaseApiCall<PaginatedEvents> apiCall = registerCall(callId, cache, callback, PaginatedEvents.class); // // if (apiCall != null && apiCall.requiresNetworkCall()) { // getService().getEvents(query, lat, lon, pageNumber).enqueue(apiCall); // } // } // // public static class Builder extends Api.Builder { // @Override // public EventbriteApi build() { // super.validate(); // return new EventbriteApi(this); // } // } // // } // // Path: app/src/main/java/com/shollmann/events/api/contract/EventbriteApiContract.java // public interface EventbriteApiContract { // @GET("/v3/events/search/") // Call<PaginatedEvents> getEvents( // @Query("q") String query, // @Query("location.latitude") double latitude, // @Query("location.longitude") double longitude, // @Query("page") int pageNumber); // // } // // Path: app/src/main/java/com/shollmann/events/db/CachingDbHelper.java // public class CachingDbHelper extends DbHelper { // private final static int DB_VERSION = 4; // private final static String DB_NAME = "eventsDatabase"; // private final static String TABLE_NAME = "cache"; // private final static String COLUMN_KEY = "cacheKey"; // private final static String COLUMN_DATA = "cacheData"; // private final static String COLUMN_DATE = "cacheDate"; // private final static boolean AUTO_PURGE = true; // // public CachingDbHelper(Context context) { // super(context, DB_NAME, DB_VERSION, TABLE_NAME, COLUMN_KEY, COLUMN_DATA, COLUMN_DATE, AUTO_PURGE); // } // } // // Path: app/src/main/java/com/shollmann/events/helper/Constants.java // public class Constants { // public static final String EMPTY_STRING = ""; // public static final String UTF_8 = "UTF-8"; // public static final String CACHE = "Cache"; // public static final String COORDINATES_FORMAT = "###.###"; // // public class Size { // public static final long ONE_KIBIBYTE = 1024; // public static final long ONE_MEBIBYTE = ONE_KIBIBYTE * 1024; // public static final long TWO_MEBIBYTES = ONE_MEBIBYTE * 2; // } // // public class EventbriteApi { // public static final String TOKEN = "VBEQ2ZP7SOEWDHH3PVOI"; // public static final String URL = "https://www.eventbriteapi.com"; // } // }
import android.app.Application; import com.shollmann.events.api.EventbriteApi; import com.shollmann.events.api.contract.EventbriteApiContract; import com.shollmann.events.db.CachingDbHelper; import com.shollmann.events.helper.Constants;
package com.shollmann.events.ui; public class EventbriteApplication extends Application { private static EventbriteApplication instance;
// Path: app/src/main/java/com/shollmann/events/api/EventbriteApi.java // public class EventbriteApi extends Api<EventbriteApiContract> { // // public EventbriteApi(Builder builder) { // super(builder); // } // // public void getEvents(String query, double lat, double lon, PaginatedEvents lastPageLoaded, CallId callId, Callback<PaginatedEvents> callback) throws IOException { // int pageNumber = lastPageLoaded != null ? lastPageLoaded.getPagination().getPageNumber() + 1 : 1; // Cache cache = new Cache.Builder() // .policy(Cache.Policy.CACHE_ELSE_NETWORK) // .ttl(Cache.Time.ONE_MINUTE) // .key(String.format("get_events_%1$s_%2$s_%3$s_%4$s", query, lat, lon, pageNumber)) // .build(); // // BaseApiCall<PaginatedEvents> apiCall = registerCall(callId, cache, callback, PaginatedEvents.class); // // if (apiCall != null && apiCall.requiresNetworkCall()) { // getService().getEvents(query, lat, lon, pageNumber).enqueue(apiCall); // } // } // // public static class Builder extends Api.Builder { // @Override // public EventbriteApi build() { // super.validate(); // return new EventbriteApi(this); // } // } // // } // // Path: app/src/main/java/com/shollmann/events/api/contract/EventbriteApiContract.java // public interface EventbriteApiContract { // @GET("/v3/events/search/") // Call<PaginatedEvents> getEvents( // @Query("q") String query, // @Query("location.latitude") double latitude, // @Query("location.longitude") double longitude, // @Query("page") int pageNumber); // // } // // Path: app/src/main/java/com/shollmann/events/db/CachingDbHelper.java // public class CachingDbHelper extends DbHelper { // private final static int DB_VERSION = 4; // private final static String DB_NAME = "eventsDatabase"; // private final static String TABLE_NAME = "cache"; // private final static String COLUMN_KEY = "cacheKey"; // private final static String COLUMN_DATA = "cacheData"; // private final static String COLUMN_DATE = "cacheDate"; // private final static boolean AUTO_PURGE = true; // // public CachingDbHelper(Context context) { // super(context, DB_NAME, DB_VERSION, TABLE_NAME, COLUMN_KEY, COLUMN_DATA, COLUMN_DATE, AUTO_PURGE); // } // } // // Path: app/src/main/java/com/shollmann/events/helper/Constants.java // public class Constants { // public static final String EMPTY_STRING = ""; // public static final String UTF_8 = "UTF-8"; // public static final String CACHE = "Cache"; // public static final String COORDINATES_FORMAT = "###.###"; // // public class Size { // public static final long ONE_KIBIBYTE = 1024; // public static final long ONE_MEBIBYTE = ONE_KIBIBYTE * 1024; // public static final long TWO_MEBIBYTES = ONE_MEBIBYTE * 2; // } // // public class EventbriteApi { // public static final String TOKEN = "VBEQ2ZP7SOEWDHH3PVOI"; // public static final String URL = "https://www.eventbriteapi.com"; // } // } // Path: app/src/main/java/com/shollmann/events/ui/EventbriteApplication.java import android.app.Application; import com.shollmann.events.api.EventbriteApi; import com.shollmann.events.api.contract.EventbriteApiContract; import com.shollmann.events.db.CachingDbHelper; import com.shollmann.events.helper.Constants; package com.shollmann.events.ui; public class EventbriteApplication extends Application { private static EventbriteApplication instance;
private CachingDbHelper cachingDbHelper;
santiago-hollmann/sample-events
app/src/main/java/com/shollmann/events/ui/EventbriteApplication.java
// Path: app/src/main/java/com/shollmann/events/api/EventbriteApi.java // public class EventbriteApi extends Api<EventbriteApiContract> { // // public EventbriteApi(Builder builder) { // super(builder); // } // // public void getEvents(String query, double lat, double lon, PaginatedEvents lastPageLoaded, CallId callId, Callback<PaginatedEvents> callback) throws IOException { // int pageNumber = lastPageLoaded != null ? lastPageLoaded.getPagination().getPageNumber() + 1 : 1; // Cache cache = new Cache.Builder() // .policy(Cache.Policy.CACHE_ELSE_NETWORK) // .ttl(Cache.Time.ONE_MINUTE) // .key(String.format("get_events_%1$s_%2$s_%3$s_%4$s", query, lat, lon, pageNumber)) // .build(); // // BaseApiCall<PaginatedEvents> apiCall = registerCall(callId, cache, callback, PaginatedEvents.class); // // if (apiCall != null && apiCall.requiresNetworkCall()) { // getService().getEvents(query, lat, lon, pageNumber).enqueue(apiCall); // } // } // // public static class Builder extends Api.Builder { // @Override // public EventbriteApi build() { // super.validate(); // return new EventbriteApi(this); // } // } // // } // // Path: app/src/main/java/com/shollmann/events/api/contract/EventbriteApiContract.java // public interface EventbriteApiContract { // @GET("/v3/events/search/") // Call<PaginatedEvents> getEvents( // @Query("q") String query, // @Query("location.latitude") double latitude, // @Query("location.longitude") double longitude, // @Query("page") int pageNumber); // // } // // Path: app/src/main/java/com/shollmann/events/db/CachingDbHelper.java // public class CachingDbHelper extends DbHelper { // private final static int DB_VERSION = 4; // private final static String DB_NAME = "eventsDatabase"; // private final static String TABLE_NAME = "cache"; // private final static String COLUMN_KEY = "cacheKey"; // private final static String COLUMN_DATA = "cacheData"; // private final static String COLUMN_DATE = "cacheDate"; // private final static boolean AUTO_PURGE = true; // // public CachingDbHelper(Context context) { // super(context, DB_NAME, DB_VERSION, TABLE_NAME, COLUMN_KEY, COLUMN_DATA, COLUMN_DATE, AUTO_PURGE); // } // } // // Path: app/src/main/java/com/shollmann/events/helper/Constants.java // public class Constants { // public static final String EMPTY_STRING = ""; // public static final String UTF_8 = "UTF-8"; // public static final String CACHE = "Cache"; // public static final String COORDINATES_FORMAT = "###.###"; // // public class Size { // public static final long ONE_KIBIBYTE = 1024; // public static final long ONE_MEBIBYTE = ONE_KIBIBYTE * 1024; // public static final long TWO_MEBIBYTES = ONE_MEBIBYTE * 2; // } // // public class EventbriteApi { // public static final String TOKEN = "VBEQ2ZP7SOEWDHH3PVOI"; // public static final String URL = "https://www.eventbriteapi.com"; // } // }
import android.app.Application; import com.shollmann.events.api.EventbriteApi; import com.shollmann.events.api.contract.EventbriteApiContract; import com.shollmann.events.db.CachingDbHelper; import com.shollmann.events.helper.Constants;
package com.shollmann.events.ui; public class EventbriteApplication extends Application { private static EventbriteApplication instance; private CachingDbHelper cachingDbHelper;
// Path: app/src/main/java/com/shollmann/events/api/EventbriteApi.java // public class EventbriteApi extends Api<EventbriteApiContract> { // // public EventbriteApi(Builder builder) { // super(builder); // } // // public void getEvents(String query, double lat, double lon, PaginatedEvents lastPageLoaded, CallId callId, Callback<PaginatedEvents> callback) throws IOException { // int pageNumber = lastPageLoaded != null ? lastPageLoaded.getPagination().getPageNumber() + 1 : 1; // Cache cache = new Cache.Builder() // .policy(Cache.Policy.CACHE_ELSE_NETWORK) // .ttl(Cache.Time.ONE_MINUTE) // .key(String.format("get_events_%1$s_%2$s_%3$s_%4$s", query, lat, lon, pageNumber)) // .build(); // // BaseApiCall<PaginatedEvents> apiCall = registerCall(callId, cache, callback, PaginatedEvents.class); // // if (apiCall != null && apiCall.requiresNetworkCall()) { // getService().getEvents(query, lat, lon, pageNumber).enqueue(apiCall); // } // } // // public static class Builder extends Api.Builder { // @Override // public EventbriteApi build() { // super.validate(); // return new EventbriteApi(this); // } // } // // } // // Path: app/src/main/java/com/shollmann/events/api/contract/EventbriteApiContract.java // public interface EventbriteApiContract { // @GET("/v3/events/search/") // Call<PaginatedEvents> getEvents( // @Query("q") String query, // @Query("location.latitude") double latitude, // @Query("location.longitude") double longitude, // @Query("page") int pageNumber); // // } // // Path: app/src/main/java/com/shollmann/events/db/CachingDbHelper.java // public class CachingDbHelper extends DbHelper { // private final static int DB_VERSION = 4; // private final static String DB_NAME = "eventsDatabase"; // private final static String TABLE_NAME = "cache"; // private final static String COLUMN_KEY = "cacheKey"; // private final static String COLUMN_DATA = "cacheData"; // private final static String COLUMN_DATE = "cacheDate"; // private final static boolean AUTO_PURGE = true; // // public CachingDbHelper(Context context) { // super(context, DB_NAME, DB_VERSION, TABLE_NAME, COLUMN_KEY, COLUMN_DATA, COLUMN_DATE, AUTO_PURGE); // } // } // // Path: app/src/main/java/com/shollmann/events/helper/Constants.java // public class Constants { // public static final String EMPTY_STRING = ""; // public static final String UTF_8 = "UTF-8"; // public static final String CACHE = "Cache"; // public static final String COORDINATES_FORMAT = "###.###"; // // public class Size { // public static final long ONE_KIBIBYTE = 1024; // public static final long ONE_MEBIBYTE = ONE_KIBIBYTE * 1024; // public static final long TWO_MEBIBYTES = ONE_MEBIBYTE * 2; // } // // public class EventbriteApi { // public static final String TOKEN = "VBEQ2ZP7SOEWDHH3PVOI"; // public static final String URL = "https://www.eventbriteapi.com"; // } // } // Path: app/src/main/java/com/shollmann/events/ui/EventbriteApplication.java import android.app.Application; import com.shollmann.events.api.EventbriteApi; import com.shollmann.events.api.contract.EventbriteApiContract; import com.shollmann.events.db.CachingDbHelper; import com.shollmann.events.helper.Constants; package com.shollmann.events.ui; public class EventbriteApplication extends Application { private static EventbriteApplication instance; private CachingDbHelper cachingDbHelper;
private EventbriteApi apiEventbrite;
santiago-hollmann/sample-events
app/src/main/java/com/shollmann/events/ui/EventbriteApplication.java
// Path: app/src/main/java/com/shollmann/events/api/EventbriteApi.java // public class EventbriteApi extends Api<EventbriteApiContract> { // // public EventbriteApi(Builder builder) { // super(builder); // } // // public void getEvents(String query, double lat, double lon, PaginatedEvents lastPageLoaded, CallId callId, Callback<PaginatedEvents> callback) throws IOException { // int pageNumber = lastPageLoaded != null ? lastPageLoaded.getPagination().getPageNumber() + 1 : 1; // Cache cache = new Cache.Builder() // .policy(Cache.Policy.CACHE_ELSE_NETWORK) // .ttl(Cache.Time.ONE_MINUTE) // .key(String.format("get_events_%1$s_%2$s_%3$s_%4$s", query, lat, lon, pageNumber)) // .build(); // // BaseApiCall<PaginatedEvents> apiCall = registerCall(callId, cache, callback, PaginatedEvents.class); // // if (apiCall != null && apiCall.requiresNetworkCall()) { // getService().getEvents(query, lat, lon, pageNumber).enqueue(apiCall); // } // } // // public static class Builder extends Api.Builder { // @Override // public EventbriteApi build() { // super.validate(); // return new EventbriteApi(this); // } // } // // } // // Path: app/src/main/java/com/shollmann/events/api/contract/EventbriteApiContract.java // public interface EventbriteApiContract { // @GET("/v3/events/search/") // Call<PaginatedEvents> getEvents( // @Query("q") String query, // @Query("location.latitude") double latitude, // @Query("location.longitude") double longitude, // @Query("page") int pageNumber); // // } // // Path: app/src/main/java/com/shollmann/events/db/CachingDbHelper.java // public class CachingDbHelper extends DbHelper { // private final static int DB_VERSION = 4; // private final static String DB_NAME = "eventsDatabase"; // private final static String TABLE_NAME = "cache"; // private final static String COLUMN_KEY = "cacheKey"; // private final static String COLUMN_DATA = "cacheData"; // private final static String COLUMN_DATE = "cacheDate"; // private final static boolean AUTO_PURGE = true; // // public CachingDbHelper(Context context) { // super(context, DB_NAME, DB_VERSION, TABLE_NAME, COLUMN_KEY, COLUMN_DATA, COLUMN_DATE, AUTO_PURGE); // } // } // // Path: app/src/main/java/com/shollmann/events/helper/Constants.java // public class Constants { // public static final String EMPTY_STRING = ""; // public static final String UTF_8 = "UTF-8"; // public static final String CACHE = "Cache"; // public static final String COORDINATES_FORMAT = "###.###"; // // public class Size { // public static final long ONE_KIBIBYTE = 1024; // public static final long ONE_MEBIBYTE = ONE_KIBIBYTE * 1024; // public static final long TWO_MEBIBYTES = ONE_MEBIBYTE * 2; // } // // public class EventbriteApi { // public static final String TOKEN = "VBEQ2ZP7SOEWDHH3PVOI"; // public static final String URL = "https://www.eventbriteapi.com"; // } // }
import android.app.Application; import com.shollmann.events.api.EventbriteApi; import com.shollmann.events.api.contract.EventbriteApiContract; import com.shollmann.events.db.CachingDbHelper; import com.shollmann.events.helper.Constants;
package com.shollmann.events.ui; public class EventbriteApplication extends Application { private static EventbriteApplication instance; private CachingDbHelper cachingDbHelper; private EventbriteApi apiEventbrite; public static EventbriteApplication getApplication() { return instance; } @Override public void onCreate() { super.onCreate(); this.instance = this; this.apiEventbrite = (EventbriteApi) new EventbriteApi.Builder()
// Path: app/src/main/java/com/shollmann/events/api/EventbriteApi.java // public class EventbriteApi extends Api<EventbriteApiContract> { // // public EventbriteApi(Builder builder) { // super(builder); // } // // public void getEvents(String query, double lat, double lon, PaginatedEvents lastPageLoaded, CallId callId, Callback<PaginatedEvents> callback) throws IOException { // int pageNumber = lastPageLoaded != null ? lastPageLoaded.getPagination().getPageNumber() + 1 : 1; // Cache cache = new Cache.Builder() // .policy(Cache.Policy.CACHE_ELSE_NETWORK) // .ttl(Cache.Time.ONE_MINUTE) // .key(String.format("get_events_%1$s_%2$s_%3$s_%4$s", query, lat, lon, pageNumber)) // .build(); // // BaseApiCall<PaginatedEvents> apiCall = registerCall(callId, cache, callback, PaginatedEvents.class); // // if (apiCall != null && apiCall.requiresNetworkCall()) { // getService().getEvents(query, lat, lon, pageNumber).enqueue(apiCall); // } // } // // public static class Builder extends Api.Builder { // @Override // public EventbriteApi build() { // super.validate(); // return new EventbriteApi(this); // } // } // // } // // Path: app/src/main/java/com/shollmann/events/api/contract/EventbriteApiContract.java // public interface EventbriteApiContract { // @GET("/v3/events/search/") // Call<PaginatedEvents> getEvents( // @Query("q") String query, // @Query("location.latitude") double latitude, // @Query("location.longitude") double longitude, // @Query("page") int pageNumber); // // } // // Path: app/src/main/java/com/shollmann/events/db/CachingDbHelper.java // public class CachingDbHelper extends DbHelper { // private final static int DB_VERSION = 4; // private final static String DB_NAME = "eventsDatabase"; // private final static String TABLE_NAME = "cache"; // private final static String COLUMN_KEY = "cacheKey"; // private final static String COLUMN_DATA = "cacheData"; // private final static String COLUMN_DATE = "cacheDate"; // private final static boolean AUTO_PURGE = true; // // public CachingDbHelper(Context context) { // super(context, DB_NAME, DB_VERSION, TABLE_NAME, COLUMN_KEY, COLUMN_DATA, COLUMN_DATE, AUTO_PURGE); // } // } // // Path: app/src/main/java/com/shollmann/events/helper/Constants.java // public class Constants { // public static final String EMPTY_STRING = ""; // public static final String UTF_8 = "UTF-8"; // public static final String CACHE = "Cache"; // public static final String COORDINATES_FORMAT = "###.###"; // // public class Size { // public static final long ONE_KIBIBYTE = 1024; // public static final long ONE_MEBIBYTE = ONE_KIBIBYTE * 1024; // public static final long TWO_MEBIBYTES = ONE_MEBIBYTE * 2; // } // // public class EventbriteApi { // public static final String TOKEN = "VBEQ2ZP7SOEWDHH3PVOI"; // public static final String URL = "https://www.eventbriteapi.com"; // } // } // Path: app/src/main/java/com/shollmann/events/ui/EventbriteApplication.java import android.app.Application; import com.shollmann.events.api.EventbriteApi; import com.shollmann.events.api.contract.EventbriteApiContract; import com.shollmann.events.db.CachingDbHelper; import com.shollmann.events.helper.Constants; package com.shollmann.events.ui; public class EventbriteApplication extends Application { private static EventbriteApplication instance; private CachingDbHelper cachingDbHelper; private EventbriteApi apiEventbrite; public static EventbriteApplication getApplication() { return instance; } @Override public void onCreate() { super.onCreate(); this.instance = this; this.apiEventbrite = (EventbriteApi) new EventbriteApi.Builder()
.baseUrl(Constants.EventbriteApi.URL)
santiago-hollmann/sample-events
app/src/main/java/com/shollmann/events/ui/EventbriteApplication.java
// Path: app/src/main/java/com/shollmann/events/api/EventbriteApi.java // public class EventbriteApi extends Api<EventbriteApiContract> { // // public EventbriteApi(Builder builder) { // super(builder); // } // // public void getEvents(String query, double lat, double lon, PaginatedEvents lastPageLoaded, CallId callId, Callback<PaginatedEvents> callback) throws IOException { // int pageNumber = lastPageLoaded != null ? lastPageLoaded.getPagination().getPageNumber() + 1 : 1; // Cache cache = new Cache.Builder() // .policy(Cache.Policy.CACHE_ELSE_NETWORK) // .ttl(Cache.Time.ONE_MINUTE) // .key(String.format("get_events_%1$s_%2$s_%3$s_%4$s", query, lat, lon, pageNumber)) // .build(); // // BaseApiCall<PaginatedEvents> apiCall = registerCall(callId, cache, callback, PaginatedEvents.class); // // if (apiCall != null && apiCall.requiresNetworkCall()) { // getService().getEvents(query, lat, lon, pageNumber).enqueue(apiCall); // } // } // // public static class Builder extends Api.Builder { // @Override // public EventbriteApi build() { // super.validate(); // return new EventbriteApi(this); // } // } // // } // // Path: app/src/main/java/com/shollmann/events/api/contract/EventbriteApiContract.java // public interface EventbriteApiContract { // @GET("/v3/events/search/") // Call<PaginatedEvents> getEvents( // @Query("q") String query, // @Query("location.latitude") double latitude, // @Query("location.longitude") double longitude, // @Query("page") int pageNumber); // // } // // Path: app/src/main/java/com/shollmann/events/db/CachingDbHelper.java // public class CachingDbHelper extends DbHelper { // private final static int DB_VERSION = 4; // private final static String DB_NAME = "eventsDatabase"; // private final static String TABLE_NAME = "cache"; // private final static String COLUMN_KEY = "cacheKey"; // private final static String COLUMN_DATA = "cacheData"; // private final static String COLUMN_DATE = "cacheDate"; // private final static boolean AUTO_PURGE = true; // // public CachingDbHelper(Context context) { // super(context, DB_NAME, DB_VERSION, TABLE_NAME, COLUMN_KEY, COLUMN_DATA, COLUMN_DATE, AUTO_PURGE); // } // } // // Path: app/src/main/java/com/shollmann/events/helper/Constants.java // public class Constants { // public static final String EMPTY_STRING = ""; // public static final String UTF_8 = "UTF-8"; // public static final String CACHE = "Cache"; // public static final String COORDINATES_FORMAT = "###.###"; // // public class Size { // public static final long ONE_KIBIBYTE = 1024; // public static final long ONE_MEBIBYTE = ONE_KIBIBYTE * 1024; // public static final long TWO_MEBIBYTES = ONE_MEBIBYTE * 2; // } // // public class EventbriteApi { // public static final String TOKEN = "VBEQ2ZP7SOEWDHH3PVOI"; // public static final String URL = "https://www.eventbriteapi.com"; // } // }
import android.app.Application; import com.shollmann.events.api.EventbriteApi; import com.shollmann.events.api.contract.EventbriteApiContract; import com.shollmann.events.db.CachingDbHelper; import com.shollmann.events.helper.Constants;
package com.shollmann.events.ui; public class EventbriteApplication extends Application { private static EventbriteApplication instance; private CachingDbHelper cachingDbHelper; private EventbriteApi apiEventbrite; public static EventbriteApplication getApplication() { return instance; } @Override public void onCreate() { super.onCreate(); this.instance = this; this.apiEventbrite = (EventbriteApi) new EventbriteApi.Builder() .baseUrl(Constants.EventbriteApi.URL)
// Path: app/src/main/java/com/shollmann/events/api/EventbriteApi.java // public class EventbriteApi extends Api<EventbriteApiContract> { // // public EventbriteApi(Builder builder) { // super(builder); // } // // public void getEvents(String query, double lat, double lon, PaginatedEvents lastPageLoaded, CallId callId, Callback<PaginatedEvents> callback) throws IOException { // int pageNumber = lastPageLoaded != null ? lastPageLoaded.getPagination().getPageNumber() + 1 : 1; // Cache cache = new Cache.Builder() // .policy(Cache.Policy.CACHE_ELSE_NETWORK) // .ttl(Cache.Time.ONE_MINUTE) // .key(String.format("get_events_%1$s_%2$s_%3$s_%4$s", query, lat, lon, pageNumber)) // .build(); // // BaseApiCall<PaginatedEvents> apiCall = registerCall(callId, cache, callback, PaginatedEvents.class); // // if (apiCall != null && apiCall.requiresNetworkCall()) { // getService().getEvents(query, lat, lon, pageNumber).enqueue(apiCall); // } // } // // public static class Builder extends Api.Builder { // @Override // public EventbriteApi build() { // super.validate(); // return new EventbriteApi(this); // } // } // // } // // Path: app/src/main/java/com/shollmann/events/api/contract/EventbriteApiContract.java // public interface EventbriteApiContract { // @GET("/v3/events/search/") // Call<PaginatedEvents> getEvents( // @Query("q") String query, // @Query("location.latitude") double latitude, // @Query("location.longitude") double longitude, // @Query("page") int pageNumber); // // } // // Path: app/src/main/java/com/shollmann/events/db/CachingDbHelper.java // public class CachingDbHelper extends DbHelper { // private final static int DB_VERSION = 4; // private final static String DB_NAME = "eventsDatabase"; // private final static String TABLE_NAME = "cache"; // private final static String COLUMN_KEY = "cacheKey"; // private final static String COLUMN_DATA = "cacheData"; // private final static String COLUMN_DATE = "cacheDate"; // private final static boolean AUTO_PURGE = true; // // public CachingDbHelper(Context context) { // super(context, DB_NAME, DB_VERSION, TABLE_NAME, COLUMN_KEY, COLUMN_DATA, COLUMN_DATE, AUTO_PURGE); // } // } // // Path: app/src/main/java/com/shollmann/events/helper/Constants.java // public class Constants { // public static final String EMPTY_STRING = ""; // public static final String UTF_8 = "UTF-8"; // public static final String CACHE = "Cache"; // public static final String COORDINATES_FORMAT = "###.###"; // // public class Size { // public static final long ONE_KIBIBYTE = 1024; // public static final long ONE_MEBIBYTE = ONE_KIBIBYTE * 1024; // public static final long TWO_MEBIBYTES = ONE_MEBIBYTE * 2; // } // // public class EventbriteApi { // public static final String TOKEN = "VBEQ2ZP7SOEWDHH3PVOI"; // public static final String URL = "https://www.eventbriteapi.com"; // } // } // Path: app/src/main/java/com/shollmann/events/ui/EventbriteApplication.java import android.app.Application; import com.shollmann.events.api.EventbriteApi; import com.shollmann.events.api.contract.EventbriteApiContract; import com.shollmann.events.db.CachingDbHelper; import com.shollmann.events.helper.Constants; package com.shollmann.events.ui; public class EventbriteApplication extends Application { private static EventbriteApplication instance; private CachingDbHelper cachingDbHelper; private EventbriteApi apiEventbrite; public static EventbriteApplication getApplication() { return instance; } @Override public void onCreate() { super.onCreate(); this.instance = this; this.apiEventbrite = (EventbriteApi) new EventbriteApi.Builder() .baseUrl(Constants.EventbriteApi.URL)
.contract(EventbriteApiContract.class)
santiago-hollmann/sample-events
app/src/main/java/com/shollmann/events/api/baseapi/BaseApiCall.java
// Path: app/src/main/java/com/shollmann/events/db/CachingDbHelper.java // public class CachingDbHelper extends DbHelper { // private final static int DB_VERSION = 4; // private final static String DB_NAME = "eventsDatabase"; // private final static String TABLE_NAME = "cache"; // private final static String COLUMN_KEY = "cacheKey"; // private final static String COLUMN_DATA = "cacheData"; // private final static String COLUMN_DATE = "cacheDate"; // private final static boolean AUTO_PURGE = true; // // public CachingDbHelper(Context context) { // super(context, DB_NAME, DB_VERSION, TABLE_NAME, COLUMN_KEY, COLUMN_DATA, COLUMN_DATE, AUTO_PURGE); // } // } // // Path: app/src/main/java/com/shollmann/events/db/DbItem.java // public class DbItem<T> { // // private T object; // private long date; // // public DbItem(T object, long date) { // this.object = object; // this.date = date; // } // // public T getObject() { // return object; // } // // public boolean isExpired(long ttl) { // int seconds = DateUtils.diffSeconds(date); // return seconds > ttl; // } // // } // // Path: app/src/main/java/com/shollmann/events/ui/EventbriteApplication.java // public class EventbriteApplication extends Application { // private static EventbriteApplication instance; // private CachingDbHelper cachingDbHelper; // private EventbriteApi apiEventbrite; // // public static EventbriteApplication getApplication() { // return instance; // } // // @Override // public void onCreate() { // super.onCreate(); // this.instance = this; // this.apiEventbrite = (EventbriteApi) new EventbriteApi.Builder() // .baseUrl(Constants.EventbriteApi.URL) // .contract(EventbriteApiContract.class) // .build(); // this.cachingDbHelper = new CachingDbHelper(getApplicationContext()); // } // // public CachingDbHelper getCachingDbHelper() { // return cachingDbHelper; // } // // public EventbriteApi getApiEventbrite() { // return apiEventbrite; // } // }
import android.text.TextUtils; import com.shollmann.events.db.CachingDbHelper; import com.shollmann.events.db.DbItem; import com.shollmann.events.ui.EventbriteApplication; import java.io.Serializable; import java.lang.reflect.Type; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response;
package com.shollmann.events.api.baseapi; public class BaseApiCall<T> implements Callback<T> { private CachingDbHelper cachingDb; private Api api; private CallId callId; private Cache cache; private Callback<T> callback; private Type responseType; private boolean isCancelled = false; private Response<T> pendingResponse = null; private Call<T> pendingCall = null; private Throwable pendingError = null; BaseApiCall(Api api, CallId callId, Cache cache, Callback<T> callback, Type responseType) {
// Path: app/src/main/java/com/shollmann/events/db/CachingDbHelper.java // public class CachingDbHelper extends DbHelper { // private final static int DB_VERSION = 4; // private final static String DB_NAME = "eventsDatabase"; // private final static String TABLE_NAME = "cache"; // private final static String COLUMN_KEY = "cacheKey"; // private final static String COLUMN_DATA = "cacheData"; // private final static String COLUMN_DATE = "cacheDate"; // private final static boolean AUTO_PURGE = true; // // public CachingDbHelper(Context context) { // super(context, DB_NAME, DB_VERSION, TABLE_NAME, COLUMN_KEY, COLUMN_DATA, COLUMN_DATE, AUTO_PURGE); // } // } // // Path: app/src/main/java/com/shollmann/events/db/DbItem.java // public class DbItem<T> { // // private T object; // private long date; // // public DbItem(T object, long date) { // this.object = object; // this.date = date; // } // // public T getObject() { // return object; // } // // public boolean isExpired(long ttl) { // int seconds = DateUtils.diffSeconds(date); // return seconds > ttl; // } // // } // // Path: app/src/main/java/com/shollmann/events/ui/EventbriteApplication.java // public class EventbriteApplication extends Application { // private static EventbriteApplication instance; // private CachingDbHelper cachingDbHelper; // private EventbriteApi apiEventbrite; // // public static EventbriteApplication getApplication() { // return instance; // } // // @Override // public void onCreate() { // super.onCreate(); // this.instance = this; // this.apiEventbrite = (EventbriteApi) new EventbriteApi.Builder() // .baseUrl(Constants.EventbriteApi.URL) // .contract(EventbriteApiContract.class) // .build(); // this.cachingDbHelper = new CachingDbHelper(getApplicationContext()); // } // // public CachingDbHelper getCachingDbHelper() { // return cachingDbHelper; // } // // public EventbriteApi getApiEventbrite() { // return apiEventbrite; // } // } // Path: app/src/main/java/com/shollmann/events/api/baseapi/BaseApiCall.java import android.text.TextUtils; import com.shollmann.events.db.CachingDbHelper; import com.shollmann.events.db.DbItem; import com.shollmann.events.ui.EventbriteApplication; import java.io.Serializable; import java.lang.reflect.Type; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; package com.shollmann.events.api.baseapi; public class BaseApiCall<T> implements Callback<T> { private CachingDbHelper cachingDb; private Api api; private CallId callId; private Cache cache; private Callback<T> callback; private Type responseType; private boolean isCancelled = false; private Response<T> pendingResponse = null; private Call<T> pendingCall = null; private Throwable pendingError = null; BaseApiCall(Api api, CallId callId, Cache cache, Callback<T> callback, Type responseType) {
this.cachingDb = EventbriteApplication.getApplication().getCachingDbHelper();
santiago-hollmann/sample-events
app/src/main/java/com/shollmann/events/api/baseapi/BaseApiCall.java
// Path: app/src/main/java/com/shollmann/events/db/CachingDbHelper.java // public class CachingDbHelper extends DbHelper { // private final static int DB_VERSION = 4; // private final static String DB_NAME = "eventsDatabase"; // private final static String TABLE_NAME = "cache"; // private final static String COLUMN_KEY = "cacheKey"; // private final static String COLUMN_DATA = "cacheData"; // private final static String COLUMN_DATE = "cacheDate"; // private final static boolean AUTO_PURGE = true; // // public CachingDbHelper(Context context) { // super(context, DB_NAME, DB_VERSION, TABLE_NAME, COLUMN_KEY, COLUMN_DATA, COLUMN_DATE, AUTO_PURGE); // } // } // // Path: app/src/main/java/com/shollmann/events/db/DbItem.java // public class DbItem<T> { // // private T object; // private long date; // // public DbItem(T object, long date) { // this.object = object; // this.date = date; // } // // public T getObject() { // return object; // } // // public boolean isExpired(long ttl) { // int seconds = DateUtils.diffSeconds(date); // return seconds > ttl; // } // // } // // Path: app/src/main/java/com/shollmann/events/ui/EventbriteApplication.java // public class EventbriteApplication extends Application { // private static EventbriteApplication instance; // private CachingDbHelper cachingDbHelper; // private EventbriteApi apiEventbrite; // // public static EventbriteApplication getApplication() { // return instance; // } // // @Override // public void onCreate() { // super.onCreate(); // this.instance = this; // this.apiEventbrite = (EventbriteApi) new EventbriteApi.Builder() // .baseUrl(Constants.EventbriteApi.URL) // .contract(EventbriteApiContract.class) // .build(); // this.cachingDbHelper = new CachingDbHelper(getApplicationContext()); // } // // public CachingDbHelper getCachingDbHelper() { // return cachingDbHelper; // } // // public EventbriteApi getApiEventbrite() { // return apiEventbrite; // } // }
import android.text.TextUtils; import com.shollmann.events.db.CachingDbHelper; import com.shollmann.events.db.DbItem; import com.shollmann.events.ui.EventbriteApplication; import java.io.Serializable; import java.lang.reflect.Type; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response;
package com.shollmann.events.api.baseapi; public class BaseApiCall<T> implements Callback<T> { private CachingDbHelper cachingDb; private Api api; private CallId callId; private Cache cache; private Callback<T> callback; private Type responseType; private boolean isCancelled = false; private Response<T> pendingResponse = null; private Call<T> pendingCall = null; private Throwable pendingError = null; BaseApiCall(Api api, CallId callId, Cache cache, Callback<T> callback, Type responseType) { this.cachingDb = EventbriteApplication.getApplication().getCachingDbHelper(); this.api = api; this.callId = callId; this.cache = cache; this.callback = callback; this.responseType = responseType; } public boolean requiresNetworkCall() { if (cache.policy() == Cache.Policy.NETWORK_ONLY || cache.policy() == Cache.Policy.NETWORK_ELSE_ANY_CACHE) { return true; }
// Path: app/src/main/java/com/shollmann/events/db/CachingDbHelper.java // public class CachingDbHelper extends DbHelper { // private final static int DB_VERSION = 4; // private final static String DB_NAME = "eventsDatabase"; // private final static String TABLE_NAME = "cache"; // private final static String COLUMN_KEY = "cacheKey"; // private final static String COLUMN_DATA = "cacheData"; // private final static String COLUMN_DATE = "cacheDate"; // private final static boolean AUTO_PURGE = true; // // public CachingDbHelper(Context context) { // super(context, DB_NAME, DB_VERSION, TABLE_NAME, COLUMN_KEY, COLUMN_DATA, COLUMN_DATE, AUTO_PURGE); // } // } // // Path: app/src/main/java/com/shollmann/events/db/DbItem.java // public class DbItem<T> { // // private T object; // private long date; // // public DbItem(T object, long date) { // this.object = object; // this.date = date; // } // // public T getObject() { // return object; // } // // public boolean isExpired(long ttl) { // int seconds = DateUtils.diffSeconds(date); // return seconds > ttl; // } // // } // // Path: app/src/main/java/com/shollmann/events/ui/EventbriteApplication.java // public class EventbriteApplication extends Application { // private static EventbriteApplication instance; // private CachingDbHelper cachingDbHelper; // private EventbriteApi apiEventbrite; // // public static EventbriteApplication getApplication() { // return instance; // } // // @Override // public void onCreate() { // super.onCreate(); // this.instance = this; // this.apiEventbrite = (EventbriteApi) new EventbriteApi.Builder() // .baseUrl(Constants.EventbriteApi.URL) // .contract(EventbriteApiContract.class) // .build(); // this.cachingDbHelper = new CachingDbHelper(getApplicationContext()); // } // // public CachingDbHelper getCachingDbHelper() { // return cachingDbHelper; // } // // public EventbriteApi getApiEventbrite() { // return apiEventbrite; // } // } // Path: app/src/main/java/com/shollmann/events/api/baseapi/BaseApiCall.java import android.text.TextUtils; import com.shollmann.events.db.CachingDbHelper; import com.shollmann.events.db.DbItem; import com.shollmann.events.ui.EventbriteApplication; import java.io.Serializable; import java.lang.reflect.Type; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; package com.shollmann.events.api.baseapi; public class BaseApiCall<T> implements Callback<T> { private CachingDbHelper cachingDb; private Api api; private CallId callId; private Cache cache; private Callback<T> callback; private Type responseType; private boolean isCancelled = false; private Response<T> pendingResponse = null; private Call<T> pendingCall = null; private Throwable pendingError = null; BaseApiCall(Api api, CallId callId, Cache cache, Callback<T> callback, Type responseType) { this.cachingDb = EventbriteApplication.getApplication().getCachingDbHelper(); this.api = api; this.callId = callId; this.cache = cache; this.callback = callback; this.responseType = responseType; } public boolean requiresNetworkCall() { if (cache.policy() == Cache.Policy.NETWORK_ONLY || cache.policy() == Cache.Policy.NETWORK_ELSE_ANY_CACHE) { return true; }
DbItem<T> cachedResponse = cachingDb.getDbItem(cache.key(), responseType);
santiago-hollmann/sample-events
app/src/main/java/com/shollmann/events/api/contract/EventbriteApiContract.java
// Path: app/src/main/java/com/shollmann/events/api/model/PaginatedEvents.java // public class PaginatedEvents implements Serializable { // private Pagination pagination; // private List<Event> events; // // public Pagination getPagination() { // return pagination; // } // // public void setPagination(Pagination pagination) { // this.pagination = pagination; // } // // public List<Event> getEvents() { // return events; // } // // public void setEvents(List<Event> events) { // this.events = events; // } // }
import com.shollmann.events.api.model.PaginatedEvents; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query;
package com.shollmann.events.api.contract; public interface EventbriteApiContract { @GET("/v3/events/search/")
// Path: app/src/main/java/com/shollmann/events/api/model/PaginatedEvents.java // public class PaginatedEvents implements Serializable { // private Pagination pagination; // private List<Event> events; // // public Pagination getPagination() { // return pagination; // } // // public void setPagination(Pagination pagination) { // this.pagination = pagination; // } // // public List<Event> getEvents() { // return events; // } // // public void setEvents(List<Event> events) { // this.events = events; // } // } // Path: app/src/main/java/com/shollmann/events/api/contract/EventbriteApiContract.java import com.shollmann.events.api.model.PaginatedEvents; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; package com.shollmann.events.api.contract; public interface EventbriteApiContract { @GET("/v3/events/search/")
Call<PaginatedEvents> getEvents(
zhangxx0/WOTPlus
app/src/main/java/com/xinxin/wotplus/network/api/UtilApi.java
// Path: app/src/main/java/com/xinxin/wotplus/model/VersionVo.java // public class VersionVo implements Serializable { // // // /** // * name : WOTPlus // * version : 1 // * changelog : First debug // * updated_at : 1460383133 // * versionShort : 0.1 // * build : 1 // * installUrl : http://download.fir.im/v2/app/install/570bad9000fc7436da000007?download_token=4ea5f79c0c954e0ea75a680d6ee03ddd // * install_url : http://download.fir.im/v2/app/install/570bad9000fc7436da000007?download_token=4ea5f79c0c954e0ea75a680d6ee03ddd // * direct_install_url : http://download.fir.im/v2/app/install/570bad9000fc7436da000007?download_token=4ea5f79c0c954e0ea75a680d6ee03ddd // * update_url : http://fir.im/rlps // * binary : {"fsize":5681684} // */ // // private String name; // private String version; // private String changelog; // private int updated_at; // private String versionShort; // private String build; // private String installUrl; // private String install_url; // private String direct_install_url; // private String update_url; // /** // * fsize : 5681684 // */ // // private BinaryEntity binary; // // public void setName(String name) { // this.name = name; // } // // public void setVersion(String version) { // this.version = version; // } // // public void setChangelog(String changelog) { // this.changelog = changelog; // } // // public void setUpdated_at(int updated_at) { // this.updated_at = updated_at; // } // // public void setVersionShort(String versionShort) { // this.versionShort = versionShort; // } // // public void setBuild(String build) { // this.build = build; // } // // public void setInstallUrl(String installUrl) { // this.installUrl = installUrl; // } // // public void setInstall_url(String install_url) { // this.install_url = install_url; // } // // public void setDirect_install_url(String direct_install_url) { // this.direct_install_url = direct_install_url; // } // // public void setUpdate_url(String update_url) { // this.update_url = update_url; // } // // public void setBinary(BinaryEntity binary) { // this.binary = binary; // } // // public String getName() { // return name; // } // // public String getVersion() { // return version; // } // // public String getChangelog() { // return changelog; // } // // public int getUpdated_at() { // return updated_at; // } // // public String getVersionShort() { // return versionShort; // } // // public String getBuild() { // return build; // } // // public String getInstallUrl() { // return installUrl; // } // // public String getInstall_url() { // return install_url; // } // // public String getDirect_install_url() { // return direct_install_url; // } // // public String getUpdate_url() { // return update_url; // } // // public BinaryEntity getBinary() { // return binary; // } // // public static class BinaryEntity { // private int fsize; // // public void setFsize(int fsize) { // this.fsize = fsize; // } // // public int getFsize() { // return fsize; // } // } // }
import com.xinxin.wotplus.model.VersionVo; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; import rx.Observable;
package com.xinxin.wotplus.network.api; /** * Created by xinxin on 2016/5/21. * */ public interface UtilApi { // http://api.fir.im/apps/latest/xxx?api_token=xxx #使用 `id` 请求 /** * 版本更新检查 * @param appId * @param api_token * @return */ @GET("{appId}")
// Path: app/src/main/java/com/xinxin/wotplus/model/VersionVo.java // public class VersionVo implements Serializable { // // // /** // * name : WOTPlus // * version : 1 // * changelog : First debug // * updated_at : 1460383133 // * versionShort : 0.1 // * build : 1 // * installUrl : http://download.fir.im/v2/app/install/570bad9000fc7436da000007?download_token=4ea5f79c0c954e0ea75a680d6ee03ddd // * install_url : http://download.fir.im/v2/app/install/570bad9000fc7436da000007?download_token=4ea5f79c0c954e0ea75a680d6ee03ddd // * direct_install_url : http://download.fir.im/v2/app/install/570bad9000fc7436da000007?download_token=4ea5f79c0c954e0ea75a680d6ee03ddd // * update_url : http://fir.im/rlps // * binary : {"fsize":5681684} // */ // // private String name; // private String version; // private String changelog; // private int updated_at; // private String versionShort; // private String build; // private String installUrl; // private String install_url; // private String direct_install_url; // private String update_url; // /** // * fsize : 5681684 // */ // // private BinaryEntity binary; // // public void setName(String name) { // this.name = name; // } // // public void setVersion(String version) { // this.version = version; // } // // public void setChangelog(String changelog) { // this.changelog = changelog; // } // // public void setUpdated_at(int updated_at) { // this.updated_at = updated_at; // } // // public void setVersionShort(String versionShort) { // this.versionShort = versionShort; // } // // public void setBuild(String build) { // this.build = build; // } // // public void setInstallUrl(String installUrl) { // this.installUrl = installUrl; // } // // public void setInstall_url(String install_url) { // this.install_url = install_url; // } // // public void setDirect_install_url(String direct_install_url) { // this.direct_install_url = direct_install_url; // } // // public void setUpdate_url(String update_url) { // this.update_url = update_url; // } // // public void setBinary(BinaryEntity binary) { // this.binary = binary; // } // // public String getName() { // return name; // } // // public String getVersion() { // return version; // } // // public String getChangelog() { // return changelog; // } // // public int getUpdated_at() { // return updated_at; // } // // public String getVersionShort() { // return versionShort; // } // // public String getBuild() { // return build; // } // // public String getInstallUrl() { // return installUrl; // } // // public String getInstall_url() { // return install_url; // } // // public String getDirect_install_url() { // return direct_install_url; // } // // public String getUpdate_url() { // return update_url; // } // // public BinaryEntity getBinary() { // return binary; // } // // public static class BinaryEntity { // private int fsize; // // public void setFsize(int fsize) { // this.fsize = fsize; // } // // public int getFsize() { // return fsize; // } // } // } // Path: app/src/main/java/com/xinxin/wotplus/network/api/UtilApi.java import com.xinxin.wotplus.model.VersionVo; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; import rx.Observable; package com.xinxin.wotplus.network.api; /** * Created by xinxin on 2016/5/21. * */ public interface UtilApi { // http://api.fir.im/apps/latest/xxx?api_token=xxx #使用 `id` 请求 /** * 版本更新检查 * @param appId * @param api_token * @return */ @GET("{appId}")
Observable<VersionVo> checkVersion(@Path("appId") String appId, @Query("api_token") String api_token);
zhangxx0/WOTPlus
app/src/main/java/com/xinxin/wotplus/util/mapper/TanksjsToMapMapper.java
// Path: app/src/main/java/com/xinxin/wotplus/model/TankInfo.java // public class TankInfo implements Serializable { // // // /** // * name : Ch01_Type59 // * modelname : Ch01_Type59 // * country : C系 // * encountry : china // * entype : mediumTank // * type : 中型坦克 // * level : 8 // * alias : 59式 // * weight : 400 // */ // // private String name; // private String modelname; // private String country; // private String encountry; // private String entype; // private String type; // private int level; // private String alias; // private String weight; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getModelname() { // return modelname; // } // // public void setModelname(String modelname) { // this.modelname = modelname; // } // // public String getCountry() { // return country; // } // // public void setCountry(String country) { // this.country = country; // } // // public String getEncountry() { // return encountry; // } // // public void setEncountry(String encountry) { // this.encountry = encountry; // } // // public String getEntype() { // return entype; // } // // public void setEntype(String entype) { // this.entype = entype; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public int getLevel() { // return level; // } // // public void setLevel(int level) { // this.level = level; // } // // public String getAlias() { // return alias; // } // // public void setAlias(String alias) { // this.alias = alias; // } // // public String getWeight() { // return weight; // } // // public void setWeight(String weight) { // this.weight = weight; // } // }
import com.google.gson.Gson; import com.xinxin.wotplus.model.TankInfo; import java.util.HashMap; import java.util.Map; import okhttp3.ResponseBody; import rx.functions.Func1;
package com.xinxin.wotplus.util.mapper; /** * Created by xinxin on 2016/5/22. * tanks.js -> map */ public class TanksjsToMapMapper implements Func1<ResponseBody, Map> { private static TanksjsToMapMapper INSTANCE = new TanksjsToMapMapper(); public TanksjsToMapMapper() { } public static TanksjsToMapMapper getInstance() { return INSTANCE; } @Override public Map call(ResponseBody responseBody) { Map map = new HashMap(); if (responseBody != null) { String tankssourse = ""; try { // responseBody.string()输出结果:System.out: }; // 可能是由于换行符的原因,不能直接用下面的.string方法;不是这个原因,因此仍然使用string()方法; // byte[] byBuffer = responseBody.bytes(); // String strRead = new String(byBuffer); String strRead = responseBody.string(); String realSourse = strRead.substring(14, strRead.length() - 2); // 还真不是换行符的问题(之前只使用一个},后来加上两个\\),,,escaping `}` not needed in Java // http://stackoverflow.com/questions/13508992/android-syntax-error-in-regexp-pattern String x = "\\},"; String[] stringArray = realSourse.replaceAll("\r|\n|\t", "").split(x); for (int i = 0; i < stringArray.length; i++) { Gson gson = new Gson();
// Path: app/src/main/java/com/xinxin/wotplus/model/TankInfo.java // public class TankInfo implements Serializable { // // // /** // * name : Ch01_Type59 // * modelname : Ch01_Type59 // * country : C系 // * encountry : china // * entype : mediumTank // * type : 中型坦克 // * level : 8 // * alias : 59式 // * weight : 400 // */ // // private String name; // private String modelname; // private String country; // private String encountry; // private String entype; // private String type; // private int level; // private String alias; // private String weight; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getModelname() { // return modelname; // } // // public void setModelname(String modelname) { // this.modelname = modelname; // } // // public String getCountry() { // return country; // } // // public void setCountry(String country) { // this.country = country; // } // // public String getEncountry() { // return encountry; // } // // public void setEncountry(String encountry) { // this.encountry = encountry; // } // // public String getEntype() { // return entype; // } // // public void setEntype(String entype) { // this.entype = entype; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public int getLevel() { // return level; // } // // public void setLevel(int level) { // this.level = level; // } // // public String getAlias() { // return alias; // } // // public void setAlias(String alias) { // this.alias = alias; // } // // public String getWeight() { // return weight; // } // // public void setWeight(String weight) { // this.weight = weight; // } // } // Path: app/src/main/java/com/xinxin/wotplus/util/mapper/TanksjsToMapMapper.java import com.google.gson.Gson; import com.xinxin.wotplus.model.TankInfo; import java.util.HashMap; import java.util.Map; import okhttp3.ResponseBody; import rx.functions.Func1; package com.xinxin.wotplus.util.mapper; /** * Created by xinxin on 2016/5/22. * tanks.js -> map */ public class TanksjsToMapMapper implements Func1<ResponseBody, Map> { private static TanksjsToMapMapper INSTANCE = new TanksjsToMapMapper(); public TanksjsToMapMapper() { } public static TanksjsToMapMapper getInstance() { return INSTANCE; } @Override public Map call(ResponseBody responseBody) { Map map = new HashMap(); if (responseBody != null) { String tankssourse = ""; try { // responseBody.string()输出结果:System.out: }; // 可能是由于换行符的原因,不能直接用下面的.string方法;不是这个原因,因此仍然使用string()方法; // byte[] byBuffer = responseBody.bytes(); // String strRead = new String(byBuffer); String strRead = responseBody.string(); String realSourse = strRead.substring(14, strRead.length() - 2); // 还真不是换行符的问题(之前只使用一个},后来加上两个\\),,,escaping `}` not needed in Java // http://stackoverflow.com/questions/13508992/android-syntax-error-in-regexp-pattern String x = "\\},"; String[] stringArray = realSourse.replaceAll("\r|\n|\t", "").split(x); for (int i = 0; i < stringArray.length; i++) { Gson gson = new Gson();
TankInfo tankInfo = new TankInfo();
zhangxx0/WOTPlus
app/src/main/java/com/xinxin/wotplus/adapter/TanksByTypeAdapter.java
// Path: app/src/main/java/com/xinxin/wotplus/model/Tank.java // public class Tank implements Serializable { // // private String tankCountry; // private String tankLevel; // private String tankIcon; // private String tankName; // private String tankFightNum; // private String tankWinRate; // private String tankBadge; // // /** // * ID用于查询坦克的详细信息 // */ // private String tankId; // // // // public String getTankId() { // return tankId; // } // // public void setTankId(String tankId) { // this.tankId = tankId; // } // // public String getTankCountry() { // return tankCountry; // } // // public void setTankCountry(String tankCountry) { // this.tankCountry = tankCountry; // } // // public String getTankLevel() { // return tankLevel; // } // // public void setTankLevel(String tankLevel) { // this.tankLevel = tankLevel; // } // // public String getTankIcon() { // return tankIcon; // } // // public void setTankIcon(String tankIcon) { // this.tankIcon = tankIcon; // } // // public String getTankName() { // return tankName; // } // // public void setTankName(String tankName) { // this.tankName = tankName; // } // // public String getTankFightNum() { // return tankFightNum; // } // // public void setTankFightNum(String tankFightNum) { // this.tankFightNum = tankFightNum; // } // // public String getTankWinRate() { // return tankWinRate; // } // // public void setTankWinRate(String tankWinRate) { // this.tankWinRate = tankWinRate; // } // // public String getTankBadge() { // return tankBadge; // } // // public void setTankBadge(String tankBadge) { // this.tankBadge = tankBadge; // } // }
import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.xinxin.wotplus.R; import com.xinxin.wotplus.model.Tank; import java.util.List;
package com.xinxin.wotplus.adapter; /** * Created by xinxin on 2016/4/7. * 各个分类的坦克列表适配器 */ public class TanksByTypeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private Context context; private LayoutInflater layoutInflater;
// Path: app/src/main/java/com/xinxin/wotplus/model/Tank.java // public class Tank implements Serializable { // // private String tankCountry; // private String tankLevel; // private String tankIcon; // private String tankName; // private String tankFightNum; // private String tankWinRate; // private String tankBadge; // // /** // * ID用于查询坦克的详细信息 // */ // private String tankId; // // // // public String getTankId() { // return tankId; // } // // public void setTankId(String tankId) { // this.tankId = tankId; // } // // public String getTankCountry() { // return tankCountry; // } // // public void setTankCountry(String tankCountry) { // this.tankCountry = tankCountry; // } // // public String getTankLevel() { // return tankLevel; // } // // public void setTankLevel(String tankLevel) { // this.tankLevel = tankLevel; // } // // public String getTankIcon() { // return tankIcon; // } // // public void setTankIcon(String tankIcon) { // this.tankIcon = tankIcon; // } // // public String getTankName() { // return tankName; // } // // public void setTankName(String tankName) { // this.tankName = tankName; // } // // public String getTankFightNum() { // return tankFightNum; // } // // public void setTankFightNum(String tankFightNum) { // this.tankFightNum = tankFightNum; // } // // public String getTankWinRate() { // return tankWinRate; // } // // public void setTankWinRate(String tankWinRate) { // this.tankWinRate = tankWinRate; // } // // public String getTankBadge() { // return tankBadge; // } // // public void setTankBadge(String tankBadge) { // this.tankBadge = tankBadge; // } // } // Path: app/src/main/java/com/xinxin/wotplus/adapter/TanksByTypeAdapter.java import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.xinxin.wotplus.R; import com.xinxin.wotplus.model.Tank; import java.util.List; package com.xinxin.wotplus.adapter; /** * Created by xinxin on 2016/4/7. * 各个分类的坦克列表适配器 */ public class TanksByTypeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private Context context; private LayoutInflater layoutInflater;
private List<Tank> tanksByTypeList;
zhangxx0/WOTPlus
app/src/main/java/com/xinxin/wotplus/network/api/TankApi.java
// Path: app/src/main/java/com/xinxin/wotplus/model/AchieveTank.java // public class AchieveTank implements Serializable{ // // // /** // * status : ok // * achievements : [{"count":11,"type":"series","name":"armorPiercer","weight":1014},{"count":17,"type":"series","name":"titleSniper","weight":1015},{"count":2,"type":"repeatable","name":"sniper","weight":205}] // * damage_per_battle : 1,255 // * xp_amount : 11,115 // * frags_per_battle : 0.73 // * damage_dealt : 13,813 // * damage_dealt_received_ratio : 1.65 // * frags_count : 8 // * xp_max : 1,825 // * hits_percent : 72.34 // * battles_count : 11 // * frags_killed_ratio : 1.14 // */ // // private String status; // private String damage_per_battle; // private String xp_amount; // private String frags_per_battle; // private String damage_dealt; // private String damage_dealt_received_ratio; // private String frags_count; // private String xp_max; // private String hits_percent; // private String battles_count; // private String frags_killed_ratio; // /** // * count : 11 // * type : series // * name : armorPiercer // * weight : 1014.0 // */ // // private List<AchievementsEntity> achievements; // // public static class AchievementsEntity { // private int count; // private String type; // private String name; // private double weight; // // public void setCount(int count) { // this.count = count; // } // // public void setType(String type) { // this.type = type; // } // // public void setName(String name) { // this.name = name; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public int getCount() { // return count; // } // // public String getType() { // return type; // } // // public String getName() { // return name; // } // // public double getWeight() { // return weight; // } // } // // public void setStatus(String status) { // this.status = status; // } // // public void setDamage_per_battle(String damage_per_battle) { // this.damage_per_battle = damage_per_battle; // } // // public void setXp_amount(String xp_amount) { // this.xp_amount = xp_amount; // } // // public void setFrags_per_battle(String frags_per_battle) { // this.frags_per_battle = frags_per_battle; // } // // public void setDamage_dealt(String damage_dealt) { // this.damage_dealt = damage_dealt; // } // // public void setDamage_dealt_received_ratio(String damage_dealt_received_ratio) { // this.damage_dealt_received_ratio = damage_dealt_received_ratio; // } // // public void setFrags_count(String frags_count) { // this.frags_count = frags_count; // } // // public void setXp_max(String xp_max) { // this.xp_max = xp_max; // } // // public void setHits_percent(String hits_percent) { // this.hits_percent = hits_percent; // } // // public void setBattles_count(String battles_count) { // this.battles_count = battles_count; // } // // public void setFrags_killed_ratio(String frags_killed_ratio) { // this.frags_killed_ratio = frags_killed_ratio; // } // // public void setAchievements(List<AchievementsEntity> achievements) { // this.achievements = achievements; // } // // public String getStatus() { // return status; // } // // public String getDamage_per_battle() { // return damage_per_battle; // } // // public String getXp_amount() { // return xp_amount; // } // // public String getFrags_per_battle() { // return frags_per_battle; // } // // public String getDamage_dealt() { // return damage_dealt; // } // // public String getDamage_dealt_received_ratio() { // return damage_dealt_received_ratio; // } // // public String getFrags_count() { // return frags_count; // } // // public String getXp_max() { // return xp_max; // } // // public String getHits_percent() { // return hits_percent; // } // // public String getBattles_count() { // return battles_count; // } // // public String getFrags_killed_ratio() { // return frags_killed_ratio; // } // // public List<AchievementsEntity> getAchievements() { // return achievements; // } // // // }
import com.xinxin.wotplus.model.AchieveTank; import retrofit2.http.GET; import retrofit2.http.Headers; import retrofit2.http.Path; import retrofit2.http.Query; import rx.Observable;
package com.xinxin.wotplus.network.api; /** * Created by xinxin on 2016/5/21. * 坦克战绩 */ public interface TankApi { // http://ncw.worldoftanks.cn/zh-cn/community/accounts/1503597733/vehicle_details/?vehicle_cd=3889 @Headers( "X-Requested-With: XMLHttpRequest" ) @GET("{accountId}/vehicle_details/")
// Path: app/src/main/java/com/xinxin/wotplus/model/AchieveTank.java // public class AchieveTank implements Serializable{ // // // /** // * status : ok // * achievements : [{"count":11,"type":"series","name":"armorPiercer","weight":1014},{"count":17,"type":"series","name":"titleSniper","weight":1015},{"count":2,"type":"repeatable","name":"sniper","weight":205}] // * damage_per_battle : 1,255 // * xp_amount : 11,115 // * frags_per_battle : 0.73 // * damage_dealt : 13,813 // * damage_dealt_received_ratio : 1.65 // * frags_count : 8 // * xp_max : 1,825 // * hits_percent : 72.34 // * battles_count : 11 // * frags_killed_ratio : 1.14 // */ // // private String status; // private String damage_per_battle; // private String xp_amount; // private String frags_per_battle; // private String damage_dealt; // private String damage_dealt_received_ratio; // private String frags_count; // private String xp_max; // private String hits_percent; // private String battles_count; // private String frags_killed_ratio; // /** // * count : 11 // * type : series // * name : armorPiercer // * weight : 1014.0 // */ // // private List<AchievementsEntity> achievements; // // public static class AchievementsEntity { // private int count; // private String type; // private String name; // private double weight; // // public void setCount(int count) { // this.count = count; // } // // public void setType(String type) { // this.type = type; // } // // public void setName(String name) { // this.name = name; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public int getCount() { // return count; // } // // public String getType() { // return type; // } // // public String getName() { // return name; // } // // public double getWeight() { // return weight; // } // } // // public void setStatus(String status) { // this.status = status; // } // // public void setDamage_per_battle(String damage_per_battle) { // this.damage_per_battle = damage_per_battle; // } // // public void setXp_amount(String xp_amount) { // this.xp_amount = xp_amount; // } // // public void setFrags_per_battle(String frags_per_battle) { // this.frags_per_battle = frags_per_battle; // } // // public void setDamage_dealt(String damage_dealt) { // this.damage_dealt = damage_dealt; // } // // public void setDamage_dealt_received_ratio(String damage_dealt_received_ratio) { // this.damage_dealt_received_ratio = damage_dealt_received_ratio; // } // // public void setFrags_count(String frags_count) { // this.frags_count = frags_count; // } // // public void setXp_max(String xp_max) { // this.xp_max = xp_max; // } // // public void setHits_percent(String hits_percent) { // this.hits_percent = hits_percent; // } // // public void setBattles_count(String battles_count) { // this.battles_count = battles_count; // } // // public void setFrags_killed_ratio(String frags_killed_ratio) { // this.frags_killed_ratio = frags_killed_ratio; // } // // public void setAchievements(List<AchievementsEntity> achievements) { // this.achievements = achievements; // } // // public String getStatus() { // return status; // } // // public String getDamage_per_battle() { // return damage_per_battle; // } // // public String getXp_amount() { // return xp_amount; // } // // public String getFrags_per_battle() { // return frags_per_battle; // } // // public String getDamage_dealt() { // return damage_dealt; // } // // public String getDamage_dealt_received_ratio() { // return damage_dealt_received_ratio; // } // // public String getFrags_count() { // return frags_count; // } // // public String getXp_max() { // return xp_max; // } // // public String getHits_percent() { // return hits_percent; // } // // public String getBattles_count() { // return battles_count; // } // // public String getFrags_killed_ratio() { // return frags_killed_ratio; // } // // public List<AchievementsEntity> getAchievements() { // return achievements; // } // // // } // Path: app/src/main/java/com/xinxin/wotplus/network/api/TankApi.java import com.xinxin.wotplus.model.AchieveTank; import retrofit2.http.GET; import retrofit2.http.Headers; import retrofit2.http.Path; import retrofit2.http.Query; import rx.Observable; package com.xinxin.wotplus.network.api; /** * Created by xinxin on 2016/5/21. * 坦克战绩 */ public interface TankApi { // http://ncw.worldoftanks.cn/zh-cn/community/accounts/1503597733/vehicle_details/?vehicle_cd=3889 @Headers( "X-Requested-With: XMLHttpRequest" ) @GET("{accountId}/vehicle_details/")
Observable<AchieveTank> getTankAchieve(@Path("accountId") String accountId, @Query("vehicle_cd") String tankId);
zhangxx0/WOTPlus
app/src/main/java/com/xinxin/wotplus/util/HttpUtil.java
// Path: app/src/main/java/com/xinxin/wotplus/MyApplication.java // public class MyApplication extends Application { // // private static Context context; // // @Override // public void onCreate() { // context = getApplicationContext(); // super.onCreate(); // // 初始化极光推送sdk // // JPushInterface.setDebugMode(true); // JPushInterface.init(this); // JPushInterface.setAlias(context, "WOTPlus1.0", new TagAliasCallback() { // @Override // public void gotResult(int i, String s, Set<String> set) { // Log.d("Jpush set alias", String.valueOf(i)); // } // }); // } // // public static Context getContext() { // return context; // } // // }
import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.telephony.TelephonyManager; import android.util.Log; import android.widget.ImageView; import android.widget.Toast; import com.xinxin.wotplus.MyApplication; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL;
package com.xinxin.wotplus.util; /** * Created by xinxin on 2016/2/17. * <p/> * 网络请求工具类 */ public class HttpUtil { public static void sendHttpRequest(final String address, final HttpCallbackListener listener) { if (!isNetworkAvailable()) { // 使用MyApplication获取context;
// Path: app/src/main/java/com/xinxin/wotplus/MyApplication.java // public class MyApplication extends Application { // // private static Context context; // // @Override // public void onCreate() { // context = getApplicationContext(); // super.onCreate(); // // 初始化极光推送sdk // // JPushInterface.setDebugMode(true); // JPushInterface.init(this); // JPushInterface.setAlias(context, "WOTPlus1.0", new TagAliasCallback() { // @Override // public void gotResult(int i, String s, Set<String> set) { // Log.d("Jpush set alias", String.valueOf(i)); // } // }); // } // // public static Context getContext() { // return context; // } // // } // Path: app/src/main/java/com/xinxin/wotplus/util/HttpUtil.java import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.telephony.TelephonyManager; import android.util.Log; import android.widget.ImageView; import android.widget.Toast; import com.xinxin.wotplus.MyApplication; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; package com.xinxin.wotplus.util; /** * Created by xinxin on 2016/2/17. * <p/> * 网络请求工具类 */ public class HttpUtil { public static void sendHttpRequest(final String address, final HttpCallbackListener listener) { if (!isNetworkAvailable()) { // 使用MyApplication获取context;
Toast.makeText(MyApplication.getContext(), "network is unavailable", Toast.LENGTH_SHORT).show();
blind-coder/SpaceTrader
SpaceTrader/src/main/java/de/anderdonau/spacetrader/FragmentAveragePrices.java
// Path: SpaceTrader/src/main/java/de/anderdonau/spacetrader/DataTypes/CrewMember.java // public class CrewMember implements Serializable { // public int nameIndex; // public int pilot; // public int fighter; // public int trader; // public int engineer; // public int curSystem; // // public CrewMember() { // nameIndex = 1; // pilot = 1; // fighter = 1; // trader = 1; // engineer = 1; // curSystem = -1; // } // // public CrewMember(int nameIndex, int pilot, int fighter, int trader, int engineer, int curSystem) { // this.nameIndex = nameIndex; // this.pilot = pilot; // this.fighter = fighter; // this.trader = trader; // this.engineer = engineer; // this.curSystem = curSystem; // } // } // // Path: SpaceTrader/src/main/java/de/anderdonau/spacetrader/DataTypes/MyFragment.java // public class MyFragment extends Fragment { // public Main main = null; // public GameState gameState = null; // // @Override // public void onAttach(Activity activity) { // super.onAttach(activity); // this.main = (Main) activity; // } // // public boolean update() { // return false; // } // } // // Path: SpaceTrader/src/main/java/de/anderdonau/spacetrader/DataTypes/SolarSystem.java // public class SolarSystem implements Serializable { // public int nameIndex; // public int techLevel; // Tech level // public int politics; // Political system // public int status; // Status // public int x; // X-coordinate (galaxy width = 150) // public int y; // Y-coordinate (galaxy height = 100) // public int specialResources; // Special resources // public int size; // System size // public int[] qty = new int[GameState.MAXTRADEITEM]; // // Quantities of tradeitems. These change very slowly over time. // public int countDown; // Countdown for reset of tradeitems. // public boolean visited; // Visited Yes or No // public int special; // Special event // Random rand = new Random(); // // public void initializeTradeitems() { // int i; // // for (i = 0; i < GameState.MAXTRADEITEM; ++i) { // if (((i == GameState.NARCOTICS) && (!Politics.mPolitics[this.politics].drugsOK)) || // ((i == GameState.FIREARMS) && (!Politics.mPolitics[this.politics].firearmsOK)) || // (this.techLevel < Tradeitems.mTradeitems[i].techProduction)) { // this.qty[i] = 0; // continue; // } // // this.qty[i] = ((9 + rand.nextInt(5)) - Math.abs( // Tradeitems.mTradeitems[i].techTopProduction - this.techLevel)) * (1 + this.size); // // // Because of the enormous profits possible, there shouldn't be too many robots or narcotics available // if (i == GameState.ROBOTS || i == GameState.NARCOTICS) { // this.qty[i] = // ((this.qty[i] * (5 - GameState.getDifficulty())) / (6 - GameState.getDifficulty())) + 1; // } // // if (Tradeitems.mTradeitems[i].cheapResource >= 0) { // if (this.specialResources == Tradeitems.mTradeitems[i].cheapResource) { // this.qty[i] = (this.qty[i] * 4) / 3; // } // } // // if (Tradeitems.mTradeitems[i].expensiveResource >= 0) { // if (this.specialResources == Tradeitems.mTradeitems[i].expensiveResource) { // this.qty[i] = (this.qty[i] * 3) >> 2; // } // } // // if (Tradeitems.mTradeitems[i].doublePriceStatus >= 0) { // if (this.status == Tradeitems.mTradeitems[i].doublePriceStatus) { // this.qty[i] = this.qty[i] / 5; // } // } // // this.qty[i] = this.qty[i] - rand.nextInt(10) + rand.nextInt(10); // // if (this.qty[i] < 0) { // this.qty[i] = 0; // } // } // } // }
import android.graphics.Typeface; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import de.anderdonau.spacetrader.DataTypes.CrewMember; import de.anderdonau.spacetrader.DataTypes.MyFragment; import de.anderdonau.spacetrader.DataTypes.SolarSystem;
/* * Copyright (c) 2014 Benjamin Schieder * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package de.anderdonau.spacetrader; public class FragmentAveragePrices extends MyFragment { View rootView; @SuppressWarnings("ConstantConditions") @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { this.gameState = (GameState) getArguments().getSerializable("gamestate"); rootView = inflater.inflate(R.layout.fragment_average_prices, container, false); update(); return rootView; } @Override public boolean update() {
// Path: SpaceTrader/src/main/java/de/anderdonau/spacetrader/DataTypes/CrewMember.java // public class CrewMember implements Serializable { // public int nameIndex; // public int pilot; // public int fighter; // public int trader; // public int engineer; // public int curSystem; // // public CrewMember() { // nameIndex = 1; // pilot = 1; // fighter = 1; // trader = 1; // engineer = 1; // curSystem = -1; // } // // public CrewMember(int nameIndex, int pilot, int fighter, int trader, int engineer, int curSystem) { // this.nameIndex = nameIndex; // this.pilot = pilot; // this.fighter = fighter; // this.trader = trader; // this.engineer = engineer; // this.curSystem = curSystem; // } // } // // Path: SpaceTrader/src/main/java/de/anderdonau/spacetrader/DataTypes/MyFragment.java // public class MyFragment extends Fragment { // public Main main = null; // public GameState gameState = null; // // @Override // public void onAttach(Activity activity) { // super.onAttach(activity); // this.main = (Main) activity; // } // // public boolean update() { // return false; // } // } // // Path: SpaceTrader/src/main/java/de/anderdonau/spacetrader/DataTypes/SolarSystem.java // public class SolarSystem implements Serializable { // public int nameIndex; // public int techLevel; // Tech level // public int politics; // Political system // public int status; // Status // public int x; // X-coordinate (galaxy width = 150) // public int y; // Y-coordinate (galaxy height = 100) // public int specialResources; // Special resources // public int size; // System size // public int[] qty = new int[GameState.MAXTRADEITEM]; // // Quantities of tradeitems. These change very slowly over time. // public int countDown; // Countdown for reset of tradeitems. // public boolean visited; // Visited Yes or No // public int special; // Special event // Random rand = new Random(); // // public void initializeTradeitems() { // int i; // // for (i = 0; i < GameState.MAXTRADEITEM; ++i) { // if (((i == GameState.NARCOTICS) && (!Politics.mPolitics[this.politics].drugsOK)) || // ((i == GameState.FIREARMS) && (!Politics.mPolitics[this.politics].firearmsOK)) || // (this.techLevel < Tradeitems.mTradeitems[i].techProduction)) { // this.qty[i] = 0; // continue; // } // // this.qty[i] = ((9 + rand.nextInt(5)) - Math.abs( // Tradeitems.mTradeitems[i].techTopProduction - this.techLevel)) * (1 + this.size); // // // Because of the enormous profits possible, there shouldn't be too many robots or narcotics available // if (i == GameState.ROBOTS || i == GameState.NARCOTICS) { // this.qty[i] = // ((this.qty[i] * (5 - GameState.getDifficulty())) / (6 - GameState.getDifficulty())) + 1; // } // // if (Tradeitems.mTradeitems[i].cheapResource >= 0) { // if (this.specialResources == Tradeitems.mTradeitems[i].cheapResource) { // this.qty[i] = (this.qty[i] * 4) / 3; // } // } // // if (Tradeitems.mTradeitems[i].expensiveResource >= 0) { // if (this.specialResources == Tradeitems.mTradeitems[i].expensiveResource) { // this.qty[i] = (this.qty[i] * 3) >> 2; // } // } // // if (Tradeitems.mTradeitems[i].doublePriceStatus >= 0) { // if (this.status == Tradeitems.mTradeitems[i].doublePriceStatus) { // this.qty[i] = this.qty[i] / 5; // } // } // // this.qty[i] = this.qty[i] - rand.nextInt(10) + rand.nextInt(10); // // if (this.qty[i] < 0) { // this.qty[i] = 0; // } // } // } // } // Path: SpaceTrader/src/main/java/de/anderdonau/spacetrader/FragmentAveragePrices.java import android.graphics.Typeface; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import de.anderdonau.spacetrader.DataTypes.CrewMember; import de.anderdonau.spacetrader.DataTypes.MyFragment; import de.anderdonau.spacetrader.DataTypes.SolarSystem; /* * Copyright (c) 2014 Benjamin Schieder * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package de.anderdonau.spacetrader; public class FragmentAveragePrices extends MyFragment { View rootView; @SuppressWarnings("ConstantConditions") @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { this.gameState = (GameState) getArguments().getSerializable("gamestate"); rootView = inflater.inflate(R.layout.fragment_average_prices, container, false); update(); return rootView; } @Override public boolean update() {
CrewMember COMMANDER = gameState.Mercenary[0];
blind-coder/SpaceTrader
SpaceTrader/src/main/java/de/anderdonau/spacetrader/FragmentAveragePrices.java
// Path: SpaceTrader/src/main/java/de/anderdonau/spacetrader/DataTypes/CrewMember.java // public class CrewMember implements Serializable { // public int nameIndex; // public int pilot; // public int fighter; // public int trader; // public int engineer; // public int curSystem; // // public CrewMember() { // nameIndex = 1; // pilot = 1; // fighter = 1; // trader = 1; // engineer = 1; // curSystem = -1; // } // // public CrewMember(int nameIndex, int pilot, int fighter, int trader, int engineer, int curSystem) { // this.nameIndex = nameIndex; // this.pilot = pilot; // this.fighter = fighter; // this.trader = trader; // this.engineer = engineer; // this.curSystem = curSystem; // } // } // // Path: SpaceTrader/src/main/java/de/anderdonau/spacetrader/DataTypes/MyFragment.java // public class MyFragment extends Fragment { // public Main main = null; // public GameState gameState = null; // // @Override // public void onAttach(Activity activity) { // super.onAttach(activity); // this.main = (Main) activity; // } // // public boolean update() { // return false; // } // } // // Path: SpaceTrader/src/main/java/de/anderdonau/spacetrader/DataTypes/SolarSystem.java // public class SolarSystem implements Serializable { // public int nameIndex; // public int techLevel; // Tech level // public int politics; // Political system // public int status; // Status // public int x; // X-coordinate (galaxy width = 150) // public int y; // Y-coordinate (galaxy height = 100) // public int specialResources; // Special resources // public int size; // System size // public int[] qty = new int[GameState.MAXTRADEITEM]; // // Quantities of tradeitems. These change very slowly over time. // public int countDown; // Countdown for reset of tradeitems. // public boolean visited; // Visited Yes or No // public int special; // Special event // Random rand = new Random(); // // public void initializeTradeitems() { // int i; // // for (i = 0; i < GameState.MAXTRADEITEM; ++i) { // if (((i == GameState.NARCOTICS) && (!Politics.mPolitics[this.politics].drugsOK)) || // ((i == GameState.FIREARMS) && (!Politics.mPolitics[this.politics].firearmsOK)) || // (this.techLevel < Tradeitems.mTradeitems[i].techProduction)) { // this.qty[i] = 0; // continue; // } // // this.qty[i] = ((9 + rand.nextInt(5)) - Math.abs( // Tradeitems.mTradeitems[i].techTopProduction - this.techLevel)) * (1 + this.size); // // // Because of the enormous profits possible, there shouldn't be too many robots or narcotics available // if (i == GameState.ROBOTS || i == GameState.NARCOTICS) { // this.qty[i] = // ((this.qty[i] * (5 - GameState.getDifficulty())) / (6 - GameState.getDifficulty())) + 1; // } // // if (Tradeitems.mTradeitems[i].cheapResource >= 0) { // if (this.specialResources == Tradeitems.mTradeitems[i].cheapResource) { // this.qty[i] = (this.qty[i] * 4) / 3; // } // } // // if (Tradeitems.mTradeitems[i].expensiveResource >= 0) { // if (this.specialResources == Tradeitems.mTradeitems[i].expensiveResource) { // this.qty[i] = (this.qty[i] * 3) >> 2; // } // } // // if (Tradeitems.mTradeitems[i].doublePriceStatus >= 0) { // if (this.status == Tradeitems.mTradeitems[i].doublePriceStatus) { // this.qty[i] = this.qty[i] / 5; // } // } // // this.qty[i] = this.qty[i] - rand.nextInt(10) + rand.nextInt(10); // // if (this.qty[i] < 0) { // this.qty[i] = 0; // } // } // } // }
import android.graphics.Typeface; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import de.anderdonau.spacetrader.DataTypes.CrewMember; import de.anderdonau.spacetrader.DataTypes.MyFragment; import de.anderdonau.spacetrader.DataTypes.SolarSystem;
/* * Copyright (c) 2014 Benjamin Schieder * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package de.anderdonau.spacetrader; public class FragmentAveragePrices extends MyFragment { View rootView; @SuppressWarnings("ConstantConditions") @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { this.gameState = (GameState) getArguments().getSerializable("gamestate"); rootView = inflater.inflate(R.layout.fragment_average_prices, container, false); update(); return rootView; } @Override public boolean update() { CrewMember COMMANDER = gameState.Mercenary[0];
// Path: SpaceTrader/src/main/java/de/anderdonau/spacetrader/DataTypes/CrewMember.java // public class CrewMember implements Serializable { // public int nameIndex; // public int pilot; // public int fighter; // public int trader; // public int engineer; // public int curSystem; // // public CrewMember() { // nameIndex = 1; // pilot = 1; // fighter = 1; // trader = 1; // engineer = 1; // curSystem = -1; // } // // public CrewMember(int nameIndex, int pilot, int fighter, int trader, int engineer, int curSystem) { // this.nameIndex = nameIndex; // this.pilot = pilot; // this.fighter = fighter; // this.trader = trader; // this.engineer = engineer; // this.curSystem = curSystem; // } // } // // Path: SpaceTrader/src/main/java/de/anderdonau/spacetrader/DataTypes/MyFragment.java // public class MyFragment extends Fragment { // public Main main = null; // public GameState gameState = null; // // @Override // public void onAttach(Activity activity) { // super.onAttach(activity); // this.main = (Main) activity; // } // // public boolean update() { // return false; // } // } // // Path: SpaceTrader/src/main/java/de/anderdonau/spacetrader/DataTypes/SolarSystem.java // public class SolarSystem implements Serializable { // public int nameIndex; // public int techLevel; // Tech level // public int politics; // Political system // public int status; // Status // public int x; // X-coordinate (galaxy width = 150) // public int y; // Y-coordinate (galaxy height = 100) // public int specialResources; // Special resources // public int size; // System size // public int[] qty = new int[GameState.MAXTRADEITEM]; // // Quantities of tradeitems. These change very slowly over time. // public int countDown; // Countdown for reset of tradeitems. // public boolean visited; // Visited Yes or No // public int special; // Special event // Random rand = new Random(); // // public void initializeTradeitems() { // int i; // // for (i = 0; i < GameState.MAXTRADEITEM; ++i) { // if (((i == GameState.NARCOTICS) && (!Politics.mPolitics[this.politics].drugsOK)) || // ((i == GameState.FIREARMS) && (!Politics.mPolitics[this.politics].firearmsOK)) || // (this.techLevel < Tradeitems.mTradeitems[i].techProduction)) { // this.qty[i] = 0; // continue; // } // // this.qty[i] = ((9 + rand.nextInt(5)) - Math.abs( // Tradeitems.mTradeitems[i].techTopProduction - this.techLevel)) * (1 + this.size); // // // Because of the enormous profits possible, there shouldn't be too many robots or narcotics available // if (i == GameState.ROBOTS || i == GameState.NARCOTICS) { // this.qty[i] = // ((this.qty[i] * (5 - GameState.getDifficulty())) / (6 - GameState.getDifficulty())) + 1; // } // // if (Tradeitems.mTradeitems[i].cheapResource >= 0) { // if (this.specialResources == Tradeitems.mTradeitems[i].cheapResource) { // this.qty[i] = (this.qty[i] * 4) / 3; // } // } // // if (Tradeitems.mTradeitems[i].expensiveResource >= 0) { // if (this.specialResources == Tradeitems.mTradeitems[i].expensiveResource) { // this.qty[i] = (this.qty[i] * 3) >> 2; // } // } // // if (Tradeitems.mTradeitems[i].doublePriceStatus >= 0) { // if (this.status == Tradeitems.mTradeitems[i].doublePriceStatus) { // this.qty[i] = this.qty[i] / 5; // } // } // // this.qty[i] = this.qty[i] - rand.nextInt(10) + rand.nextInt(10); // // if (this.qty[i] < 0) { // this.qty[i] = 0; // } // } // } // } // Path: SpaceTrader/src/main/java/de/anderdonau/spacetrader/FragmentAveragePrices.java import android.graphics.Typeface; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import de.anderdonau.spacetrader.DataTypes.CrewMember; import de.anderdonau.spacetrader.DataTypes.MyFragment; import de.anderdonau.spacetrader.DataTypes.SolarSystem; /* * Copyright (c) 2014 Benjamin Schieder * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package de.anderdonau.spacetrader; public class FragmentAveragePrices extends MyFragment { View rootView; @SuppressWarnings("ConstantConditions") @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { this.gameState = (GameState) getArguments().getSerializable("gamestate"); rootView = inflater.inflate(R.layout.fragment_average_prices, container, false); update(); return rootView; } @Override public boolean update() { CrewMember COMMANDER = gameState.Mercenary[0];
SolarSystem CURSYSTEM = gameState.SolarSystem[COMMANDER.curSystem];
blind-coder/SpaceTrader
SpaceTrader/src/main/java/de/anderdonau/spacetrader/FragmentShortcuts.java
// Path: SpaceTrader/src/main/java/de/anderdonau/spacetrader/DataTypes/MyFragment.java // public class MyFragment extends Fragment { // public Main main = null; // public GameState gameState = null; // // @Override // public void onAttach(Activity activity) { // super.onAttach(activity); // this.main = (Main) activity; // } // // public boolean update() { // return false; // } // } // // Path: SpaceTrader/src/main/java/de/anderdonau/spacetrader/DataTypes/ShortcutArrayAdapter.java // public class ShortcutArrayAdapter extends ArrayAdapter<String> { // private Main main; // private final String[] values; // private final GameState gameState; // // public ShortcutArrayAdapter(Main main, String[] values, GameState gameState) { // super(main, R.layout.listview_shortcut_entry, values); // this.main = main; // this.values = values; // this.gameState = gameState; // } // // @Override // public View getView(int position, View convertView, ViewGroup parent) { // LayoutInflater inflater = (LayoutInflater) main.getSystemService( // Context.LAYOUT_INFLATER_SERVICE); // // View rowView = inflater.inflate(R.layout.listview_shortcut_entry, parent, false); // //noinspection ConstantConditions // TextView textView = (TextView) rowView.findViewById(R.id.txtShortcut); // TextView textView1 = (TextView) rowView.findViewById(R.id.txtTarget); // textView.setText(values[position]); // // int i = position == 0 ? gameState.Shortcut1 : position == 1 ? gameState.Shortcut2 : // position == 2 ? gameState.Shortcut3 : gameState.Shortcut4; // String s = main.Shortcuts[i][1]; // textView1.setText(s); // // return rowView; // } // }
import android.app.AlertDialog; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Button; import android.widget.LinearLayout; import android.widget.ListView; import de.anderdonau.spacetrader.DataTypes.MyFragment; import de.anderdonau.spacetrader.DataTypes.ShortcutArrayAdapter;
/* * Copyright (c) 2014 Benjamin Schieder * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package de.anderdonau.spacetrader; public class FragmentShortcuts extends MyFragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //noinspection ConstantConditions this.gameState = (GameState) getArguments().getSerializable("gamestate"); final View rootView = inflater.inflate(R.layout.fragment_shortcuts, container, false); //noinspection ConstantConditions final ListView listView = (ListView) rootView.findViewById(R.id.listView); String[] values = {"Shortcut 1", "Shortcut 2", "Shortcut 3", "Shortcut 4"};
// Path: SpaceTrader/src/main/java/de/anderdonau/spacetrader/DataTypes/MyFragment.java // public class MyFragment extends Fragment { // public Main main = null; // public GameState gameState = null; // // @Override // public void onAttach(Activity activity) { // super.onAttach(activity); // this.main = (Main) activity; // } // // public boolean update() { // return false; // } // } // // Path: SpaceTrader/src/main/java/de/anderdonau/spacetrader/DataTypes/ShortcutArrayAdapter.java // public class ShortcutArrayAdapter extends ArrayAdapter<String> { // private Main main; // private final String[] values; // private final GameState gameState; // // public ShortcutArrayAdapter(Main main, String[] values, GameState gameState) { // super(main, R.layout.listview_shortcut_entry, values); // this.main = main; // this.values = values; // this.gameState = gameState; // } // // @Override // public View getView(int position, View convertView, ViewGroup parent) { // LayoutInflater inflater = (LayoutInflater) main.getSystemService( // Context.LAYOUT_INFLATER_SERVICE); // // View rowView = inflater.inflate(R.layout.listview_shortcut_entry, parent, false); // //noinspection ConstantConditions // TextView textView = (TextView) rowView.findViewById(R.id.txtShortcut); // TextView textView1 = (TextView) rowView.findViewById(R.id.txtTarget); // textView.setText(values[position]); // // int i = position == 0 ? gameState.Shortcut1 : position == 1 ? gameState.Shortcut2 : // position == 2 ? gameState.Shortcut3 : gameState.Shortcut4; // String s = main.Shortcuts[i][1]; // textView1.setText(s); // // return rowView; // } // } // Path: SpaceTrader/src/main/java/de/anderdonau/spacetrader/FragmentShortcuts.java import android.app.AlertDialog; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Button; import android.widget.LinearLayout; import android.widget.ListView; import de.anderdonau.spacetrader.DataTypes.MyFragment; import de.anderdonau.spacetrader.DataTypes.ShortcutArrayAdapter; /* * Copyright (c) 2014 Benjamin Schieder * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package de.anderdonau.spacetrader; public class FragmentShortcuts extends MyFragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //noinspection ConstantConditions this.gameState = (GameState) getArguments().getSerializable("gamestate"); final View rootView = inflater.inflate(R.layout.fragment_shortcuts, container, false); //noinspection ConstantConditions final ListView listView = (ListView) rootView.findViewById(R.id.listView); String[] values = {"Shortcut 1", "Shortcut 2", "Shortcut 3", "Shortcut 4"};
listView.setAdapter(new ShortcutArrayAdapter(main, values, gameState));
blind-coder/SpaceTrader
SpaceTrader/src/main/java/de/anderdonau/spacetrader/NavigationChart.java
// Path: SpaceTrader/src/main/java/de/anderdonau/spacetrader/DataTypes/SolarSystem.java // public class SolarSystem implements Serializable { // public int nameIndex; // public int techLevel; // Tech level // public int politics; // Political system // public int status; // Status // public int x; // X-coordinate (galaxy width = 150) // public int y; // Y-coordinate (galaxy height = 100) // public int specialResources; // Special resources // public int size; // System size // public int[] qty = new int[GameState.MAXTRADEITEM]; // // Quantities of tradeitems. These change very slowly over time. // public int countDown; // Countdown for reset of tradeitems. // public boolean visited; // Visited Yes or No // public int special; // Special event // Random rand = new Random(); // // public void initializeTradeitems() { // int i; // // for (i = 0; i < GameState.MAXTRADEITEM; ++i) { // if (((i == GameState.NARCOTICS) && (!Politics.mPolitics[this.politics].drugsOK)) || // ((i == GameState.FIREARMS) && (!Politics.mPolitics[this.politics].firearmsOK)) || // (this.techLevel < Tradeitems.mTradeitems[i].techProduction)) { // this.qty[i] = 0; // continue; // } // // this.qty[i] = ((9 + rand.nextInt(5)) - Math.abs( // Tradeitems.mTradeitems[i].techTopProduction - this.techLevel)) * (1 + this.size); // // // Because of the enormous profits possible, there shouldn't be too many robots or narcotics available // if (i == GameState.ROBOTS || i == GameState.NARCOTICS) { // this.qty[i] = // ((this.qty[i] * (5 - GameState.getDifficulty())) / (6 - GameState.getDifficulty())) + 1; // } // // if (Tradeitems.mTradeitems[i].cheapResource >= 0) { // if (this.specialResources == Tradeitems.mTradeitems[i].cheapResource) { // this.qty[i] = (this.qty[i] * 4) / 3; // } // } // // if (Tradeitems.mTradeitems[i].expensiveResource >= 0) { // if (this.specialResources == Tradeitems.mTradeitems[i].expensiveResource) { // this.qty[i] = (this.qty[i] * 3) >> 2; // } // } // // if (Tradeitems.mTradeitems[i].doublePriceStatus >= 0) { // if (this.status == Tradeitems.mTradeitems[i].doublePriceStatus) { // this.qty[i] = this.qty[i] / 5; // } // } // // this.qty[i] = this.qty[i] - rand.nextInt(10) + rand.nextInt(10); // // if (this.qty[i] < 0) { // this.qty[i] = 0; // } // } // } // }
import de.anderdonau.spacetrader.DataTypes.SolarSystem; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View;
} public NavigationChart(Context context, AttributeSet attrs) { super(context, attrs); } public NavigationChart(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public void setGameState(GameState mGameState) { this.mGameState = mGameState; } @SuppressWarnings("ConstantConditions") public void setMain(Main main) { this.main = main; TypedArray themeArray = main.getTheme().obtainStyledAttributes( new int[]{R.attr.navChartDrawColor}); int index = 0; int defaultColourValue = Color.BLACK; this.textColor = themeArray.getColor(index, defaultColourValue); } public void setShortRange(boolean isShortRange) { this.isShortRange = isShortRange; } public int getSystemAt(float posX, float posY) { for (int i = 0; i < GameState.MAXSOLARSYSTEM; i++) {
// Path: SpaceTrader/src/main/java/de/anderdonau/spacetrader/DataTypes/SolarSystem.java // public class SolarSystem implements Serializable { // public int nameIndex; // public int techLevel; // Tech level // public int politics; // Political system // public int status; // Status // public int x; // X-coordinate (galaxy width = 150) // public int y; // Y-coordinate (galaxy height = 100) // public int specialResources; // Special resources // public int size; // System size // public int[] qty = new int[GameState.MAXTRADEITEM]; // // Quantities of tradeitems. These change very slowly over time. // public int countDown; // Countdown for reset of tradeitems. // public boolean visited; // Visited Yes or No // public int special; // Special event // Random rand = new Random(); // // public void initializeTradeitems() { // int i; // // for (i = 0; i < GameState.MAXTRADEITEM; ++i) { // if (((i == GameState.NARCOTICS) && (!Politics.mPolitics[this.politics].drugsOK)) || // ((i == GameState.FIREARMS) && (!Politics.mPolitics[this.politics].firearmsOK)) || // (this.techLevel < Tradeitems.mTradeitems[i].techProduction)) { // this.qty[i] = 0; // continue; // } // // this.qty[i] = ((9 + rand.nextInt(5)) - Math.abs( // Tradeitems.mTradeitems[i].techTopProduction - this.techLevel)) * (1 + this.size); // // // Because of the enormous profits possible, there shouldn't be too many robots or narcotics available // if (i == GameState.ROBOTS || i == GameState.NARCOTICS) { // this.qty[i] = // ((this.qty[i] * (5 - GameState.getDifficulty())) / (6 - GameState.getDifficulty())) + 1; // } // // if (Tradeitems.mTradeitems[i].cheapResource >= 0) { // if (this.specialResources == Tradeitems.mTradeitems[i].cheapResource) { // this.qty[i] = (this.qty[i] * 4) / 3; // } // } // // if (Tradeitems.mTradeitems[i].expensiveResource >= 0) { // if (this.specialResources == Tradeitems.mTradeitems[i].expensiveResource) { // this.qty[i] = (this.qty[i] * 3) >> 2; // } // } // // if (Tradeitems.mTradeitems[i].doublePriceStatus >= 0) { // if (this.status == Tradeitems.mTradeitems[i].doublePriceStatus) { // this.qty[i] = this.qty[i] / 5; // } // } // // this.qty[i] = this.qty[i] - rand.nextInt(10) + rand.nextInt(10); // // if (this.qty[i] < 0) { // this.qty[i] = 0; // } // } // } // } // Path: SpaceTrader/src/main/java/de/anderdonau/spacetrader/NavigationChart.java import de.anderdonau.spacetrader.DataTypes.SolarSystem; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; } public NavigationChart(Context context, AttributeSet attrs) { super(context, attrs); } public NavigationChart(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public void setGameState(GameState mGameState) { this.mGameState = mGameState; } @SuppressWarnings("ConstantConditions") public void setMain(Main main) { this.main = main; TypedArray themeArray = main.getTheme().obtainStyledAttributes( new int[]{R.attr.navChartDrawColor}); int index = 0; int defaultColourValue = Color.BLACK; this.textColor = themeArray.getColor(index, defaultColourValue); } public void setShortRange(boolean isShortRange) { this.isShortRange = isShortRange; } public int getSystemAt(float posX, float posY) { for (int i = 0; i < GameState.MAXSOLARSYSTEM; i++) {
SolarSystem s = mGameState.SolarSystem[i];
blind-coder/SpaceTrader
SpaceTrader/src/main/java/de/anderdonau/spacetrader/FragmentBuyCargo.java
// Path: SpaceTrader/src/main/java/de/anderdonau/spacetrader/DataTypes/CrewMember.java // public class CrewMember implements Serializable { // public int nameIndex; // public int pilot; // public int fighter; // public int trader; // public int engineer; // public int curSystem; // // public CrewMember() { // nameIndex = 1; // pilot = 1; // fighter = 1; // trader = 1; // engineer = 1; // curSystem = -1; // } // // public CrewMember(int nameIndex, int pilot, int fighter, int trader, int engineer, int curSystem) { // this.nameIndex = nameIndex; // this.pilot = pilot; // this.fighter = fighter; // this.trader = trader; // this.engineer = engineer; // this.curSystem = curSystem; // } // } // // Path: SpaceTrader/src/main/java/de/anderdonau/spacetrader/DataTypes/MyFragment.java // public class MyFragment extends Fragment { // public Main main = null; // public GameState gameState = null; // // @Override // public void onAttach(Activity activity) { // super.onAttach(activity); // this.main = (Main) activity; // } // // public boolean update() { // return false; // } // } // // Path: SpaceTrader/src/main/java/de/anderdonau/spacetrader/DataTypes/SolarSystem.java // public class SolarSystem implements Serializable { // public int nameIndex; // public int techLevel; // Tech level // public int politics; // Political system // public int status; // Status // public int x; // X-coordinate (galaxy width = 150) // public int y; // Y-coordinate (galaxy height = 100) // public int specialResources; // Special resources // public int size; // System size // public int[] qty = new int[GameState.MAXTRADEITEM]; // // Quantities of tradeitems. These change very slowly over time. // public int countDown; // Countdown for reset of tradeitems. // public boolean visited; // Visited Yes or No // public int special; // Special event // Random rand = new Random(); // // public void initializeTradeitems() { // int i; // // for (i = 0; i < GameState.MAXTRADEITEM; ++i) { // if (((i == GameState.NARCOTICS) && (!Politics.mPolitics[this.politics].drugsOK)) || // ((i == GameState.FIREARMS) && (!Politics.mPolitics[this.politics].firearmsOK)) || // (this.techLevel < Tradeitems.mTradeitems[i].techProduction)) { // this.qty[i] = 0; // continue; // } // // this.qty[i] = ((9 + rand.nextInt(5)) - Math.abs( // Tradeitems.mTradeitems[i].techTopProduction - this.techLevel)) * (1 + this.size); // // // Because of the enormous profits possible, there shouldn't be too many robots or narcotics available // if (i == GameState.ROBOTS || i == GameState.NARCOTICS) { // this.qty[i] = // ((this.qty[i] * (5 - GameState.getDifficulty())) / (6 - GameState.getDifficulty())) + 1; // } // // if (Tradeitems.mTradeitems[i].cheapResource >= 0) { // if (this.specialResources == Tradeitems.mTradeitems[i].cheapResource) { // this.qty[i] = (this.qty[i] * 4) / 3; // } // } // // if (Tradeitems.mTradeitems[i].expensiveResource >= 0) { // if (this.specialResources == Tradeitems.mTradeitems[i].expensiveResource) { // this.qty[i] = (this.qty[i] * 3) >> 2; // } // } // // if (Tradeitems.mTradeitems[i].doublePriceStatus >= 0) { // if (this.status == Tradeitems.mTradeitems[i].doublePriceStatus) { // this.qty[i] = this.qty[i] / 5; // } // } // // this.qty[i] = this.qty[i] - rand.nextInt(10) + rand.nextInt(10); // // if (this.qty[i] < 0) { // this.qty[i] = 0; // } // } // } // }
import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import de.anderdonau.spacetrader.DataTypes.CrewMember; import de.anderdonau.spacetrader.DataTypes.MyFragment; import de.anderdonau.spacetrader.DataTypes.SolarSystem;
/* * Copyright (c) 2014 Benjamin Schieder * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package de.anderdonau.spacetrader; public class FragmentBuyCargo extends MyFragment { View rootView; @SuppressWarnings("ConstantConditions") @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { this.gameState = (GameState) getArguments().getSerializable("gamestate"); rootView = inflater.inflate(R.layout.fragment_buy_cargo, container, false); update(); return rootView; } @Override public boolean update() {
// Path: SpaceTrader/src/main/java/de/anderdonau/spacetrader/DataTypes/CrewMember.java // public class CrewMember implements Serializable { // public int nameIndex; // public int pilot; // public int fighter; // public int trader; // public int engineer; // public int curSystem; // // public CrewMember() { // nameIndex = 1; // pilot = 1; // fighter = 1; // trader = 1; // engineer = 1; // curSystem = -1; // } // // public CrewMember(int nameIndex, int pilot, int fighter, int trader, int engineer, int curSystem) { // this.nameIndex = nameIndex; // this.pilot = pilot; // this.fighter = fighter; // this.trader = trader; // this.engineer = engineer; // this.curSystem = curSystem; // } // } // // Path: SpaceTrader/src/main/java/de/anderdonau/spacetrader/DataTypes/MyFragment.java // public class MyFragment extends Fragment { // public Main main = null; // public GameState gameState = null; // // @Override // public void onAttach(Activity activity) { // super.onAttach(activity); // this.main = (Main) activity; // } // // public boolean update() { // return false; // } // } // // Path: SpaceTrader/src/main/java/de/anderdonau/spacetrader/DataTypes/SolarSystem.java // public class SolarSystem implements Serializable { // public int nameIndex; // public int techLevel; // Tech level // public int politics; // Political system // public int status; // Status // public int x; // X-coordinate (galaxy width = 150) // public int y; // Y-coordinate (galaxy height = 100) // public int specialResources; // Special resources // public int size; // System size // public int[] qty = new int[GameState.MAXTRADEITEM]; // // Quantities of tradeitems. These change very slowly over time. // public int countDown; // Countdown for reset of tradeitems. // public boolean visited; // Visited Yes or No // public int special; // Special event // Random rand = new Random(); // // public void initializeTradeitems() { // int i; // // for (i = 0; i < GameState.MAXTRADEITEM; ++i) { // if (((i == GameState.NARCOTICS) && (!Politics.mPolitics[this.politics].drugsOK)) || // ((i == GameState.FIREARMS) && (!Politics.mPolitics[this.politics].firearmsOK)) || // (this.techLevel < Tradeitems.mTradeitems[i].techProduction)) { // this.qty[i] = 0; // continue; // } // // this.qty[i] = ((9 + rand.nextInt(5)) - Math.abs( // Tradeitems.mTradeitems[i].techTopProduction - this.techLevel)) * (1 + this.size); // // // Because of the enormous profits possible, there shouldn't be too many robots or narcotics available // if (i == GameState.ROBOTS || i == GameState.NARCOTICS) { // this.qty[i] = // ((this.qty[i] * (5 - GameState.getDifficulty())) / (6 - GameState.getDifficulty())) + 1; // } // // if (Tradeitems.mTradeitems[i].cheapResource >= 0) { // if (this.specialResources == Tradeitems.mTradeitems[i].cheapResource) { // this.qty[i] = (this.qty[i] * 4) / 3; // } // } // // if (Tradeitems.mTradeitems[i].expensiveResource >= 0) { // if (this.specialResources == Tradeitems.mTradeitems[i].expensiveResource) { // this.qty[i] = (this.qty[i] * 3) >> 2; // } // } // // if (Tradeitems.mTradeitems[i].doublePriceStatus >= 0) { // if (this.status == Tradeitems.mTradeitems[i].doublePriceStatus) { // this.qty[i] = this.qty[i] / 5; // } // } // // this.qty[i] = this.qty[i] - rand.nextInt(10) + rand.nextInt(10); // // if (this.qty[i] < 0) { // this.qty[i] = 0; // } // } // } // } // Path: SpaceTrader/src/main/java/de/anderdonau/spacetrader/FragmentBuyCargo.java import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import de.anderdonau.spacetrader.DataTypes.CrewMember; import de.anderdonau.spacetrader.DataTypes.MyFragment; import de.anderdonau.spacetrader.DataTypes.SolarSystem; /* * Copyright (c) 2014 Benjamin Schieder * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package de.anderdonau.spacetrader; public class FragmentBuyCargo extends MyFragment { View rootView; @SuppressWarnings("ConstantConditions") @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { this.gameState = (GameState) getArguments().getSerializable("gamestate"); rootView = inflater.inflate(R.layout.fragment_buy_cargo, container, false); update(); return rootView; } @Override public boolean update() {
CrewMember COMMANDER;
blind-coder/SpaceTrader
SpaceTrader/src/main/java/de/anderdonau/spacetrader/FragmentBuyCargo.java
// Path: SpaceTrader/src/main/java/de/anderdonau/spacetrader/DataTypes/CrewMember.java // public class CrewMember implements Serializable { // public int nameIndex; // public int pilot; // public int fighter; // public int trader; // public int engineer; // public int curSystem; // // public CrewMember() { // nameIndex = 1; // pilot = 1; // fighter = 1; // trader = 1; // engineer = 1; // curSystem = -1; // } // // public CrewMember(int nameIndex, int pilot, int fighter, int trader, int engineer, int curSystem) { // this.nameIndex = nameIndex; // this.pilot = pilot; // this.fighter = fighter; // this.trader = trader; // this.engineer = engineer; // this.curSystem = curSystem; // } // } // // Path: SpaceTrader/src/main/java/de/anderdonau/spacetrader/DataTypes/MyFragment.java // public class MyFragment extends Fragment { // public Main main = null; // public GameState gameState = null; // // @Override // public void onAttach(Activity activity) { // super.onAttach(activity); // this.main = (Main) activity; // } // // public boolean update() { // return false; // } // } // // Path: SpaceTrader/src/main/java/de/anderdonau/spacetrader/DataTypes/SolarSystem.java // public class SolarSystem implements Serializable { // public int nameIndex; // public int techLevel; // Tech level // public int politics; // Political system // public int status; // Status // public int x; // X-coordinate (galaxy width = 150) // public int y; // Y-coordinate (galaxy height = 100) // public int specialResources; // Special resources // public int size; // System size // public int[] qty = new int[GameState.MAXTRADEITEM]; // // Quantities of tradeitems. These change very slowly over time. // public int countDown; // Countdown for reset of tradeitems. // public boolean visited; // Visited Yes or No // public int special; // Special event // Random rand = new Random(); // // public void initializeTradeitems() { // int i; // // for (i = 0; i < GameState.MAXTRADEITEM; ++i) { // if (((i == GameState.NARCOTICS) && (!Politics.mPolitics[this.politics].drugsOK)) || // ((i == GameState.FIREARMS) && (!Politics.mPolitics[this.politics].firearmsOK)) || // (this.techLevel < Tradeitems.mTradeitems[i].techProduction)) { // this.qty[i] = 0; // continue; // } // // this.qty[i] = ((9 + rand.nextInt(5)) - Math.abs( // Tradeitems.mTradeitems[i].techTopProduction - this.techLevel)) * (1 + this.size); // // // Because of the enormous profits possible, there shouldn't be too many robots or narcotics available // if (i == GameState.ROBOTS || i == GameState.NARCOTICS) { // this.qty[i] = // ((this.qty[i] * (5 - GameState.getDifficulty())) / (6 - GameState.getDifficulty())) + 1; // } // // if (Tradeitems.mTradeitems[i].cheapResource >= 0) { // if (this.specialResources == Tradeitems.mTradeitems[i].cheapResource) { // this.qty[i] = (this.qty[i] * 4) / 3; // } // } // // if (Tradeitems.mTradeitems[i].expensiveResource >= 0) { // if (this.specialResources == Tradeitems.mTradeitems[i].expensiveResource) { // this.qty[i] = (this.qty[i] * 3) >> 2; // } // } // // if (Tradeitems.mTradeitems[i].doublePriceStatus >= 0) { // if (this.status == Tradeitems.mTradeitems[i].doublePriceStatus) { // this.qty[i] = this.qty[i] / 5; // } // } // // this.qty[i] = this.qty[i] - rand.nextInt(10) + rand.nextInt(10); // // if (this.qty[i] < 0) { // this.qty[i] = 0; // } // } // } // }
import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import de.anderdonau.spacetrader.DataTypes.CrewMember; import de.anderdonau.spacetrader.DataTypes.MyFragment; import de.anderdonau.spacetrader.DataTypes.SolarSystem;
/* * Copyright (c) 2014 Benjamin Schieder * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package de.anderdonau.spacetrader; public class FragmentBuyCargo extends MyFragment { View rootView; @SuppressWarnings("ConstantConditions") @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { this.gameState = (GameState) getArguments().getSerializable("gamestate"); rootView = inflater.inflate(R.layout.fragment_buy_cargo, container, false); update(); return rootView; } @Override public boolean update() { CrewMember COMMANDER;
// Path: SpaceTrader/src/main/java/de/anderdonau/spacetrader/DataTypes/CrewMember.java // public class CrewMember implements Serializable { // public int nameIndex; // public int pilot; // public int fighter; // public int trader; // public int engineer; // public int curSystem; // // public CrewMember() { // nameIndex = 1; // pilot = 1; // fighter = 1; // trader = 1; // engineer = 1; // curSystem = -1; // } // // public CrewMember(int nameIndex, int pilot, int fighter, int trader, int engineer, int curSystem) { // this.nameIndex = nameIndex; // this.pilot = pilot; // this.fighter = fighter; // this.trader = trader; // this.engineer = engineer; // this.curSystem = curSystem; // } // } // // Path: SpaceTrader/src/main/java/de/anderdonau/spacetrader/DataTypes/MyFragment.java // public class MyFragment extends Fragment { // public Main main = null; // public GameState gameState = null; // // @Override // public void onAttach(Activity activity) { // super.onAttach(activity); // this.main = (Main) activity; // } // // public boolean update() { // return false; // } // } // // Path: SpaceTrader/src/main/java/de/anderdonau/spacetrader/DataTypes/SolarSystem.java // public class SolarSystem implements Serializable { // public int nameIndex; // public int techLevel; // Tech level // public int politics; // Political system // public int status; // Status // public int x; // X-coordinate (galaxy width = 150) // public int y; // Y-coordinate (galaxy height = 100) // public int specialResources; // Special resources // public int size; // System size // public int[] qty = new int[GameState.MAXTRADEITEM]; // // Quantities of tradeitems. These change very slowly over time. // public int countDown; // Countdown for reset of tradeitems. // public boolean visited; // Visited Yes or No // public int special; // Special event // Random rand = new Random(); // // public void initializeTradeitems() { // int i; // // for (i = 0; i < GameState.MAXTRADEITEM; ++i) { // if (((i == GameState.NARCOTICS) && (!Politics.mPolitics[this.politics].drugsOK)) || // ((i == GameState.FIREARMS) && (!Politics.mPolitics[this.politics].firearmsOK)) || // (this.techLevel < Tradeitems.mTradeitems[i].techProduction)) { // this.qty[i] = 0; // continue; // } // // this.qty[i] = ((9 + rand.nextInt(5)) - Math.abs( // Tradeitems.mTradeitems[i].techTopProduction - this.techLevel)) * (1 + this.size); // // // Because of the enormous profits possible, there shouldn't be too many robots or narcotics available // if (i == GameState.ROBOTS || i == GameState.NARCOTICS) { // this.qty[i] = // ((this.qty[i] * (5 - GameState.getDifficulty())) / (6 - GameState.getDifficulty())) + 1; // } // // if (Tradeitems.mTradeitems[i].cheapResource >= 0) { // if (this.specialResources == Tradeitems.mTradeitems[i].cheapResource) { // this.qty[i] = (this.qty[i] * 4) / 3; // } // } // // if (Tradeitems.mTradeitems[i].expensiveResource >= 0) { // if (this.specialResources == Tradeitems.mTradeitems[i].expensiveResource) { // this.qty[i] = (this.qty[i] * 3) >> 2; // } // } // // if (Tradeitems.mTradeitems[i].doublePriceStatus >= 0) { // if (this.status == Tradeitems.mTradeitems[i].doublePriceStatus) { // this.qty[i] = this.qty[i] / 5; // } // } // // this.qty[i] = this.qty[i] - rand.nextInt(10) + rand.nextInt(10); // // if (this.qty[i] < 0) { // this.qty[i] = 0; // } // } // } // } // Path: SpaceTrader/src/main/java/de/anderdonau/spacetrader/FragmentBuyCargo.java import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import de.anderdonau.spacetrader.DataTypes.CrewMember; import de.anderdonau.spacetrader.DataTypes.MyFragment; import de.anderdonau.spacetrader.DataTypes.SolarSystem; /* * Copyright (c) 2014 Benjamin Schieder * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package de.anderdonau.spacetrader; public class FragmentBuyCargo extends MyFragment { View rootView; @SuppressWarnings("ConstantConditions") @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { this.gameState = (GameState) getArguments().getSerializable("gamestate"); rootView = inflater.inflate(R.layout.fragment_buy_cargo, container, false); update(); return rootView; } @Override public boolean update() { CrewMember COMMANDER;
SolarSystem CURSYSTEM;
jesuino/livro-javafx-pratico
codigo/javafx-pratico/src/main/java/javafxpratico/AprendendoTransicoes.java
// Path: codigo/javafx-pratico/src/main/java/javafxpratico/AprendendoTransicoes.java // public static enum Transicoes { // FADE, TRANSLATE, SCALE, FILL, ROTATE // }
import java.util.stream.Stream; import javafx.animation.Animation.Status; import javafx.animation.FadeTransition; import javafx.animation.FillTransition; import javafx.animation.RotateTransition; import javafx.animation.ScaleTransition; import javafx.animation.Transition; import javafx.animation.TranslateTransition; import javafx.application.Application; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.Slider; import javafx.scene.control.ToggleButton; import javafx.scene.control.ToggleGroup; import javafx.scene.effect.Reflection; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.paint.Color; import javafx.scene.shape.Shape; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.stage.Stage; import javafx.util.Duration; import javafxpratico.AprendendoTransicoes.FabricaTransicao.Transicoes;
HBox hbInferior = criaPainelInferior(); BorderPane.setMargin(hbInferior, new Insets(10)); raiz.setBottom(hbInferior); raiz.setCenter(alvo); criaNoAlvo(); Scene cena = new Scene(raiz, 800, 600); palco.setTitle("Testando Transições do JavaFX"); palco.setScene(cena); palco.show(); } private void criaNoAlvo() { // configurar coisas do texto alvo... alvo = new Text("** Transições **"); alvo.setFont(new Font(60)); // efeitinsss Reflection efeito = new Reflection(); efeito.setFraction(0.7); alvo.setEffect(efeito); alvo.setFill(Color.RED); raiz.setCenter(alvo); } private HBox criaPainelSuperior() { HBox hbTopo = new HBox(10); hbTopo.setSpacing(10); hbTopo.setAlignment(Pos.CENTER);
// Path: codigo/javafx-pratico/src/main/java/javafxpratico/AprendendoTransicoes.java // public static enum Transicoes { // FADE, TRANSLATE, SCALE, FILL, ROTATE // } // Path: codigo/javafx-pratico/src/main/java/javafxpratico/AprendendoTransicoes.java import java.util.stream.Stream; import javafx.animation.Animation.Status; import javafx.animation.FadeTransition; import javafx.animation.FillTransition; import javafx.animation.RotateTransition; import javafx.animation.ScaleTransition; import javafx.animation.Transition; import javafx.animation.TranslateTransition; import javafx.application.Application; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.Slider; import javafx.scene.control.ToggleButton; import javafx.scene.control.ToggleGroup; import javafx.scene.effect.Reflection; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.paint.Color; import javafx.scene.shape.Shape; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.stage.Stage; import javafx.util.Duration; import javafxpratico.AprendendoTransicoes.FabricaTransicao.Transicoes; HBox hbInferior = criaPainelInferior(); BorderPane.setMargin(hbInferior, new Insets(10)); raiz.setBottom(hbInferior); raiz.setCenter(alvo); criaNoAlvo(); Scene cena = new Scene(raiz, 800, 600); palco.setTitle("Testando Transições do JavaFX"); palco.setScene(cena); palco.show(); } private void criaNoAlvo() { // configurar coisas do texto alvo... alvo = new Text("** Transições **"); alvo.setFont(new Font(60)); // efeitinsss Reflection efeito = new Reflection(); efeito.setFraction(0.7); alvo.setEffect(efeito); alvo.setFill(Color.RED); raiz.setCenter(alvo); } private HBox criaPainelSuperior() { HBox hbTopo = new HBox(10); hbTopo.setSpacing(10); hbTopo.setAlignment(Pos.CENTER);
Transicoes[] transicoes = Transicoes.values();
jesuino/livro-javafx-pratico
codigo/javafx-pratico/src/main/java/javafxpratico/crud/service/impl/ContasCSVService.java
// Path: codigo/javafx-pratico/src/main/java/javafxpratico/crud/model/Conta.java // public class Conta { // // private int id; // private String concessionaria; // private String descricao; // private Date dataVencimento; // // // gets e sets // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getConcessionaria() { // return concessionaria; // } // // public void setConcessionaria(String concessionaria) { // this.concessionaria = concessionaria; // } // // public String getDescricao() { // return descricao; // } // // public void setDescricao(String descricao) { // this.descricao = descricao; // } // // public Date getDataVencimento() { // return dataVencimento; // } // // public void setDataVencimento(Date dataVencimento) { // this.dataVencimento = dataVencimento; // } // // } // // Path: codigo/javafx-pratico/src/main/java/javafxpratico/crud/service/ContasService.java // public interface ContasService { // // // CREATE // public void salvar(Conta conta); // // // RETRIEVE // public List<Conta> buscarTodas(); // // public Conta buscaPorId(int id); // // // DELETE // public void apagar(int id); // // // UPDATE // public void atualizar(Conta conta); // // // // retorna a implementação que escolhemos - no nosso caso o ContasCSVService, // // mas poderia ser outro, como ContasDBService... // public static ContasService getNewInstance() { // return new ContasCSVService(); // } // // }
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.stream.Collectors; import javafxpratico.crud.model.Conta; import javafxpratico.crud.service.ContasService;
package javafxpratico.crud.service.impl; /** * * Uma implementação do ContasService para lidar com arquivo CSV * @author wsiqueir * */ public class ContasCSVService implements ContasService { // divisor de colunas no arquivo private static final String SEPARADOR = ";"; // o caminho para o arquivo deve ser selecionado aqui private static final Path ARQUIVO_SAIDA = Paths.get("./dados.csv"); // os dados do arquivo
// Path: codigo/javafx-pratico/src/main/java/javafxpratico/crud/model/Conta.java // public class Conta { // // private int id; // private String concessionaria; // private String descricao; // private Date dataVencimento; // // // gets e sets // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getConcessionaria() { // return concessionaria; // } // // public void setConcessionaria(String concessionaria) { // this.concessionaria = concessionaria; // } // // public String getDescricao() { // return descricao; // } // // public void setDescricao(String descricao) { // this.descricao = descricao; // } // // public Date getDataVencimento() { // return dataVencimento; // } // // public void setDataVencimento(Date dataVencimento) { // this.dataVencimento = dataVencimento; // } // // } // // Path: codigo/javafx-pratico/src/main/java/javafxpratico/crud/service/ContasService.java // public interface ContasService { // // // CREATE // public void salvar(Conta conta); // // // RETRIEVE // public List<Conta> buscarTodas(); // // public Conta buscaPorId(int id); // // // DELETE // public void apagar(int id); // // // UPDATE // public void atualizar(Conta conta); // // // // retorna a implementação que escolhemos - no nosso caso o ContasCSVService, // // mas poderia ser outro, como ContasDBService... // public static ContasService getNewInstance() { // return new ContasCSVService(); // } // // } // Path: codigo/javafx-pratico/src/main/java/javafxpratico/crud/service/impl/ContasCSVService.java import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.stream.Collectors; import javafxpratico.crud.model.Conta; import javafxpratico.crud.service.ContasService; package javafxpratico.crud.service.impl; /** * * Uma implementação do ContasService para lidar com arquivo CSV * @author wsiqueir * */ public class ContasCSVService implements ContasService { // divisor de colunas no arquivo private static final String SEPARADOR = ";"; // o caminho para o arquivo deve ser selecionado aqui private static final Path ARQUIVO_SAIDA = Paths.get("./dados.csv"); // os dados do arquivo
private List<Conta> contas;
jesuino/livro-javafx-pratico
codigo/javafx-pratico/src/main/java/javafxpratico/crud/controller/ContasController.java
// Path: codigo/javafx-pratico/src/main/java/javafxpratico/crud/model/Conta.java // public class Conta { // // private int id; // private String concessionaria; // private String descricao; // private Date dataVencimento; // // // gets e sets // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getConcessionaria() { // return concessionaria; // } // // public void setConcessionaria(String concessionaria) { // this.concessionaria = concessionaria; // } // // public String getDescricao() { // return descricao; // } // // public void setDescricao(String descricao) { // this.descricao = descricao; // } // // public Date getDataVencimento() { // return dataVencimento; // } // // public void setDataVencimento(Date dataVencimento) { // this.dataVencimento = dataVencimento; // } // // } // // Path: codigo/javafx-pratico/src/main/java/javafxpratico/crud/service/ContasService.java // public interface ContasService { // // // CREATE // public void salvar(Conta conta); // // // RETRIEVE // public List<Conta> buscarTodas(); // // public Conta buscaPorId(int id); // // // DELETE // public void apagar(int id); // // // UPDATE // public void atualizar(Conta conta); // // // // retorna a implementação que escolhemos - no nosso caso o ContasCSVService, // // mas poderia ser outro, como ContasDBService... // public static ContasService getNewInstance() { // return new ContasCSVService(); // } // // }
import java.net.URL; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date; import java.util.ResourceBundle; import javafx.beans.binding.BooleanBinding; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.DatePicker; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; import javafxpratico.crud.model.Conta; import javafxpratico.crud.service.ContasService;
package javafxpratico.crud.controller; /** * * O controller da aplicação, onde a mágica acontece * @author wsiqueir * */ public class ContasController implements Initializable { @FXML
// Path: codigo/javafx-pratico/src/main/java/javafxpratico/crud/model/Conta.java // public class Conta { // // private int id; // private String concessionaria; // private String descricao; // private Date dataVencimento; // // // gets e sets // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getConcessionaria() { // return concessionaria; // } // // public void setConcessionaria(String concessionaria) { // this.concessionaria = concessionaria; // } // // public String getDescricao() { // return descricao; // } // // public void setDescricao(String descricao) { // this.descricao = descricao; // } // // public Date getDataVencimento() { // return dataVencimento; // } // // public void setDataVencimento(Date dataVencimento) { // this.dataVencimento = dataVencimento; // } // // } // // Path: codigo/javafx-pratico/src/main/java/javafxpratico/crud/service/ContasService.java // public interface ContasService { // // // CREATE // public void salvar(Conta conta); // // // RETRIEVE // public List<Conta> buscarTodas(); // // public Conta buscaPorId(int id); // // // DELETE // public void apagar(int id); // // // UPDATE // public void atualizar(Conta conta); // // // // retorna a implementação que escolhemos - no nosso caso o ContasCSVService, // // mas poderia ser outro, como ContasDBService... // public static ContasService getNewInstance() { // return new ContasCSVService(); // } // // } // Path: codigo/javafx-pratico/src/main/java/javafxpratico/crud/controller/ContasController.java import java.net.URL; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date; import java.util.ResourceBundle; import javafx.beans.binding.BooleanBinding; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.DatePicker; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; import javafxpratico.crud.model.Conta; import javafxpratico.crud.service.ContasService; package javafxpratico.crud.controller; /** * * O controller da aplicação, onde a mágica acontece * @author wsiqueir * */ public class ContasController implements Initializable { @FXML
private TableView<Conta> tblContas;
jesuino/livro-javafx-pratico
codigo/javafx-pratico/src/main/java/javafxpratico/crud/controller/ContasController.java
// Path: codigo/javafx-pratico/src/main/java/javafxpratico/crud/model/Conta.java // public class Conta { // // private int id; // private String concessionaria; // private String descricao; // private Date dataVencimento; // // // gets e sets // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getConcessionaria() { // return concessionaria; // } // // public void setConcessionaria(String concessionaria) { // this.concessionaria = concessionaria; // } // // public String getDescricao() { // return descricao; // } // // public void setDescricao(String descricao) { // this.descricao = descricao; // } // // public Date getDataVencimento() { // return dataVencimento; // } // // public void setDataVencimento(Date dataVencimento) { // this.dataVencimento = dataVencimento; // } // // } // // Path: codigo/javafx-pratico/src/main/java/javafxpratico/crud/service/ContasService.java // public interface ContasService { // // // CREATE // public void salvar(Conta conta); // // // RETRIEVE // public List<Conta> buscarTodas(); // // public Conta buscaPorId(int id); // // // DELETE // public void apagar(int id); // // // UPDATE // public void atualizar(Conta conta); // // // // retorna a implementação que escolhemos - no nosso caso o ContasCSVService, // // mas poderia ser outro, como ContasDBService... // public static ContasService getNewInstance() { // return new ContasCSVService(); // } // // }
import java.net.URL; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date; import java.util.ResourceBundle; import javafx.beans.binding.BooleanBinding; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.DatePicker; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; import javafxpratico.crud.model.Conta; import javafxpratico.crud.service.ContasService;
package javafxpratico.crud.controller; /** * * O controller da aplicação, onde a mágica acontece * @author wsiqueir * */ public class ContasController implements Initializable { @FXML private TableView<Conta> tblContas; @FXML private TableColumn<Conta, String> clConsc; @FXML private TableColumn<Conta, String> clDesc; @FXML private TableColumn<Conta, Date> clVenc; @FXML private TextField txtConsc; @FXML private TextField txtDesc; @FXML private DatePicker dpVencimento; @FXML private Button btnSalvar; @FXML private Button btnAtualizar; @FXML private Button btnApagar; @FXML private Button btnLimpart;
// Path: codigo/javafx-pratico/src/main/java/javafxpratico/crud/model/Conta.java // public class Conta { // // private int id; // private String concessionaria; // private String descricao; // private Date dataVencimento; // // // gets e sets // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getConcessionaria() { // return concessionaria; // } // // public void setConcessionaria(String concessionaria) { // this.concessionaria = concessionaria; // } // // public String getDescricao() { // return descricao; // } // // public void setDescricao(String descricao) { // this.descricao = descricao; // } // // public Date getDataVencimento() { // return dataVencimento; // } // // public void setDataVencimento(Date dataVencimento) { // this.dataVencimento = dataVencimento; // } // // } // // Path: codigo/javafx-pratico/src/main/java/javafxpratico/crud/service/ContasService.java // public interface ContasService { // // // CREATE // public void salvar(Conta conta); // // // RETRIEVE // public List<Conta> buscarTodas(); // // public Conta buscaPorId(int id); // // // DELETE // public void apagar(int id); // // // UPDATE // public void atualizar(Conta conta); // // // // retorna a implementação que escolhemos - no nosso caso o ContasCSVService, // // mas poderia ser outro, como ContasDBService... // public static ContasService getNewInstance() { // return new ContasCSVService(); // } // // } // Path: codigo/javafx-pratico/src/main/java/javafxpratico/crud/controller/ContasController.java import java.net.URL; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date; import java.util.ResourceBundle; import javafx.beans.binding.BooleanBinding; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.DatePicker; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; import javafxpratico.crud.model.Conta; import javafxpratico.crud.service.ContasService; package javafxpratico.crud.controller; /** * * O controller da aplicação, onde a mágica acontece * @author wsiqueir * */ public class ContasController implements Initializable { @FXML private TableView<Conta> tblContas; @FXML private TableColumn<Conta, String> clConsc; @FXML private TableColumn<Conta, String> clDesc; @FXML private TableColumn<Conta, Date> clVenc; @FXML private TextField txtConsc; @FXML private TextField txtDesc; @FXML private DatePicker dpVencimento; @FXML private Button btnSalvar; @FXML private Button btnAtualizar; @FXML private Button btnApagar; @FXML private Button btnLimpart;
private ContasService service;
simplegeo/simplegeo-java-client
src/com/simplegeo/client/model/DefaultRecord.java
// Path: src/com/simplegeo/client/types/Point.java // public class Point { // // private double latitude; // private double longitude; // // public Point(double latitude, double longitude) { // this.latitude = latitude; // this.longitude = longitude; // } // // /** // * @return the latitude // */ // public double getLatitude() { // return latitude; // } // // /** // * @param latitude the latitude to set // */ // public void setLatitude(double latitude) { // this.latitude = latitude; // } // // /** // * @return the longitude // */ // public double getLongitude() { // return longitude; // } // // /** // * @param longitude the longitude to set // */ // public void setLongitude(double longitude) { // this.longitude = longitude; // } // }
import com.simplegeo.client.types.Point; import org.json.JSONException; import org.json.JSONObject;
/** * @param key the key to look-up in the {@link org.json.JSONObject} properties * @return the Object value */ public Object getObjectProperty(String key) { Object value = null; try { value = getProperties().get(key); } catch (JSONException e) { ; } return value; } /** * @param key the key to use * @param value the Object value that will be assigned * to the key in the properties {@link org.json.JSONObject}. */ public void setObjectProperty(String key, Object value) { if(value == null) value = JSONObject.NULL; try { getProperties().put(key, value); } catch (JSONException e) { } }
// Path: src/com/simplegeo/client/types/Point.java // public class Point { // // private double latitude; // private double longitude; // // public Point(double latitude, double longitude) { // this.latitude = latitude; // this.longitude = longitude; // } // // /** // * @return the latitude // */ // public double getLatitude() { // return latitude; // } // // /** // * @param latitude the latitude to set // */ // public void setLatitude(double latitude) { // this.latitude = latitude; // } // // /** // * @return the longitude // */ // public double getLongitude() { // return longitude; // } // // /** // * @param longitude the longitude to set // */ // public void setLongitude(double longitude) { // this.longitude = longitude; // } // } // Path: src/com/simplegeo/client/model/DefaultRecord.java import com.simplegeo.client.types.Point; import org.json.JSONException; import org.json.JSONObject; /** * @param key the key to look-up in the {@link org.json.JSONObject} properties * @return the Object value */ public Object getObjectProperty(String key) { Object value = null; try { value = getProperties().get(key); } catch (JSONException e) { ; } return value; } /** * @param key the key to use * @param value the Object value that will be assigned * to the key in the properties {@link org.json.JSONObject}. */ public void setObjectProperty(String key, Object value) { if(value == null) value = JSONObject.NULL; try { getProperties().put(key, value); } catch (JSONException e) { } }
public Point getOrigin() {
simplegeo/simplegeo-java-client
src/com/simplegeo/client/model/LayerManager.java
// Path: src/com/simplegeo/client/query/NearbyQuery.java // public abstract class NearbyQuery implements IQuery { // // private String cursor; // private String layer; // private List<String> types; // private int limit; // private double start; // private double end; // // /** // * @param layer @see com.simplegeo.client.query.NearbyQuery#getLayer() // * @param types @see com.simplegeo.client.query.NearbyQuery#getTypes() // * @param limit @see com.simplegeo.client.query.NearbyQuery#getLimit() // * @param cursor @see com.simplegeo.client.query.IQuery#getCursor() // * @throws ValidLayerException // */ // public NearbyQuery(String layer, List<String> types, int limit, String cursor) throws ValidLayerException { // this(layer, types, limit, cursor, -1, -1); // } // // public NearbyQuery(String layer, List<String> types, int limit, String cursor, double start, double end) // throws ValidLayerException { // // this.types = types; // this.cursor = cursor; // this.limit = limit; // // if (layer == null || layer.equals("")) // throw new ValidLayerException(""); // // this.layer = layer; // // this.start = start; // this.end = end; // } // // /** // * @see com.simplegeo.client.query.IQuery#getParams() // */ // public Map<String, String> getParams() { // Map<String, String> params = new HashMap<String, String>(); // if(limit > 0) // params.put("limit", Integer.toString(limit)); // // if(types != null && !types.isEmpty()) // params.put("types", SimpleGeoUtilities.commaSeparatedString(types)); // // if(cursor != null) // params.put("cursor", cursor); // // if(start > 0 && end > 0) { // params.put("start", Double.toString(start)); // params.put("end", Double.toString(end)); // } // // return params; // } // // /** // * @throws UnsupportedEncodingException // * @see com.simplegeo.client.query.IQuery#getUri() // */ // public String getUri() throws UnsupportedEncodingException { // return String.format("/records/%s/nearby", URLEncoder.encode(layer, "UTF-8")); // } // // /** // * @see com.simplegeo.client.query.IQuery#getCursor() // */ // public String getCursor() { // return cursor; // } // // /** // * @see com.simplegeo.client.query.IQuery#setCursor() // */ // public void setCursor(String cursor) { // this.cursor = cursor; // } // // /** // * @return the layer // */ // public String getLayer() { // return layer; // } // // /** // * @param layer the layer to search in // */ // public void setLayer(String layer) { // this.layer = layer; // } // // /** // * If this value is null, ALL types will be searched. // * // * @return the types to look for // */ // public List<String> getTypes() { // return types; // } // // /** // * @param types the types to set // */ // public void setTypes(List<String> types) { // this.types = types; // } // // /** // * The default limit is 25. // * // * @return the limit // */ // public int getLimit() { // return limit; // } // // /** // * @param limit the limit to set // */ // public void setLimit(int limit) { // this.limit = limit; // } // }
import java.util.Collection; import java.util.List; import org.json.JSONException; import com.simplegeo.client.query.NearbyQuery; import java.io.IOException; import java.util.ArrayList;
public void update() { for(Layer layer : layers) try { layer.update(); } catch (IOException e) { e.printStackTrace(); } } /** * Calls {@link com.simplegeo.client.model.Layer#retrieve()} on all Layer * objects registered with the manager. */ public void retrieve() { for(Layer layer : layers) try { layer.retrieve(); } catch (IOException e) { e.printStackTrace(); } } /** * Calls {@link com.simplegeo.client.model.Layer#nearby(NearbyQuery)} on all * Layer objects registered with the manager. * * @param query the nearby query * @return */ @SuppressWarnings("unchecked")
// Path: src/com/simplegeo/client/query/NearbyQuery.java // public abstract class NearbyQuery implements IQuery { // // private String cursor; // private String layer; // private List<String> types; // private int limit; // private double start; // private double end; // // /** // * @param layer @see com.simplegeo.client.query.NearbyQuery#getLayer() // * @param types @see com.simplegeo.client.query.NearbyQuery#getTypes() // * @param limit @see com.simplegeo.client.query.NearbyQuery#getLimit() // * @param cursor @see com.simplegeo.client.query.IQuery#getCursor() // * @throws ValidLayerException // */ // public NearbyQuery(String layer, List<String> types, int limit, String cursor) throws ValidLayerException { // this(layer, types, limit, cursor, -1, -1); // } // // public NearbyQuery(String layer, List<String> types, int limit, String cursor, double start, double end) // throws ValidLayerException { // // this.types = types; // this.cursor = cursor; // this.limit = limit; // // if (layer == null || layer.equals("")) // throw new ValidLayerException(""); // // this.layer = layer; // // this.start = start; // this.end = end; // } // // /** // * @see com.simplegeo.client.query.IQuery#getParams() // */ // public Map<String, String> getParams() { // Map<String, String> params = new HashMap<String, String>(); // if(limit > 0) // params.put("limit", Integer.toString(limit)); // // if(types != null && !types.isEmpty()) // params.put("types", SimpleGeoUtilities.commaSeparatedString(types)); // // if(cursor != null) // params.put("cursor", cursor); // // if(start > 0 && end > 0) { // params.put("start", Double.toString(start)); // params.put("end", Double.toString(end)); // } // // return params; // } // // /** // * @throws UnsupportedEncodingException // * @see com.simplegeo.client.query.IQuery#getUri() // */ // public String getUri() throws UnsupportedEncodingException { // return String.format("/records/%s/nearby", URLEncoder.encode(layer, "UTF-8")); // } // // /** // * @see com.simplegeo.client.query.IQuery#getCursor() // */ // public String getCursor() { // return cursor; // } // // /** // * @see com.simplegeo.client.query.IQuery#setCursor() // */ // public void setCursor(String cursor) { // this.cursor = cursor; // } // // /** // * @return the layer // */ // public String getLayer() { // return layer; // } // // /** // * @param layer the layer to search in // */ // public void setLayer(String layer) { // this.layer = layer; // } // // /** // * If this value is null, ALL types will be searched. // * // * @return the types to look for // */ // public List<String> getTypes() { // return types; // } // // /** // * @param types the types to set // */ // public void setTypes(List<String> types) { // this.types = types; // } // // /** // * The default limit is 25. // * // * @return the limit // */ // public int getLimit() { // return limit; // } // // /** // * @param limit the limit to set // */ // public void setLimit(int limit) { // this.limit = limit; // } // } // Path: src/com/simplegeo/client/model/LayerManager.java import java.util.Collection; import java.util.List; import org.json.JSONException; import com.simplegeo.client.query.NearbyQuery; import java.io.IOException; import java.util.ArrayList; public void update() { for(Layer layer : layers) try { layer.update(); } catch (IOException e) { e.printStackTrace(); } } /** * Calls {@link com.simplegeo.client.model.Layer#retrieve()} on all Layer * objects registered with the manager. */ public void retrieve() { for(Layer layer : layers) try { layer.retrieve(); } catch (IOException e) { e.printStackTrace(); } } /** * Calls {@link com.simplegeo.client.model.Layer#nearby(NearbyQuery)} on all * Layer objects registered with the manager. * * @param query the nearby query * @return */ @SuppressWarnings("unchecked")
public List<IRecord> nearby(NearbyQuery query) {
simplegeo/simplegeo-java-client
src/com/simplegeo/client/query/NearbyQuery.java
// Path: src/com/simplegeo/client/http/exceptions/ValidLayerException.java // public class ValidLayerException extends Exception { // // /** // * // */ // private static final long serialVersionUID = -3256654766900362800L; // // public ValidLayerException(String string) { // super(string); // } // // } // // Path: src/com/simplegeo/client/utilities/SimpleGeoUtilities.java // public class SimpleGeoUtilities { // // static public String commaSeparatedString(List<String> strings) { // // String mainString = ""; // for(String string : strings) // mainString += "," + string; // // mainString.replaceFirst(",", ""); // // return mainString; // // } // }
import java.util.HashMap; import java.util.List; import java.util.Map; import com.simplegeo.client.http.exceptions.ValidLayerException; import com.simplegeo.client.utilities.SimpleGeoUtilities; import java.io.UnsupportedEncodingException; import java.net.URLEncoder;
/** * Copyright (c) 2009-2010, SimpleGeo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. Redistributions * in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * Neither the name of the SimpleGeo nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.simplegeo.client.query; /** * An abstracted class that defines the some of the common parameters * between a Geohash and LatLon nearby query. * * @author Derek Smith */ public abstract class NearbyQuery implements IQuery { private String cursor; private String layer; private List<String> types; private int limit; private double start; private double end; /** * @param layer @see com.simplegeo.client.query.NearbyQuery#getLayer() * @param types @see com.simplegeo.client.query.NearbyQuery#getTypes() * @param limit @see com.simplegeo.client.query.NearbyQuery#getLimit() * @param cursor @see com.simplegeo.client.query.IQuery#getCursor() * @throws ValidLayerException */
// Path: src/com/simplegeo/client/http/exceptions/ValidLayerException.java // public class ValidLayerException extends Exception { // // /** // * // */ // private static final long serialVersionUID = -3256654766900362800L; // // public ValidLayerException(String string) { // super(string); // } // // } // // Path: src/com/simplegeo/client/utilities/SimpleGeoUtilities.java // public class SimpleGeoUtilities { // // static public String commaSeparatedString(List<String> strings) { // // String mainString = ""; // for(String string : strings) // mainString += "," + string; // // mainString.replaceFirst(",", ""); // // return mainString; // // } // } // Path: src/com/simplegeo/client/query/NearbyQuery.java import java.util.HashMap; import java.util.List; import java.util.Map; import com.simplegeo.client.http.exceptions.ValidLayerException; import com.simplegeo.client.utilities.SimpleGeoUtilities; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; /** * Copyright (c) 2009-2010, SimpleGeo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. Redistributions * in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * Neither the name of the SimpleGeo nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.simplegeo.client.query; /** * An abstracted class that defines the some of the common parameters * between a Geohash and LatLon nearby query. * * @author Derek Smith */ public abstract class NearbyQuery implements IQuery { private String cursor; private String layer; private List<String> types; private int limit; private double start; private double end; /** * @param layer @see com.simplegeo.client.query.NearbyQuery#getLayer() * @param types @see com.simplegeo.client.query.NearbyQuery#getTypes() * @param limit @see com.simplegeo.client.query.NearbyQuery#getLimit() * @param cursor @see com.simplegeo.client.query.IQuery#getCursor() * @throws ValidLayerException */
public NearbyQuery(String layer, List<String> types, int limit, String cursor) throws ValidLayerException {
simplegeo/simplegeo-java-client
src/com/simplegeo/client/query/NearbyQuery.java
// Path: src/com/simplegeo/client/http/exceptions/ValidLayerException.java // public class ValidLayerException extends Exception { // // /** // * // */ // private static final long serialVersionUID = -3256654766900362800L; // // public ValidLayerException(String string) { // super(string); // } // // } // // Path: src/com/simplegeo/client/utilities/SimpleGeoUtilities.java // public class SimpleGeoUtilities { // // static public String commaSeparatedString(List<String> strings) { // // String mainString = ""; // for(String string : strings) // mainString += "," + string; // // mainString.replaceFirst(",", ""); // // return mainString; // // } // }
import java.util.HashMap; import java.util.List; import java.util.Map; import com.simplegeo.client.http.exceptions.ValidLayerException; import com.simplegeo.client.utilities.SimpleGeoUtilities; import java.io.UnsupportedEncodingException; import java.net.URLEncoder;
/** * Copyright (c) 2009-2010, SimpleGeo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. Redistributions * in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * Neither the name of the SimpleGeo nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.simplegeo.client.query; /** * An abstracted class that defines the some of the common parameters * between a Geohash and LatLon nearby query. * * @author Derek Smith */ public abstract class NearbyQuery implements IQuery { private String cursor; private String layer; private List<String> types; private int limit; private double start; private double end; /** * @param layer @see com.simplegeo.client.query.NearbyQuery#getLayer() * @param types @see com.simplegeo.client.query.NearbyQuery#getTypes() * @param limit @see com.simplegeo.client.query.NearbyQuery#getLimit() * @param cursor @see com.simplegeo.client.query.IQuery#getCursor() * @throws ValidLayerException */ public NearbyQuery(String layer, List<String> types, int limit, String cursor) throws ValidLayerException { this(layer, types, limit, cursor, -1, -1); } public NearbyQuery(String layer, List<String> types, int limit, String cursor, double start, double end) throws ValidLayerException { this.types = types; this.cursor = cursor; this.limit = limit; if (layer == null || layer.equals("")) throw new ValidLayerException(""); this.layer = layer; this.start = start; this.end = end; } /** * @see com.simplegeo.client.query.IQuery#getParams() */ public Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); if(limit > 0) params.put("limit", Integer.toString(limit)); if(types != null && !types.isEmpty())
// Path: src/com/simplegeo/client/http/exceptions/ValidLayerException.java // public class ValidLayerException extends Exception { // // /** // * // */ // private static final long serialVersionUID = -3256654766900362800L; // // public ValidLayerException(String string) { // super(string); // } // // } // // Path: src/com/simplegeo/client/utilities/SimpleGeoUtilities.java // public class SimpleGeoUtilities { // // static public String commaSeparatedString(List<String> strings) { // // String mainString = ""; // for(String string : strings) // mainString += "," + string; // // mainString.replaceFirst(",", ""); // // return mainString; // // } // } // Path: src/com/simplegeo/client/query/NearbyQuery.java import java.util.HashMap; import java.util.List; import java.util.Map; import com.simplegeo.client.http.exceptions.ValidLayerException; import com.simplegeo.client.utilities.SimpleGeoUtilities; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; /** * Copyright (c) 2009-2010, SimpleGeo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. Redistributions * in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * Neither the name of the SimpleGeo nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.simplegeo.client.query; /** * An abstracted class that defines the some of the common parameters * between a Geohash and LatLon nearby query. * * @author Derek Smith */ public abstract class NearbyQuery implements IQuery { private String cursor; private String layer; private List<String> types; private int limit; private double start; private double end; /** * @param layer @see com.simplegeo.client.query.NearbyQuery#getLayer() * @param types @see com.simplegeo.client.query.NearbyQuery#getTypes() * @param limit @see com.simplegeo.client.query.NearbyQuery#getLimit() * @param cursor @see com.simplegeo.client.query.IQuery#getCursor() * @throws ValidLayerException */ public NearbyQuery(String layer, List<String> types, int limit, String cursor) throws ValidLayerException { this(layer, types, limit, cursor, -1, -1); } public NearbyQuery(String layer, List<String> types, int limit, String cursor, double start, double end) throws ValidLayerException { this.types = types; this.cursor = cursor; this.limit = limit; if (layer == null || layer.equals("")) throw new ValidLayerException(""); this.layer = layer; this.start = start; this.end = end; } /** * @see com.simplegeo.client.query.IQuery#getParams() */ public Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); if(limit > 0) params.put("limit", Integer.toString(limit)); if(types != null && !types.isEmpty())
params.put("types", SimpleGeoUtilities.commaSeparatedString(types));
simplegeo/simplegeo-java-client
src/com/simplegeo/client/query/IPAddressQuery.java
// Path: src/com/simplegeo/client/http/exceptions/ValidLayerException.java // public class ValidLayerException extends Exception { // // /** // * // */ // private static final long serialVersionUID = -3256654766900362800L; // // public ValidLayerException(String string) { // super(string); // } // // }
import com.simplegeo.client.http.exceptions.ValidLayerException; import java.io.UnsupportedEncodingException; import java.util.List;
/** * Copyright (c) 2009-2010, SimpleGeo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. Redistributions * in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * Neither the name of the SimpleGeo nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.simplegeo.client.query; /** * A nearby query that uses an ip address as its search parameters. * * @see com.simplegeo.client.query.IPAddressQuery * * @author Derek Smith */ public class IPAddressQuery extends NearbyQuery { private String ipAddress;
// Path: src/com/simplegeo/client/http/exceptions/ValidLayerException.java // public class ValidLayerException extends Exception { // // /** // * // */ // private static final long serialVersionUID = -3256654766900362800L; // // public ValidLayerException(String string) { // super(string); // } // // } // Path: src/com/simplegeo/client/query/IPAddressQuery.java import com.simplegeo.client.http.exceptions.ValidLayerException; import java.io.UnsupportedEncodingException; import java.util.List; /** * Copyright (c) 2009-2010, SimpleGeo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. Redistributions * in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * Neither the name of the SimpleGeo nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.simplegeo.client.query; /** * A nearby query that uses an ip address as its search parameters. * * @see com.simplegeo.client.query.IPAddressQuery * * @author Derek Smith */ public class IPAddressQuery extends NearbyQuery { private String ipAddress;
public IPAddressQuery(String ipAddress, String layer) throws ValidLayerException {
simplegeo/simplegeo-java-client
src/com/simplegeo/client/query/LatLonNearbyQuery.java
// Path: src/com/simplegeo/client/http/exceptions/ValidLayerException.java // public class ValidLayerException extends Exception { // // /** // * // */ // private static final long serialVersionUID = -3256654766900362800L; // // public ValidLayerException(String string) { // super(string); // } // // }
import java.util.Map; import com.simplegeo.client.http.exceptions.ValidLayerException; import java.io.UnsupportedEncodingException; import java.util.List;
/** * Copyright (c) 2009-2010, SimpleGeo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. Redistributions * in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * Neither the name of the SimpleGeo nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.simplegeo.client.query; /** * A nearby query that uses latitude, longitude and radius as its search * parameters. * * @see com.simplegeo.client.query.NearbyQuery * * @author Derek Smith */ public class LatLonNearbyQuery extends NearbyQuery { private double lat; private double lon; private double radius; /** * @param lat the latitude * @param lon the longitude * @param radius the radius of the search in km * @param @see com.simplegeo.client.query.NearbyQuery#getLayer() * @throws ValidLayerException */
// Path: src/com/simplegeo/client/http/exceptions/ValidLayerException.java // public class ValidLayerException extends Exception { // // /** // * // */ // private static final long serialVersionUID = -3256654766900362800L; // // public ValidLayerException(String string) { // super(string); // } // // } // Path: src/com/simplegeo/client/query/LatLonNearbyQuery.java import java.util.Map; import com.simplegeo.client.http.exceptions.ValidLayerException; import java.io.UnsupportedEncodingException; import java.util.List; /** * Copyright (c) 2009-2010, SimpleGeo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. Redistributions * in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * Neither the name of the SimpleGeo nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.simplegeo.client.query; /** * A nearby query that uses latitude, longitude and radius as its search * parameters. * * @see com.simplegeo.client.query.NearbyQuery * * @author Derek Smith */ public class LatLonNearbyQuery extends NearbyQuery { private double lat; private double lon; private double radius; /** * @param lat the latitude * @param lon the longitude * @param radius the radius of the search in km * @param @see com.simplegeo.client.query.NearbyQuery#getLayer() * @throws ValidLayerException */
public LatLonNearbyQuery(double lat, double lon, double radius, String layer) throws ValidLayerException {
simplegeo/simplegeo-java-client
src/com/simplegeo/client/query/GeohashNearbyQuery.java
// Path: src/com/simplegeo/client/http/exceptions/ValidLayerException.java // public class ValidLayerException extends Exception { // // /** // * // */ // private static final long serialVersionUID = -3256654766900362800L; // // public ValidLayerException(String string) { // super(string); // } // // }
import com.simplegeo.client.http.exceptions.ValidLayerException; import ch.hsr.geohash.GeoHash; import java.io.UnsupportedEncodingException; import java.util.List;
/** * Copyright (c) 2009-2010, SimpleGeo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. Redistributions * in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * Neither the name of the SimpleGeo nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.simplegeo.client.query; /** * A nearby query that uses a geohash as its search parameters. * * @see com.simplegeo.client.query.NearbyQuery * * @author Derek Smith */ public class GeohashNearbyQuery extends NearbyQuery { private GeoHash geohash; /** * @param geohash the area to search for records * @param @see com.simplegeo.client.query.NearbyQuery#getLayer() * @throws ValidLayerException */
// Path: src/com/simplegeo/client/http/exceptions/ValidLayerException.java // public class ValidLayerException extends Exception { // // /** // * // */ // private static final long serialVersionUID = -3256654766900362800L; // // public ValidLayerException(String string) { // super(string); // } // // } // Path: src/com/simplegeo/client/query/GeohashNearbyQuery.java import com.simplegeo.client.http.exceptions.ValidLayerException; import ch.hsr.geohash.GeoHash; import java.io.UnsupportedEncodingException; import java.util.List; /** * Copyright (c) 2009-2010, SimpleGeo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. Redistributions * in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * Neither the name of the SimpleGeo nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.simplegeo.client.query; /** * A nearby query that uses a geohash as its search parameters. * * @see com.simplegeo.client.query.NearbyQuery * * @author Derek Smith */ public class GeohashNearbyQuery extends NearbyQuery { private GeoHash geohash; /** * @param geohash the area to search for records * @param @see com.simplegeo.client.query.NearbyQuery#getLayer() * @throws ValidLayerException */
public GeohashNearbyQuery(GeoHash geohash, String layer) throws ValidLayerException {
simplegeo/simplegeo-java-client
src/com/simplegeo/client/http/SimpleGeoHandler.java
// Path: src/com/simplegeo/client/handler/SimpleGeoJSONHandlerIfc.java // public interface SimpleGeoJSONHandlerIfc { // // /** // * @param response // * @return the object contained in the response // */ // public Object parseResponse (String response); // // } // // Path: src/com/simplegeo/client/http/exceptions/APIException.java // @SuppressWarnings("serial") // public class APIException extends IOException { // // private static Logger logger = Logger.getLogger(APIException.class.getName()); // // /** // * The Http status code that generated the exception. // */ // public int statusCode; // // /** // * A static factory method that creates proper API exceptions from // * a {@link org.apache.http.HttpEntity} and {@link org.apache.http.StatusLine}. // * The message is built using a combination of both the status code and the payload. // * // * @param entity the entity retrieved from a Http response // * @param statusLine the {@link org.apache.http.StatusLine} that was retrieved // * from a Http response // * @return a new APIException object // */ // public static APIException createException(HttpEntity entity, StatusLine statusLine) { // // int statusCode = statusLine.getStatusCode(); // String reason = null; // // try { // // InputStream inputStream = entity.getContent(); // DataInputStream dis = new DataInputStream(inputStream); // reason = dis.readUTF(); // // } catch (EOFException e) { // // ; // // } catch (IllegalStateException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // // if(reason == null) // reason = statusLine.getReasonPhrase(); // // logger.info(String.format("(status %d) %s", statusCode, reason)); // // return new APIException(statusCode, reason); // } // // /** // * Creates an exception with the given status code and message. // * // * @param statusCode the Http status code that generated the exception // * @param reason the reason why the this exception is being created // */ // public APIException(int statusCode, String reason) { // // super(reason); // this.statusCode = statusCode; // // logger.info(String.format("(status %d) %s", statusCode, reason)); // } // // } // // Path: src/com/simplegeo/client/http/exceptions/NoSuchRecordException.java // @SuppressWarnings("serial") // public class NoSuchRecordException extends APIException { // // public NoSuchRecordException(int statusCode, String reason) { // super(statusCode, reason); // } // // } // // Path: src/com/simplegeo/client/http/exceptions/NotAuthorizedException.java // @SuppressWarnings("serial") // public class NotAuthorizedException extends APIException { // // public NotAuthorizedException(int statusCode, String reason) { // super(statusCode, reason); // } // // }
import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.util.EntityUtils; import com.simplegeo.client.handler.SimpleGeoJSONHandlerIfc; import com.simplegeo.client.http.exceptions.APIException; import com.simplegeo.client.http.exceptions.NoSuchRecordException; import com.simplegeo.client.http.exceptions.NotAuthorizedException; import java.io.IOException; import java.util.logging.Logger;
/** * Copyright (c) 2009-2010, SimpleGeo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. Redistributions * in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * Neither the name of the SimpleGeo nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.simplegeo.client.http; /** * A handler used to parse requests sent to http://api.simplegeo.com. * * @author Derek Smith */ public class SimpleGeoHandler implements ResponseHandler<Object> { private static Logger logger = Logger.getLogger(SimpleGeoHandler.class.getName());
// Path: src/com/simplegeo/client/handler/SimpleGeoJSONHandlerIfc.java // public interface SimpleGeoJSONHandlerIfc { // // /** // * @param response // * @return the object contained in the response // */ // public Object parseResponse (String response); // // } // // Path: src/com/simplegeo/client/http/exceptions/APIException.java // @SuppressWarnings("serial") // public class APIException extends IOException { // // private static Logger logger = Logger.getLogger(APIException.class.getName()); // // /** // * The Http status code that generated the exception. // */ // public int statusCode; // // /** // * A static factory method that creates proper API exceptions from // * a {@link org.apache.http.HttpEntity} and {@link org.apache.http.StatusLine}. // * The message is built using a combination of both the status code and the payload. // * // * @param entity the entity retrieved from a Http response // * @param statusLine the {@link org.apache.http.StatusLine} that was retrieved // * from a Http response // * @return a new APIException object // */ // public static APIException createException(HttpEntity entity, StatusLine statusLine) { // // int statusCode = statusLine.getStatusCode(); // String reason = null; // // try { // // InputStream inputStream = entity.getContent(); // DataInputStream dis = new DataInputStream(inputStream); // reason = dis.readUTF(); // // } catch (EOFException e) { // // ; // // } catch (IllegalStateException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // // if(reason == null) // reason = statusLine.getReasonPhrase(); // // logger.info(String.format("(status %d) %s", statusCode, reason)); // // return new APIException(statusCode, reason); // } // // /** // * Creates an exception with the given status code and message. // * // * @param statusCode the Http status code that generated the exception // * @param reason the reason why the this exception is being created // */ // public APIException(int statusCode, String reason) { // // super(reason); // this.statusCode = statusCode; // // logger.info(String.format("(status %d) %s", statusCode, reason)); // } // // } // // Path: src/com/simplegeo/client/http/exceptions/NoSuchRecordException.java // @SuppressWarnings("serial") // public class NoSuchRecordException extends APIException { // // public NoSuchRecordException(int statusCode, String reason) { // super(statusCode, reason); // } // // } // // Path: src/com/simplegeo/client/http/exceptions/NotAuthorizedException.java // @SuppressWarnings("serial") // public class NotAuthorizedException extends APIException { // // public NotAuthorizedException(int statusCode, String reason) { // super(statusCode, reason); // } // // } // Path: src/com/simplegeo/client/http/SimpleGeoHandler.java import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.util.EntityUtils; import com.simplegeo.client.handler.SimpleGeoJSONHandlerIfc; import com.simplegeo.client.http.exceptions.APIException; import com.simplegeo.client.http.exceptions.NoSuchRecordException; import com.simplegeo.client.http.exceptions.NotAuthorizedException; import java.io.IOException; import java.util.logging.Logger; /** * Copyright (c) 2009-2010, SimpleGeo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. Redistributions * in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * Neither the name of the SimpleGeo nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.simplegeo.client.http; /** * A handler used to parse requests sent to http://api.simplegeo.com. * * @author Derek Smith */ public class SimpleGeoHandler implements ResponseHandler<Object> { private static Logger logger = Logger.getLogger(SimpleGeoHandler.class.getName());
private SimpleGeoJSONHandlerIfc handler;
FabianTerhorst/Iron
iron-encryption/src/main/java/io/fabianterhorst/iron/encryption/IronEncryption.java
// Path: iron/src/main/java/io/fabianterhorst/iron/Encryption.java // public interface Encryption { // Cipher getCipher(int mode); // ByteArrayInputStream decrypt(InputStream text); // CipherOutputStream encrypt(OutputStream bytes); // } // // Path: iron/src/main/java/io/fabianterhorst/iron/Iron.java // public class Iron { // public static final String DEFAULT_DB_NAME = "io.iron"; // // private static Context mContext; // // private static Loader mLoader; // // private static Encryption mEncryption; // // private static int mCache = Cache.NONE; // // private static final ConcurrentHashMap<String, Chest> mChestMap = new ConcurrentHashMap<>(); // // /** // * Lightweight method to init Iron instance. Should be executed in {@link Application#onCreate()} // * // * @param context context, used to get application context // */ // public static void init(Context context) { // mContext = context.getApplicationContext(); // } // // /** // * Set the loader to the Iron instance // * // * @param loader loader extension for the iron instance // */ // public static void setLoader(Loader loader) { // mLoader = loader; // } // // /** // * Set the encryption to the Iron instance // * // * @param encryption encryption extension for the iron instance // */ // public static void setEncryption(Encryption encryption) { // mEncryption = encryption; // } // // /** // * Set the cache strategy to store the written objects in memory // * // * @param cache the cache strategy Cache#Memory or Cache#NONE // */ // public static void setCache(int cache) { // mCache = cache; // } // // /** // * Returns Iron chest instance with the given name // * // * @param name name of new database // * @return Iron instance // */ // public static Chest chest(String name) { // if (name.equals(DEFAULT_DB_NAME)) throw new IronException(DEFAULT_DB_NAME + // " name is reserved for default library name"); // return getChest(name); // } // // /** // * Returns default iron chest instance // * // * @return Chest instance // */ // public static Chest chest() { // return getChest(DEFAULT_DB_NAME); // } // // private static Chest getChest(String name) { // if (mContext == null) { // throw new IronException("Iron.init is not called"); // } // synchronized (mChestMap) { // Chest chest = mChestMap.get(name); // if (chest == null) { // chest = new Chest(mContext, name, mLoader, mEncryption, mCache); // mChestMap.put(name, chest); // } // return chest; // } // } // // /** // * @deprecated use Iron.chest().write() // */ // public static <T> Chest put(String key, T value) { // return chest().write(key, value); // } // // /** // * @deprecated use Iron.chest().read() // */ // public static <T> T get(String key) { // return chest().read(key); // } // // /** // * @deprecated use Iron.chest().read() // */ // public static <T> T get(String key, T defaultValue) { // return chest().read(key, defaultValue); // } // // /** // * @deprecated use Iron.chest().exist() // */ // public static boolean exist(String key) { // return chest().exist(key); // } // // /** // * @deprecated use Iron.chest().delete() // */ // public static void delete(String key) { // chest().delete(key); // } // // /** // * @deprecated use Iron.chest().destroy(). NOTE: Iron.init() be called // * before destroy() // */ // public static void clear(Context context) { // init(context); // chest().destroy(); // } // }
import android.util.Log; import org.apache.commons.io.IOUtils; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.GeneralSecurityException; import java.security.SecureRandom; import java.util.concurrent.atomic.AtomicBoolean; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.CipherOutputStream; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import io.fabianterhorst.iron.Encryption; import io.fabianterhorst.iron.Iron;
@Override public Cipher getCipher(int mode){ try { byte[] iv = generateIv(); Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION); cipher.init(mode, mKey.getConfidentialityKey(), new IvParameterSpec(iv)); return cipher; }catch(GeneralSecurityException e){ e.printStackTrace(); } return null; } @Override public ByteArrayInputStream decrypt(InputStream inputStream) { CipherInputStream cipherInputStream = new CipherInputStream(inputStream, getCipher(Cipher.DECRYPT_MODE)); try { return new ByteArrayInputStream(IOUtils.toByteArray(cipherInputStream)); }catch(IOException io){ io.printStackTrace(); } return null; } @Override public CipherOutputStream encrypt(OutputStream outputStream) { return new CipherOutputStream(outputStream, getCipher(Cipher.ENCRYPT_MODE)); } public AesCbcWithIntegrity.SecretKeys getKey() {
// Path: iron/src/main/java/io/fabianterhorst/iron/Encryption.java // public interface Encryption { // Cipher getCipher(int mode); // ByteArrayInputStream decrypt(InputStream text); // CipherOutputStream encrypt(OutputStream bytes); // } // // Path: iron/src/main/java/io/fabianterhorst/iron/Iron.java // public class Iron { // public static final String DEFAULT_DB_NAME = "io.iron"; // // private static Context mContext; // // private static Loader mLoader; // // private static Encryption mEncryption; // // private static int mCache = Cache.NONE; // // private static final ConcurrentHashMap<String, Chest> mChestMap = new ConcurrentHashMap<>(); // // /** // * Lightweight method to init Iron instance. Should be executed in {@link Application#onCreate()} // * // * @param context context, used to get application context // */ // public static void init(Context context) { // mContext = context.getApplicationContext(); // } // // /** // * Set the loader to the Iron instance // * // * @param loader loader extension for the iron instance // */ // public static void setLoader(Loader loader) { // mLoader = loader; // } // // /** // * Set the encryption to the Iron instance // * // * @param encryption encryption extension for the iron instance // */ // public static void setEncryption(Encryption encryption) { // mEncryption = encryption; // } // // /** // * Set the cache strategy to store the written objects in memory // * // * @param cache the cache strategy Cache#Memory or Cache#NONE // */ // public static void setCache(int cache) { // mCache = cache; // } // // /** // * Returns Iron chest instance with the given name // * // * @param name name of new database // * @return Iron instance // */ // public static Chest chest(String name) { // if (name.equals(DEFAULT_DB_NAME)) throw new IronException(DEFAULT_DB_NAME + // " name is reserved for default library name"); // return getChest(name); // } // // /** // * Returns default iron chest instance // * // * @return Chest instance // */ // public static Chest chest() { // return getChest(DEFAULT_DB_NAME); // } // // private static Chest getChest(String name) { // if (mContext == null) { // throw new IronException("Iron.init is not called"); // } // synchronized (mChestMap) { // Chest chest = mChestMap.get(name); // if (chest == null) { // chest = new Chest(mContext, name, mLoader, mEncryption, mCache); // mChestMap.put(name, chest); // } // return chest; // } // } // // /** // * @deprecated use Iron.chest().write() // */ // public static <T> Chest put(String key, T value) { // return chest().write(key, value); // } // // /** // * @deprecated use Iron.chest().read() // */ // public static <T> T get(String key) { // return chest().read(key); // } // // /** // * @deprecated use Iron.chest().read() // */ // public static <T> T get(String key, T defaultValue) { // return chest().read(key, defaultValue); // } // // /** // * @deprecated use Iron.chest().exist() // */ // public static boolean exist(String key) { // return chest().exist(key); // } // // /** // * @deprecated use Iron.chest().delete() // */ // public static void delete(String key) { // chest().delete(key); // } // // /** // * @deprecated use Iron.chest().destroy(). NOTE: Iron.init() be called // * before destroy() // */ // public static void clear(Context context) { // init(context); // chest().destroy(); // } // } // Path: iron-encryption/src/main/java/io/fabianterhorst/iron/encryption/IronEncryption.java import android.util.Log; import org.apache.commons.io.IOUtils; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.GeneralSecurityException; import java.security.SecureRandom; import java.util.concurrent.atomic.AtomicBoolean; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.CipherOutputStream; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import io.fabianterhorst.iron.Encryption; import io.fabianterhorst.iron.Iron; @Override public Cipher getCipher(int mode){ try { byte[] iv = generateIv(); Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION); cipher.init(mode, mKey.getConfidentialityKey(), new IvParameterSpec(iv)); return cipher; }catch(GeneralSecurityException e){ e.printStackTrace(); } return null; } @Override public ByteArrayInputStream decrypt(InputStream inputStream) { CipherInputStream cipherInputStream = new CipherInputStream(inputStream, getCipher(Cipher.DECRYPT_MODE)); try { return new ByteArrayInputStream(IOUtils.toByteArray(cipherInputStream)); }catch(IOException io){ io.printStackTrace(); } return null; } @Override public CipherOutputStream encrypt(OutputStream outputStream) { return new CipherOutputStream(outputStream, getCipher(Cipher.ENCRYPT_MODE)); } public AesCbcWithIntegrity.SecretKeys getKey() {
AesCbcWithIntegrity.SecretKeys key = Iron.chest("keys").read("key");
FabianTerhorst/Iron
iron-retrofit/src/main/java/io/fabianterhorst/iron/retrofit/IronRetrofit.java
// Path: iron/src/main/java/io/fabianterhorst/iron/Iron.java // public class Iron { // public static final String DEFAULT_DB_NAME = "io.iron"; // // private static Context mContext; // // private static Loader mLoader; // // private static Encryption mEncryption; // // private static int mCache = Cache.NONE; // // private static final ConcurrentHashMap<String, Chest> mChestMap = new ConcurrentHashMap<>(); // // /** // * Lightweight method to init Iron instance. Should be executed in {@link Application#onCreate()} // * // * @param context context, used to get application context // */ // public static void init(Context context) { // mContext = context.getApplicationContext(); // } // // /** // * Set the loader to the Iron instance // * // * @param loader loader extension for the iron instance // */ // public static void setLoader(Loader loader) { // mLoader = loader; // } // // /** // * Set the encryption to the Iron instance // * // * @param encryption encryption extension for the iron instance // */ // public static void setEncryption(Encryption encryption) { // mEncryption = encryption; // } // // /** // * Set the cache strategy to store the written objects in memory // * // * @param cache the cache strategy Cache#Memory or Cache#NONE // */ // public static void setCache(int cache) { // mCache = cache; // } // // /** // * Returns Iron chest instance with the given name // * // * @param name name of new database // * @return Iron instance // */ // public static Chest chest(String name) { // if (name.equals(DEFAULT_DB_NAME)) throw new IronException(DEFAULT_DB_NAME + // " name is reserved for default library name"); // return getChest(name); // } // // /** // * Returns default iron chest instance // * // * @return Chest instance // */ // public static Chest chest() { // return getChest(DEFAULT_DB_NAME); // } // // private static Chest getChest(String name) { // if (mContext == null) { // throw new IronException("Iron.init is not called"); // } // synchronized (mChestMap) { // Chest chest = mChestMap.get(name); // if (chest == null) { // chest = new Chest(mContext, name, mLoader, mEncryption, mCache); // mChestMap.put(name, chest); // } // return chest; // } // } // // /** // * @deprecated use Iron.chest().write() // */ // public static <T> Chest put(String key, T value) { // return chest().write(key, value); // } // // /** // * @deprecated use Iron.chest().read() // */ // public static <T> T get(String key) { // return chest().read(key); // } // // /** // * @deprecated use Iron.chest().read() // */ // public static <T> T get(String key, T defaultValue) { // return chest().read(key, defaultValue); // } // // /** // * @deprecated use Iron.chest().exist() // */ // public static boolean exist(String key) { // return chest().exist(key); // } // // /** // * @deprecated use Iron.chest().delete() // */ // public static void delete(String key) { // chest().delete(key); // } // // /** // * @deprecated use Iron.chest().destroy(). NOTE: Iron.init() be called // * before destroy() // */ // public static void clear(Context context) { // init(context); // chest().destroy(); // } // } // // Path: iron/src/main/java/io/fabianterhorst/iron/Loader.java // public interface Loader { // <T> void load(T call, final String key); // }
import io.fabianterhorst.iron.Iron; import io.fabianterhorst.iron.Loader; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response;
package io.fabianterhorst.iron.retrofit; public class IronRetrofit implements Loader { @SuppressWarnings("unchecked") public <T> void load(T call, final String key) { if (call instanceof Call) { ((Call<T>) call).enqueue(new Callback<T>() { @Override public void onResponse(Call<T> call, Response<T> response) { if (response.isSuccessful())
// Path: iron/src/main/java/io/fabianterhorst/iron/Iron.java // public class Iron { // public static final String DEFAULT_DB_NAME = "io.iron"; // // private static Context mContext; // // private static Loader mLoader; // // private static Encryption mEncryption; // // private static int mCache = Cache.NONE; // // private static final ConcurrentHashMap<String, Chest> mChestMap = new ConcurrentHashMap<>(); // // /** // * Lightweight method to init Iron instance. Should be executed in {@link Application#onCreate()} // * // * @param context context, used to get application context // */ // public static void init(Context context) { // mContext = context.getApplicationContext(); // } // // /** // * Set the loader to the Iron instance // * // * @param loader loader extension for the iron instance // */ // public static void setLoader(Loader loader) { // mLoader = loader; // } // // /** // * Set the encryption to the Iron instance // * // * @param encryption encryption extension for the iron instance // */ // public static void setEncryption(Encryption encryption) { // mEncryption = encryption; // } // // /** // * Set the cache strategy to store the written objects in memory // * // * @param cache the cache strategy Cache#Memory or Cache#NONE // */ // public static void setCache(int cache) { // mCache = cache; // } // // /** // * Returns Iron chest instance with the given name // * // * @param name name of new database // * @return Iron instance // */ // public static Chest chest(String name) { // if (name.equals(DEFAULT_DB_NAME)) throw new IronException(DEFAULT_DB_NAME + // " name is reserved for default library name"); // return getChest(name); // } // // /** // * Returns default iron chest instance // * // * @return Chest instance // */ // public static Chest chest() { // return getChest(DEFAULT_DB_NAME); // } // // private static Chest getChest(String name) { // if (mContext == null) { // throw new IronException("Iron.init is not called"); // } // synchronized (mChestMap) { // Chest chest = mChestMap.get(name); // if (chest == null) { // chest = new Chest(mContext, name, mLoader, mEncryption, mCache); // mChestMap.put(name, chest); // } // return chest; // } // } // // /** // * @deprecated use Iron.chest().write() // */ // public static <T> Chest put(String key, T value) { // return chest().write(key, value); // } // // /** // * @deprecated use Iron.chest().read() // */ // public static <T> T get(String key) { // return chest().read(key); // } // // /** // * @deprecated use Iron.chest().read() // */ // public static <T> T get(String key, T defaultValue) { // return chest().read(key, defaultValue); // } // // /** // * @deprecated use Iron.chest().exist() // */ // public static boolean exist(String key) { // return chest().exist(key); // } // // /** // * @deprecated use Iron.chest().delete() // */ // public static void delete(String key) { // chest().delete(key); // } // // /** // * @deprecated use Iron.chest().destroy(). NOTE: Iron.init() be called // * before destroy() // */ // public static void clear(Context context) { // init(context); // chest().destroy(); // } // } // // Path: iron/src/main/java/io/fabianterhorst/iron/Loader.java // public interface Loader { // <T> void load(T call, final String key); // } // Path: iron-retrofit/src/main/java/io/fabianterhorst/iron/retrofit/IronRetrofit.java import io.fabianterhorst.iron.Iron; import io.fabianterhorst.iron.Loader; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; package io.fabianterhorst.iron.retrofit; public class IronRetrofit implements Loader { @SuppressWarnings("unchecked") public <T> void load(T call, final String key) { if (call instanceof Call) { ((Call<T>) call).enqueue(new Callback<T>() { @Override public void onResponse(Call<T> call, Response<T> response) { if (response.isSuccessful())
Iron.chest().write(key, response.body());
FabianTerhorst/Iron
app/src/main/java/io/fabianterhorst/iron/sample/MyApplication.java
// Path: iron/src/main/java/io/fabianterhorst/iron/Cache.java // public interface Cache { // int NONE = 1; // // int MEMORY = 2; // // void evictAll(); // // Object put(String key, Object value); // // Object get(String key); // // Object remove(String key); // } // // Path: iron/src/main/java/io/fabianterhorst/iron/Iron.java // public class Iron { // public static final String DEFAULT_DB_NAME = "io.iron"; // // private static Context mContext; // // private static Loader mLoader; // // private static Encryption mEncryption; // // private static int mCache = Cache.NONE; // // private static final ConcurrentHashMap<String, Chest> mChestMap = new ConcurrentHashMap<>(); // // /** // * Lightweight method to init Iron instance. Should be executed in {@link Application#onCreate()} // * // * @param context context, used to get application context // */ // public static void init(Context context) { // mContext = context.getApplicationContext(); // } // // /** // * Set the loader to the Iron instance // * // * @param loader loader extension for the iron instance // */ // public static void setLoader(Loader loader) { // mLoader = loader; // } // // /** // * Set the encryption to the Iron instance // * // * @param encryption encryption extension for the iron instance // */ // public static void setEncryption(Encryption encryption) { // mEncryption = encryption; // } // // /** // * Set the cache strategy to store the written objects in memory // * // * @param cache the cache strategy Cache#Memory or Cache#NONE // */ // public static void setCache(int cache) { // mCache = cache; // } // // /** // * Returns Iron chest instance with the given name // * // * @param name name of new database // * @return Iron instance // */ // public static Chest chest(String name) { // if (name.equals(DEFAULT_DB_NAME)) throw new IronException(DEFAULT_DB_NAME + // " name is reserved for default library name"); // return getChest(name); // } // // /** // * Returns default iron chest instance // * // * @return Chest instance // */ // public static Chest chest() { // return getChest(DEFAULT_DB_NAME); // } // // private static Chest getChest(String name) { // if (mContext == null) { // throw new IronException("Iron.init is not called"); // } // synchronized (mChestMap) { // Chest chest = mChestMap.get(name); // if (chest == null) { // chest = new Chest(mContext, name, mLoader, mEncryption, mCache); // mChestMap.put(name, chest); // } // return chest; // } // } // // /** // * @deprecated use Iron.chest().write() // */ // public static <T> Chest put(String key, T value) { // return chest().write(key, value); // } // // /** // * @deprecated use Iron.chest().read() // */ // public static <T> T get(String key) { // return chest().read(key); // } // // /** // * @deprecated use Iron.chest().read() // */ // public static <T> T get(String key, T defaultValue) { // return chest().read(key, defaultValue); // } // // /** // * @deprecated use Iron.chest().exist() // */ // public static boolean exist(String key) { // return chest().exist(key); // } // // /** // * @deprecated use Iron.chest().delete() // */ // public static void delete(String key) { // chest().delete(key); // } // // /** // * @deprecated use Iron.chest().destroy(). NOTE: Iron.init() be called // * before destroy() // */ // public static void clear(Context context) { // init(context); // chest().destroy(); // } // } // // Path: iron-retrofit/src/main/java/io/fabianterhorst/iron/retrofit/IronRetrofit.java // public class IronRetrofit implements Loader { // @SuppressWarnings("unchecked") // public <T> void load(T call, final String key) { // if (call instanceof Call) { // ((Call<T>) call).enqueue(new Callback<T>() { // @Override // public void onResponse(Call<T> call, Response<T> response) { // if (response.isSuccessful()) // Iron.chest().write(key, response.body()); // } // // @Override // public void onFailure(Call<T> call, Throwable t) { // t.printStackTrace(); // } // }); // } // } // }
import android.app.Application; import io.fabianterhorst.iron.Cache; import io.fabianterhorst.iron.Iron; import io.fabianterhorst.iron.retrofit.IronRetrofit;
package io.fabianterhorst.iron.sample; public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); //Todo : Iron builder
// Path: iron/src/main/java/io/fabianterhorst/iron/Cache.java // public interface Cache { // int NONE = 1; // // int MEMORY = 2; // // void evictAll(); // // Object put(String key, Object value); // // Object get(String key); // // Object remove(String key); // } // // Path: iron/src/main/java/io/fabianterhorst/iron/Iron.java // public class Iron { // public static final String DEFAULT_DB_NAME = "io.iron"; // // private static Context mContext; // // private static Loader mLoader; // // private static Encryption mEncryption; // // private static int mCache = Cache.NONE; // // private static final ConcurrentHashMap<String, Chest> mChestMap = new ConcurrentHashMap<>(); // // /** // * Lightweight method to init Iron instance. Should be executed in {@link Application#onCreate()} // * // * @param context context, used to get application context // */ // public static void init(Context context) { // mContext = context.getApplicationContext(); // } // // /** // * Set the loader to the Iron instance // * // * @param loader loader extension for the iron instance // */ // public static void setLoader(Loader loader) { // mLoader = loader; // } // // /** // * Set the encryption to the Iron instance // * // * @param encryption encryption extension for the iron instance // */ // public static void setEncryption(Encryption encryption) { // mEncryption = encryption; // } // // /** // * Set the cache strategy to store the written objects in memory // * // * @param cache the cache strategy Cache#Memory or Cache#NONE // */ // public static void setCache(int cache) { // mCache = cache; // } // // /** // * Returns Iron chest instance with the given name // * // * @param name name of new database // * @return Iron instance // */ // public static Chest chest(String name) { // if (name.equals(DEFAULT_DB_NAME)) throw new IronException(DEFAULT_DB_NAME + // " name is reserved for default library name"); // return getChest(name); // } // // /** // * Returns default iron chest instance // * // * @return Chest instance // */ // public static Chest chest() { // return getChest(DEFAULT_DB_NAME); // } // // private static Chest getChest(String name) { // if (mContext == null) { // throw new IronException("Iron.init is not called"); // } // synchronized (mChestMap) { // Chest chest = mChestMap.get(name); // if (chest == null) { // chest = new Chest(mContext, name, mLoader, mEncryption, mCache); // mChestMap.put(name, chest); // } // return chest; // } // } // // /** // * @deprecated use Iron.chest().write() // */ // public static <T> Chest put(String key, T value) { // return chest().write(key, value); // } // // /** // * @deprecated use Iron.chest().read() // */ // public static <T> T get(String key) { // return chest().read(key); // } // // /** // * @deprecated use Iron.chest().read() // */ // public static <T> T get(String key, T defaultValue) { // return chest().read(key, defaultValue); // } // // /** // * @deprecated use Iron.chest().exist() // */ // public static boolean exist(String key) { // return chest().exist(key); // } // // /** // * @deprecated use Iron.chest().delete() // */ // public static void delete(String key) { // chest().delete(key); // } // // /** // * @deprecated use Iron.chest().destroy(). NOTE: Iron.init() be called // * before destroy() // */ // public static void clear(Context context) { // init(context); // chest().destroy(); // } // } // // Path: iron-retrofit/src/main/java/io/fabianterhorst/iron/retrofit/IronRetrofit.java // public class IronRetrofit implements Loader { // @SuppressWarnings("unchecked") // public <T> void load(T call, final String key) { // if (call instanceof Call) { // ((Call<T>) call).enqueue(new Callback<T>() { // @Override // public void onResponse(Call<T> call, Response<T> response) { // if (response.isSuccessful()) // Iron.chest().write(key, response.body()); // } // // @Override // public void onFailure(Call<T> call, Throwable t) { // t.printStackTrace(); // } // }); // } // } // } // Path: app/src/main/java/io/fabianterhorst/iron/sample/MyApplication.java import android.app.Application; import io.fabianterhorst.iron.Cache; import io.fabianterhorst.iron.Iron; import io.fabianterhorst.iron.retrofit.IronRetrofit; package io.fabianterhorst.iron.sample; public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); //Todo : Iron builder
Iron.init(getApplicationContext());
FabianTerhorst/Iron
app/src/main/java/io/fabianterhorst/iron/sample/MyApplication.java
// Path: iron/src/main/java/io/fabianterhorst/iron/Cache.java // public interface Cache { // int NONE = 1; // // int MEMORY = 2; // // void evictAll(); // // Object put(String key, Object value); // // Object get(String key); // // Object remove(String key); // } // // Path: iron/src/main/java/io/fabianterhorst/iron/Iron.java // public class Iron { // public static final String DEFAULT_DB_NAME = "io.iron"; // // private static Context mContext; // // private static Loader mLoader; // // private static Encryption mEncryption; // // private static int mCache = Cache.NONE; // // private static final ConcurrentHashMap<String, Chest> mChestMap = new ConcurrentHashMap<>(); // // /** // * Lightweight method to init Iron instance. Should be executed in {@link Application#onCreate()} // * // * @param context context, used to get application context // */ // public static void init(Context context) { // mContext = context.getApplicationContext(); // } // // /** // * Set the loader to the Iron instance // * // * @param loader loader extension for the iron instance // */ // public static void setLoader(Loader loader) { // mLoader = loader; // } // // /** // * Set the encryption to the Iron instance // * // * @param encryption encryption extension for the iron instance // */ // public static void setEncryption(Encryption encryption) { // mEncryption = encryption; // } // // /** // * Set the cache strategy to store the written objects in memory // * // * @param cache the cache strategy Cache#Memory or Cache#NONE // */ // public static void setCache(int cache) { // mCache = cache; // } // // /** // * Returns Iron chest instance with the given name // * // * @param name name of new database // * @return Iron instance // */ // public static Chest chest(String name) { // if (name.equals(DEFAULT_DB_NAME)) throw new IronException(DEFAULT_DB_NAME + // " name is reserved for default library name"); // return getChest(name); // } // // /** // * Returns default iron chest instance // * // * @return Chest instance // */ // public static Chest chest() { // return getChest(DEFAULT_DB_NAME); // } // // private static Chest getChest(String name) { // if (mContext == null) { // throw new IronException("Iron.init is not called"); // } // synchronized (mChestMap) { // Chest chest = mChestMap.get(name); // if (chest == null) { // chest = new Chest(mContext, name, mLoader, mEncryption, mCache); // mChestMap.put(name, chest); // } // return chest; // } // } // // /** // * @deprecated use Iron.chest().write() // */ // public static <T> Chest put(String key, T value) { // return chest().write(key, value); // } // // /** // * @deprecated use Iron.chest().read() // */ // public static <T> T get(String key) { // return chest().read(key); // } // // /** // * @deprecated use Iron.chest().read() // */ // public static <T> T get(String key, T defaultValue) { // return chest().read(key, defaultValue); // } // // /** // * @deprecated use Iron.chest().exist() // */ // public static boolean exist(String key) { // return chest().exist(key); // } // // /** // * @deprecated use Iron.chest().delete() // */ // public static void delete(String key) { // chest().delete(key); // } // // /** // * @deprecated use Iron.chest().destroy(). NOTE: Iron.init() be called // * before destroy() // */ // public static void clear(Context context) { // init(context); // chest().destroy(); // } // } // // Path: iron-retrofit/src/main/java/io/fabianterhorst/iron/retrofit/IronRetrofit.java // public class IronRetrofit implements Loader { // @SuppressWarnings("unchecked") // public <T> void load(T call, final String key) { // if (call instanceof Call) { // ((Call<T>) call).enqueue(new Callback<T>() { // @Override // public void onResponse(Call<T> call, Response<T> response) { // if (response.isSuccessful()) // Iron.chest().write(key, response.body()); // } // // @Override // public void onFailure(Call<T> call, Throwable t) { // t.printStackTrace(); // } // }); // } // } // }
import android.app.Application; import io.fabianterhorst.iron.Cache; import io.fabianterhorst.iron.Iron; import io.fabianterhorst.iron.retrofit.IronRetrofit;
package io.fabianterhorst.iron.sample; public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); //Todo : Iron builder Iron.init(getApplicationContext());
// Path: iron/src/main/java/io/fabianterhorst/iron/Cache.java // public interface Cache { // int NONE = 1; // // int MEMORY = 2; // // void evictAll(); // // Object put(String key, Object value); // // Object get(String key); // // Object remove(String key); // } // // Path: iron/src/main/java/io/fabianterhorst/iron/Iron.java // public class Iron { // public static final String DEFAULT_DB_NAME = "io.iron"; // // private static Context mContext; // // private static Loader mLoader; // // private static Encryption mEncryption; // // private static int mCache = Cache.NONE; // // private static final ConcurrentHashMap<String, Chest> mChestMap = new ConcurrentHashMap<>(); // // /** // * Lightweight method to init Iron instance. Should be executed in {@link Application#onCreate()} // * // * @param context context, used to get application context // */ // public static void init(Context context) { // mContext = context.getApplicationContext(); // } // // /** // * Set the loader to the Iron instance // * // * @param loader loader extension for the iron instance // */ // public static void setLoader(Loader loader) { // mLoader = loader; // } // // /** // * Set the encryption to the Iron instance // * // * @param encryption encryption extension for the iron instance // */ // public static void setEncryption(Encryption encryption) { // mEncryption = encryption; // } // // /** // * Set the cache strategy to store the written objects in memory // * // * @param cache the cache strategy Cache#Memory or Cache#NONE // */ // public static void setCache(int cache) { // mCache = cache; // } // // /** // * Returns Iron chest instance with the given name // * // * @param name name of new database // * @return Iron instance // */ // public static Chest chest(String name) { // if (name.equals(DEFAULT_DB_NAME)) throw new IronException(DEFAULT_DB_NAME + // " name is reserved for default library name"); // return getChest(name); // } // // /** // * Returns default iron chest instance // * // * @return Chest instance // */ // public static Chest chest() { // return getChest(DEFAULT_DB_NAME); // } // // private static Chest getChest(String name) { // if (mContext == null) { // throw new IronException("Iron.init is not called"); // } // synchronized (mChestMap) { // Chest chest = mChestMap.get(name); // if (chest == null) { // chest = new Chest(mContext, name, mLoader, mEncryption, mCache); // mChestMap.put(name, chest); // } // return chest; // } // } // // /** // * @deprecated use Iron.chest().write() // */ // public static <T> Chest put(String key, T value) { // return chest().write(key, value); // } // // /** // * @deprecated use Iron.chest().read() // */ // public static <T> T get(String key) { // return chest().read(key); // } // // /** // * @deprecated use Iron.chest().read() // */ // public static <T> T get(String key, T defaultValue) { // return chest().read(key, defaultValue); // } // // /** // * @deprecated use Iron.chest().exist() // */ // public static boolean exist(String key) { // return chest().exist(key); // } // // /** // * @deprecated use Iron.chest().delete() // */ // public static void delete(String key) { // chest().delete(key); // } // // /** // * @deprecated use Iron.chest().destroy(). NOTE: Iron.init() be called // * before destroy() // */ // public static void clear(Context context) { // init(context); // chest().destroy(); // } // } // // Path: iron-retrofit/src/main/java/io/fabianterhorst/iron/retrofit/IronRetrofit.java // public class IronRetrofit implements Loader { // @SuppressWarnings("unchecked") // public <T> void load(T call, final String key) { // if (call instanceof Call) { // ((Call<T>) call).enqueue(new Callback<T>() { // @Override // public void onResponse(Call<T> call, Response<T> response) { // if (response.isSuccessful()) // Iron.chest().write(key, response.body()); // } // // @Override // public void onFailure(Call<T> call, Throwable t) { // t.printStackTrace(); // } // }); // } // } // } // Path: app/src/main/java/io/fabianterhorst/iron/sample/MyApplication.java import android.app.Application; import io.fabianterhorst.iron.Cache; import io.fabianterhorst.iron.Iron; import io.fabianterhorst.iron.retrofit.IronRetrofit; package io.fabianterhorst.iron.sample; public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); //Todo : Iron builder Iron.init(getApplicationContext());
Iron.setCache(Cache.MEMORY);
FabianTerhorst/Iron
app/src/main/java/io/fabianterhorst/iron/sample/MyApplication.java
// Path: iron/src/main/java/io/fabianterhorst/iron/Cache.java // public interface Cache { // int NONE = 1; // // int MEMORY = 2; // // void evictAll(); // // Object put(String key, Object value); // // Object get(String key); // // Object remove(String key); // } // // Path: iron/src/main/java/io/fabianterhorst/iron/Iron.java // public class Iron { // public static final String DEFAULT_DB_NAME = "io.iron"; // // private static Context mContext; // // private static Loader mLoader; // // private static Encryption mEncryption; // // private static int mCache = Cache.NONE; // // private static final ConcurrentHashMap<String, Chest> mChestMap = new ConcurrentHashMap<>(); // // /** // * Lightweight method to init Iron instance. Should be executed in {@link Application#onCreate()} // * // * @param context context, used to get application context // */ // public static void init(Context context) { // mContext = context.getApplicationContext(); // } // // /** // * Set the loader to the Iron instance // * // * @param loader loader extension for the iron instance // */ // public static void setLoader(Loader loader) { // mLoader = loader; // } // // /** // * Set the encryption to the Iron instance // * // * @param encryption encryption extension for the iron instance // */ // public static void setEncryption(Encryption encryption) { // mEncryption = encryption; // } // // /** // * Set the cache strategy to store the written objects in memory // * // * @param cache the cache strategy Cache#Memory or Cache#NONE // */ // public static void setCache(int cache) { // mCache = cache; // } // // /** // * Returns Iron chest instance with the given name // * // * @param name name of new database // * @return Iron instance // */ // public static Chest chest(String name) { // if (name.equals(DEFAULT_DB_NAME)) throw new IronException(DEFAULT_DB_NAME + // " name is reserved for default library name"); // return getChest(name); // } // // /** // * Returns default iron chest instance // * // * @return Chest instance // */ // public static Chest chest() { // return getChest(DEFAULT_DB_NAME); // } // // private static Chest getChest(String name) { // if (mContext == null) { // throw new IronException("Iron.init is not called"); // } // synchronized (mChestMap) { // Chest chest = mChestMap.get(name); // if (chest == null) { // chest = new Chest(mContext, name, mLoader, mEncryption, mCache); // mChestMap.put(name, chest); // } // return chest; // } // } // // /** // * @deprecated use Iron.chest().write() // */ // public static <T> Chest put(String key, T value) { // return chest().write(key, value); // } // // /** // * @deprecated use Iron.chest().read() // */ // public static <T> T get(String key) { // return chest().read(key); // } // // /** // * @deprecated use Iron.chest().read() // */ // public static <T> T get(String key, T defaultValue) { // return chest().read(key, defaultValue); // } // // /** // * @deprecated use Iron.chest().exist() // */ // public static boolean exist(String key) { // return chest().exist(key); // } // // /** // * @deprecated use Iron.chest().delete() // */ // public static void delete(String key) { // chest().delete(key); // } // // /** // * @deprecated use Iron.chest().destroy(). NOTE: Iron.init() be called // * before destroy() // */ // public static void clear(Context context) { // init(context); // chest().destroy(); // } // } // // Path: iron-retrofit/src/main/java/io/fabianterhorst/iron/retrofit/IronRetrofit.java // public class IronRetrofit implements Loader { // @SuppressWarnings("unchecked") // public <T> void load(T call, final String key) { // if (call instanceof Call) { // ((Call<T>) call).enqueue(new Callback<T>() { // @Override // public void onResponse(Call<T> call, Response<T> response) { // if (response.isSuccessful()) // Iron.chest().write(key, response.body()); // } // // @Override // public void onFailure(Call<T> call, Throwable t) { // t.printStackTrace(); // } // }); // } // } // }
import android.app.Application; import io.fabianterhorst.iron.Cache; import io.fabianterhorst.iron.Iron; import io.fabianterhorst.iron.retrofit.IronRetrofit;
package io.fabianterhorst.iron.sample; public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); //Todo : Iron builder Iron.init(getApplicationContext()); Iron.setCache(Cache.MEMORY);
// Path: iron/src/main/java/io/fabianterhorst/iron/Cache.java // public interface Cache { // int NONE = 1; // // int MEMORY = 2; // // void evictAll(); // // Object put(String key, Object value); // // Object get(String key); // // Object remove(String key); // } // // Path: iron/src/main/java/io/fabianterhorst/iron/Iron.java // public class Iron { // public static final String DEFAULT_DB_NAME = "io.iron"; // // private static Context mContext; // // private static Loader mLoader; // // private static Encryption mEncryption; // // private static int mCache = Cache.NONE; // // private static final ConcurrentHashMap<String, Chest> mChestMap = new ConcurrentHashMap<>(); // // /** // * Lightweight method to init Iron instance. Should be executed in {@link Application#onCreate()} // * // * @param context context, used to get application context // */ // public static void init(Context context) { // mContext = context.getApplicationContext(); // } // // /** // * Set the loader to the Iron instance // * // * @param loader loader extension for the iron instance // */ // public static void setLoader(Loader loader) { // mLoader = loader; // } // // /** // * Set the encryption to the Iron instance // * // * @param encryption encryption extension for the iron instance // */ // public static void setEncryption(Encryption encryption) { // mEncryption = encryption; // } // // /** // * Set the cache strategy to store the written objects in memory // * // * @param cache the cache strategy Cache#Memory or Cache#NONE // */ // public static void setCache(int cache) { // mCache = cache; // } // // /** // * Returns Iron chest instance with the given name // * // * @param name name of new database // * @return Iron instance // */ // public static Chest chest(String name) { // if (name.equals(DEFAULT_DB_NAME)) throw new IronException(DEFAULT_DB_NAME + // " name is reserved for default library name"); // return getChest(name); // } // // /** // * Returns default iron chest instance // * // * @return Chest instance // */ // public static Chest chest() { // return getChest(DEFAULT_DB_NAME); // } // // private static Chest getChest(String name) { // if (mContext == null) { // throw new IronException("Iron.init is not called"); // } // synchronized (mChestMap) { // Chest chest = mChestMap.get(name); // if (chest == null) { // chest = new Chest(mContext, name, mLoader, mEncryption, mCache); // mChestMap.put(name, chest); // } // return chest; // } // } // // /** // * @deprecated use Iron.chest().write() // */ // public static <T> Chest put(String key, T value) { // return chest().write(key, value); // } // // /** // * @deprecated use Iron.chest().read() // */ // public static <T> T get(String key) { // return chest().read(key); // } // // /** // * @deprecated use Iron.chest().read() // */ // public static <T> T get(String key, T defaultValue) { // return chest().read(key, defaultValue); // } // // /** // * @deprecated use Iron.chest().exist() // */ // public static boolean exist(String key) { // return chest().exist(key); // } // // /** // * @deprecated use Iron.chest().delete() // */ // public static void delete(String key) { // chest().delete(key); // } // // /** // * @deprecated use Iron.chest().destroy(). NOTE: Iron.init() be called // * before destroy() // */ // public static void clear(Context context) { // init(context); // chest().destroy(); // } // } // // Path: iron-retrofit/src/main/java/io/fabianterhorst/iron/retrofit/IronRetrofit.java // public class IronRetrofit implements Loader { // @SuppressWarnings("unchecked") // public <T> void load(T call, final String key) { // if (call instanceof Call) { // ((Call<T>) call).enqueue(new Callback<T>() { // @Override // public void onResponse(Call<T> call, Response<T> response) { // if (response.isSuccessful()) // Iron.chest().write(key, response.body()); // } // // @Override // public void onFailure(Call<T> call, Throwable t) { // t.printStackTrace(); // } // }); // } // } // } // Path: app/src/main/java/io/fabianterhorst/iron/sample/MyApplication.java import android.app.Application; import io.fabianterhorst.iron.Cache; import io.fabianterhorst.iron.Iron; import io.fabianterhorst.iron.retrofit.IronRetrofit; package io.fabianterhorst.iron.sample; public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); //Todo : Iron builder Iron.init(getApplicationContext()); Iron.setCache(Cache.MEMORY);
Iron.setLoader(new IronRetrofit());
FabianTerhorst/Iron
iron/src/androidTest/java/io/fabianterhorst/iron/DataTest.java
// Path: iron/src/androidTest/java/io/fabianterhorst/iron/testdata/Person.java // public class Person { // private String mName; // private int mAge; // private List<String> mPhoneNumbers; // private String[] mBikes; // // public String getName() { // return mName; // } // // public void setName(String name) { // mName = name; // } // // public int getAge() { // return mAge; // } // // public void setAge(int age) { // mAge = age; // } // // public List<String> getPhoneNumbers() { // return mPhoneNumbers; // } // // public void setPhoneNumbers(List<String> phoneNumbers) { // mPhoneNumbers = phoneNumbers; // } // // public String[] getBikes() { // return mBikes; // } // // public void setBikes(String[] bikes) { // mBikes = bikes; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || Person.class != o.getClass()) return false; // Person person = (Person) o; // return mAge == person.mAge && Arrays.equals(mBikes, person.mBikes) && (mName != null ? mName.equals(person.mName) : person.mName == null && (mPhoneNumbers != null ? mPhoneNumbers.equals(person.mPhoneNumbers) : person.mPhoneNumbers == null)); // } // // @Override // public int hashCode() { // int result = mName != null ? mName.hashCode() : 0; // result = 31 * result + mAge; // result = 31 * result + (mPhoneNumbers != null ? mPhoneNumbers.hashCode() : 0); // result = 31 * result + (mBikes != null ? Arrays.hashCode(mBikes) : 0); // return result; // } // } // // Path: iron/src/androidTest/java/io/fabianterhorst/iron/testdata/PersonArg.java // public class PersonArg extends Person { // public PersonArg(String name) { // super(); // setName("changed" + name); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || PersonArg.class != o.getClass()) return false; // // PersonArg person = (PersonArg) o; // // if (getAge() != person.getAge()) return false; // if (!Arrays.equals(getBikes(), person.getBikes())) return false; // if (getName() != null ? !getName().equals(person.getName()) : person.getName() != null) // return false; // //noinspection RedundantIfStatement // if (getPhoneNumbers() != null // ? !getPhoneNumbers().equals(person.getPhoneNumbers()) // : person.getPhoneNumbers() != null) // return false; // // return true; // } // // @Override // public int hashCode() { // return super.hashCode(); // } // } // // Path: iron/src/androidTest/java/io/fabianterhorst/iron/testdata/TestDataGenerator.java // @NonNull // public static <T extends Person> T genPerson(T p, int i) { // p.setAge(i); // p.setBikes(new String[2]); // p.getBikes()[0] = "Kellys gen#" + i; // p.getBikes()[1] = "Trek gen#" + i; // p.setPhoneNumbers(new ArrayList<String>()); // p.getPhoneNumbers().add("0-KEEP-CALM" + i); // p.getPhoneNumbers().add("0-USE-IRON" + i); // return p; // } // // Path: iron/src/androidTest/java/io/fabianterhorst/iron/testdata/TestDataGenerator.java // public static List<Person> genPersonList(int size) { // List<Person> list = new ArrayList<>(); // for (int i = 0; i < size; i++) { // Person p = genPerson(new Person(), i); // list.add(p); // } // return list; // } // // Path: iron/src/androidTest/java/io/fabianterhorst/iron/testdata/TestDataGenerator.java // public static Map<Integer, Person> genPersonMap(int size) { // HashMap<Integer, Person> map = new HashMap<>(); // int i = 0; // for (Person person : genPersonList(size)) { // map.put(i++, person); // } // return map; // }
import android.support.test.runner.AndroidJUnit4; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.GregorianCalendar; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import io.fabianterhorst.iron.testdata.Person; import io.fabianterhorst.iron.testdata.PersonArg; import static android.support.test.InstrumentationRegistry.getTargetContext; import static io.fabianterhorst.iron.testdata.TestDataGenerator.genPerson; import static io.fabianterhorst.iron.testdata.TestDataGenerator.genPersonList; import static io.fabianterhorst.iron.testdata.TestDataGenerator.genPersonMap; import static org.assertj.core.api.Assertions.assertThat;
package io.fabianterhorst.iron; /** * Tests List write/read API */ @RunWith(AndroidJUnit4.class) public class DataTest { @Before public void setUp() throws Exception { Iron.init(getTargetContext()); //Iron.setCache(Cache.MEMORY); //Iron.chest("keys").destroy(); Iron.chest().destroy(); //Iron.setEncryptionExtension(new IronEncryption()); } @Test public void testPutEmptyList() throws Exception {
// Path: iron/src/androidTest/java/io/fabianterhorst/iron/testdata/Person.java // public class Person { // private String mName; // private int mAge; // private List<String> mPhoneNumbers; // private String[] mBikes; // // public String getName() { // return mName; // } // // public void setName(String name) { // mName = name; // } // // public int getAge() { // return mAge; // } // // public void setAge(int age) { // mAge = age; // } // // public List<String> getPhoneNumbers() { // return mPhoneNumbers; // } // // public void setPhoneNumbers(List<String> phoneNumbers) { // mPhoneNumbers = phoneNumbers; // } // // public String[] getBikes() { // return mBikes; // } // // public void setBikes(String[] bikes) { // mBikes = bikes; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || Person.class != o.getClass()) return false; // Person person = (Person) o; // return mAge == person.mAge && Arrays.equals(mBikes, person.mBikes) && (mName != null ? mName.equals(person.mName) : person.mName == null && (mPhoneNumbers != null ? mPhoneNumbers.equals(person.mPhoneNumbers) : person.mPhoneNumbers == null)); // } // // @Override // public int hashCode() { // int result = mName != null ? mName.hashCode() : 0; // result = 31 * result + mAge; // result = 31 * result + (mPhoneNumbers != null ? mPhoneNumbers.hashCode() : 0); // result = 31 * result + (mBikes != null ? Arrays.hashCode(mBikes) : 0); // return result; // } // } // // Path: iron/src/androidTest/java/io/fabianterhorst/iron/testdata/PersonArg.java // public class PersonArg extends Person { // public PersonArg(String name) { // super(); // setName("changed" + name); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || PersonArg.class != o.getClass()) return false; // // PersonArg person = (PersonArg) o; // // if (getAge() != person.getAge()) return false; // if (!Arrays.equals(getBikes(), person.getBikes())) return false; // if (getName() != null ? !getName().equals(person.getName()) : person.getName() != null) // return false; // //noinspection RedundantIfStatement // if (getPhoneNumbers() != null // ? !getPhoneNumbers().equals(person.getPhoneNumbers()) // : person.getPhoneNumbers() != null) // return false; // // return true; // } // // @Override // public int hashCode() { // return super.hashCode(); // } // } // // Path: iron/src/androidTest/java/io/fabianterhorst/iron/testdata/TestDataGenerator.java // @NonNull // public static <T extends Person> T genPerson(T p, int i) { // p.setAge(i); // p.setBikes(new String[2]); // p.getBikes()[0] = "Kellys gen#" + i; // p.getBikes()[1] = "Trek gen#" + i; // p.setPhoneNumbers(new ArrayList<String>()); // p.getPhoneNumbers().add("0-KEEP-CALM" + i); // p.getPhoneNumbers().add("0-USE-IRON" + i); // return p; // } // // Path: iron/src/androidTest/java/io/fabianterhorst/iron/testdata/TestDataGenerator.java // public static List<Person> genPersonList(int size) { // List<Person> list = new ArrayList<>(); // for (int i = 0; i < size; i++) { // Person p = genPerson(new Person(), i); // list.add(p); // } // return list; // } // // Path: iron/src/androidTest/java/io/fabianterhorst/iron/testdata/TestDataGenerator.java // public static Map<Integer, Person> genPersonMap(int size) { // HashMap<Integer, Person> map = new HashMap<>(); // int i = 0; // for (Person person : genPersonList(size)) { // map.put(i++, person); // } // return map; // } // Path: iron/src/androidTest/java/io/fabianterhorst/iron/DataTest.java import android.support.test.runner.AndroidJUnit4; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.GregorianCalendar; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import io.fabianterhorst.iron.testdata.Person; import io.fabianterhorst.iron.testdata.PersonArg; import static android.support.test.InstrumentationRegistry.getTargetContext; import static io.fabianterhorst.iron.testdata.TestDataGenerator.genPerson; import static io.fabianterhorst.iron.testdata.TestDataGenerator.genPersonList; import static io.fabianterhorst.iron.testdata.TestDataGenerator.genPersonMap; import static org.assertj.core.api.Assertions.assertThat; package io.fabianterhorst.iron; /** * Tests List write/read API */ @RunWith(AndroidJUnit4.class) public class DataTest { @Before public void setUp() throws Exception { Iron.init(getTargetContext()); //Iron.setCache(Cache.MEMORY); //Iron.chest("keys").destroy(); Iron.chest().destroy(); //Iron.setEncryptionExtension(new IronEncryption()); } @Test public void testPutEmptyList() throws Exception {
final List<Person> inserted = genPersonList(0);
FabianTerhorst/Iron
iron/src/androidTest/java/io/fabianterhorst/iron/DataTest.java
// Path: iron/src/androidTest/java/io/fabianterhorst/iron/testdata/Person.java // public class Person { // private String mName; // private int mAge; // private List<String> mPhoneNumbers; // private String[] mBikes; // // public String getName() { // return mName; // } // // public void setName(String name) { // mName = name; // } // // public int getAge() { // return mAge; // } // // public void setAge(int age) { // mAge = age; // } // // public List<String> getPhoneNumbers() { // return mPhoneNumbers; // } // // public void setPhoneNumbers(List<String> phoneNumbers) { // mPhoneNumbers = phoneNumbers; // } // // public String[] getBikes() { // return mBikes; // } // // public void setBikes(String[] bikes) { // mBikes = bikes; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || Person.class != o.getClass()) return false; // Person person = (Person) o; // return mAge == person.mAge && Arrays.equals(mBikes, person.mBikes) && (mName != null ? mName.equals(person.mName) : person.mName == null && (mPhoneNumbers != null ? mPhoneNumbers.equals(person.mPhoneNumbers) : person.mPhoneNumbers == null)); // } // // @Override // public int hashCode() { // int result = mName != null ? mName.hashCode() : 0; // result = 31 * result + mAge; // result = 31 * result + (mPhoneNumbers != null ? mPhoneNumbers.hashCode() : 0); // result = 31 * result + (mBikes != null ? Arrays.hashCode(mBikes) : 0); // return result; // } // } // // Path: iron/src/androidTest/java/io/fabianterhorst/iron/testdata/PersonArg.java // public class PersonArg extends Person { // public PersonArg(String name) { // super(); // setName("changed" + name); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || PersonArg.class != o.getClass()) return false; // // PersonArg person = (PersonArg) o; // // if (getAge() != person.getAge()) return false; // if (!Arrays.equals(getBikes(), person.getBikes())) return false; // if (getName() != null ? !getName().equals(person.getName()) : person.getName() != null) // return false; // //noinspection RedundantIfStatement // if (getPhoneNumbers() != null // ? !getPhoneNumbers().equals(person.getPhoneNumbers()) // : person.getPhoneNumbers() != null) // return false; // // return true; // } // // @Override // public int hashCode() { // return super.hashCode(); // } // } // // Path: iron/src/androidTest/java/io/fabianterhorst/iron/testdata/TestDataGenerator.java // @NonNull // public static <T extends Person> T genPerson(T p, int i) { // p.setAge(i); // p.setBikes(new String[2]); // p.getBikes()[0] = "Kellys gen#" + i; // p.getBikes()[1] = "Trek gen#" + i; // p.setPhoneNumbers(new ArrayList<String>()); // p.getPhoneNumbers().add("0-KEEP-CALM" + i); // p.getPhoneNumbers().add("0-USE-IRON" + i); // return p; // } // // Path: iron/src/androidTest/java/io/fabianterhorst/iron/testdata/TestDataGenerator.java // public static List<Person> genPersonList(int size) { // List<Person> list = new ArrayList<>(); // for (int i = 0; i < size; i++) { // Person p = genPerson(new Person(), i); // list.add(p); // } // return list; // } // // Path: iron/src/androidTest/java/io/fabianterhorst/iron/testdata/TestDataGenerator.java // public static Map<Integer, Person> genPersonMap(int size) { // HashMap<Integer, Person> map = new HashMap<>(); // int i = 0; // for (Person person : genPersonList(size)) { // map.put(i++, person); // } // return map; // }
import android.support.test.runner.AndroidJUnit4; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.GregorianCalendar; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import io.fabianterhorst.iron.testdata.Person; import io.fabianterhorst.iron.testdata.PersonArg; import static android.support.test.InstrumentationRegistry.getTargetContext; import static io.fabianterhorst.iron.testdata.TestDataGenerator.genPerson; import static io.fabianterhorst.iron.testdata.TestDataGenerator.genPersonList; import static io.fabianterhorst.iron.testdata.TestDataGenerator.genPersonMap; import static org.assertj.core.api.Assertions.assertThat;
package io.fabianterhorst.iron; /** * Tests List write/read API */ @RunWith(AndroidJUnit4.class) public class DataTest { @Before public void setUp() throws Exception { Iron.init(getTargetContext()); //Iron.setCache(Cache.MEMORY); //Iron.chest("keys").destroy(); Iron.chest().destroy(); //Iron.setEncryptionExtension(new IronEncryption()); } @Test public void testPutEmptyList() throws Exception {
// Path: iron/src/androidTest/java/io/fabianterhorst/iron/testdata/Person.java // public class Person { // private String mName; // private int mAge; // private List<String> mPhoneNumbers; // private String[] mBikes; // // public String getName() { // return mName; // } // // public void setName(String name) { // mName = name; // } // // public int getAge() { // return mAge; // } // // public void setAge(int age) { // mAge = age; // } // // public List<String> getPhoneNumbers() { // return mPhoneNumbers; // } // // public void setPhoneNumbers(List<String> phoneNumbers) { // mPhoneNumbers = phoneNumbers; // } // // public String[] getBikes() { // return mBikes; // } // // public void setBikes(String[] bikes) { // mBikes = bikes; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || Person.class != o.getClass()) return false; // Person person = (Person) o; // return mAge == person.mAge && Arrays.equals(mBikes, person.mBikes) && (mName != null ? mName.equals(person.mName) : person.mName == null && (mPhoneNumbers != null ? mPhoneNumbers.equals(person.mPhoneNumbers) : person.mPhoneNumbers == null)); // } // // @Override // public int hashCode() { // int result = mName != null ? mName.hashCode() : 0; // result = 31 * result + mAge; // result = 31 * result + (mPhoneNumbers != null ? mPhoneNumbers.hashCode() : 0); // result = 31 * result + (mBikes != null ? Arrays.hashCode(mBikes) : 0); // return result; // } // } // // Path: iron/src/androidTest/java/io/fabianterhorst/iron/testdata/PersonArg.java // public class PersonArg extends Person { // public PersonArg(String name) { // super(); // setName("changed" + name); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || PersonArg.class != o.getClass()) return false; // // PersonArg person = (PersonArg) o; // // if (getAge() != person.getAge()) return false; // if (!Arrays.equals(getBikes(), person.getBikes())) return false; // if (getName() != null ? !getName().equals(person.getName()) : person.getName() != null) // return false; // //noinspection RedundantIfStatement // if (getPhoneNumbers() != null // ? !getPhoneNumbers().equals(person.getPhoneNumbers()) // : person.getPhoneNumbers() != null) // return false; // // return true; // } // // @Override // public int hashCode() { // return super.hashCode(); // } // } // // Path: iron/src/androidTest/java/io/fabianterhorst/iron/testdata/TestDataGenerator.java // @NonNull // public static <T extends Person> T genPerson(T p, int i) { // p.setAge(i); // p.setBikes(new String[2]); // p.getBikes()[0] = "Kellys gen#" + i; // p.getBikes()[1] = "Trek gen#" + i; // p.setPhoneNumbers(new ArrayList<String>()); // p.getPhoneNumbers().add("0-KEEP-CALM" + i); // p.getPhoneNumbers().add("0-USE-IRON" + i); // return p; // } // // Path: iron/src/androidTest/java/io/fabianterhorst/iron/testdata/TestDataGenerator.java // public static List<Person> genPersonList(int size) { // List<Person> list = new ArrayList<>(); // for (int i = 0; i < size; i++) { // Person p = genPerson(new Person(), i); // list.add(p); // } // return list; // } // // Path: iron/src/androidTest/java/io/fabianterhorst/iron/testdata/TestDataGenerator.java // public static Map<Integer, Person> genPersonMap(int size) { // HashMap<Integer, Person> map = new HashMap<>(); // int i = 0; // for (Person person : genPersonList(size)) { // map.put(i++, person); // } // return map; // } // Path: iron/src/androidTest/java/io/fabianterhorst/iron/DataTest.java import android.support.test.runner.AndroidJUnit4; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.GregorianCalendar; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import io.fabianterhorst.iron.testdata.Person; import io.fabianterhorst.iron.testdata.PersonArg; import static android.support.test.InstrumentationRegistry.getTargetContext; import static io.fabianterhorst.iron.testdata.TestDataGenerator.genPerson; import static io.fabianterhorst.iron.testdata.TestDataGenerator.genPersonList; import static io.fabianterhorst.iron.testdata.TestDataGenerator.genPersonMap; import static org.assertj.core.api.Assertions.assertThat; package io.fabianterhorst.iron; /** * Tests List write/read API */ @RunWith(AndroidJUnit4.class) public class DataTest { @Before public void setUp() throws Exception { Iron.init(getTargetContext()); //Iron.setCache(Cache.MEMORY); //Iron.chest("keys").destroy(); Iron.chest().destroy(); //Iron.setEncryptionExtension(new IronEncryption()); } @Test public void testPutEmptyList() throws Exception {
final List<Person> inserted = genPersonList(0);
FabianTerhorst/Iron
iron/src/androidTest/java/io/fabianterhorst/iron/DataTest.java
// Path: iron/src/androidTest/java/io/fabianterhorst/iron/testdata/Person.java // public class Person { // private String mName; // private int mAge; // private List<String> mPhoneNumbers; // private String[] mBikes; // // public String getName() { // return mName; // } // // public void setName(String name) { // mName = name; // } // // public int getAge() { // return mAge; // } // // public void setAge(int age) { // mAge = age; // } // // public List<String> getPhoneNumbers() { // return mPhoneNumbers; // } // // public void setPhoneNumbers(List<String> phoneNumbers) { // mPhoneNumbers = phoneNumbers; // } // // public String[] getBikes() { // return mBikes; // } // // public void setBikes(String[] bikes) { // mBikes = bikes; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || Person.class != o.getClass()) return false; // Person person = (Person) o; // return mAge == person.mAge && Arrays.equals(mBikes, person.mBikes) && (mName != null ? mName.equals(person.mName) : person.mName == null && (mPhoneNumbers != null ? mPhoneNumbers.equals(person.mPhoneNumbers) : person.mPhoneNumbers == null)); // } // // @Override // public int hashCode() { // int result = mName != null ? mName.hashCode() : 0; // result = 31 * result + mAge; // result = 31 * result + (mPhoneNumbers != null ? mPhoneNumbers.hashCode() : 0); // result = 31 * result + (mBikes != null ? Arrays.hashCode(mBikes) : 0); // return result; // } // } // // Path: iron/src/androidTest/java/io/fabianterhorst/iron/testdata/PersonArg.java // public class PersonArg extends Person { // public PersonArg(String name) { // super(); // setName("changed" + name); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || PersonArg.class != o.getClass()) return false; // // PersonArg person = (PersonArg) o; // // if (getAge() != person.getAge()) return false; // if (!Arrays.equals(getBikes(), person.getBikes())) return false; // if (getName() != null ? !getName().equals(person.getName()) : person.getName() != null) // return false; // //noinspection RedundantIfStatement // if (getPhoneNumbers() != null // ? !getPhoneNumbers().equals(person.getPhoneNumbers()) // : person.getPhoneNumbers() != null) // return false; // // return true; // } // // @Override // public int hashCode() { // return super.hashCode(); // } // } // // Path: iron/src/androidTest/java/io/fabianterhorst/iron/testdata/TestDataGenerator.java // @NonNull // public static <T extends Person> T genPerson(T p, int i) { // p.setAge(i); // p.setBikes(new String[2]); // p.getBikes()[0] = "Kellys gen#" + i; // p.getBikes()[1] = "Trek gen#" + i; // p.setPhoneNumbers(new ArrayList<String>()); // p.getPhoneNumbers().add("0-KEEP-CALM" + i); // p.getPhoneNumbers().add("0-USE-IRON" + i); // return p; // } // // Path: iron/src/androidTest/java/io/fabianterhorst/iron/testdata/TestDataGenerator.java // public static List<Person> genPersonList(int size) { // List<Person> list = new ArrayList<>(); // for (int i = 0; i < size; i++) { // Person p = genPerson(new Person(), i); // list.add(p); // } // return list; // } // // Path: iron/src/androidTest/java/io/fabianterhorst/iron/testdata/TestDataGenerator.java // public static Map<Integer, Person> genPersonMap(int size) { // HashMap<Integer, Person> map = new HashMap<>(); // int i = 0; // for (Person person : genPersonList(size)) { // map.put(i++, person); // } // return map; // }
import android.support.test.runner.AndroidJUnit4; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.GregorianCalendar; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import io.fabianterhorst.iron.testdata.Person; import io.fabianterhorst.iron.testdata.PersonArg; import static android.support.test.InstrumentationRegistry.getTargetContext; import static io.fabianterhorst.iron.testdata.TestDataGenerator.genPerson; import static io.fabianterhorst.iron.testdata.TestDataGenerator.genPersonList; import static io.fabianterhorst.iron.testdata.TestDataGenerator.genPersonMap; import static org.assertj.core.api.Assertions.assertThat;
List list = Collections.singletonList("item"); assertThat(testReadWrite(list)).isEqualTo(list.getClass()); } @Test public void testPutSingletonSet() { Set set = Collections.singleton("item"); assertThat(testReadWrite(set)).isEqualTo(set.getClass()); } @Test public void testPutSingletonMap() { Map map = Collections.singletonMap("key", "value"); assertThat(testReadWrite(map)).isEqualTo(map.getClass()); } @Test public void testPutGeorgianCalendar() { GregorianCalendar calendar = new GregorianCalendar(); assertThat(testReadWrite(calendar)).isEqualTo(calendar.getClass()); } @Test public void testPutSynchronizedList() { List list = Collections.synchronizedList(new ArrayList<>()); assertThat(testReadWrite(list)).isEqualTo(list.getClass()); } @Test public void testReadWriteClassWithoutNoArgConstructor() {
// Path: iron/src/androidTest/java/io/fabianterhorst/iron/testdata/Person.java // public class Person { // private String mName; // private int mAge; // private List<String> mPhoneNumbers; // private String[] mBikes; // // public String getName() { // return mName; // } // // public void setName(String name) { // mName = name; // } // // public int getAge() { // return mAge; // } // // public void setAge(int age) { // mAge = age; // } // // public List<String> getPhoneNumbers() { // return mPhoneNumbers; // } // // public void setPhoneNumbers(List<String> phoneNumbers) { // mPhoneNumbers = phoneNumbers; // } // // public String[] getBikes() { // return mBikes; // } // // public void setBikes(String[] bikes) { // mBikes = bikes; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || Person.class != o.getClass()) return false; // Person person = (Person) o; // return mAge == person.mAge && Arrays.equals(mBikes, person.mBikes) && (mName != null ? mName.equals(person.mName) : person.mName == null && (mPhoneNumbers != null ? mPhoneNumbers.equals(person.mPhoneNumbers) : person.mPhoneNumbers == null)); // } // // @Override // public int hashCode() { // int result = mName != null ? mName.hashCode() : 0; // result = 31 * result + mAge; // result = 31 * result + (mPhoneNumbers != null ? mPhoneNumbers.hashCode() : 0); // result = 31 * result + (mBikes != null ? Arrays.hashCode(mBikes) : 0); // return result; // } // } // // Path: iron/src/androidTest/java/io/fabianterhorst/iron/testdata/PersonArg.java // public class PersonArg extends Person { // public PersonArg(String name) { // super(); // setName("changed" + name); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || PersonArg.class != o.getClass()) return false; // // PersonArg person = (PersonArg) o; // // if (getAge() != person.getAge()) return false; // if (!Arrays.equals(getBikes(), person.getBikes())) return false; // if (getName() != null ? !getName().equals(person.getName()) : person.getName() != null) // return false; // //noinspection RedundantIfStatement // if (getPhoneNumbers() != null // ? !getPhoneNumbers().equals(person.getPhoneNumbers()) // : person.getPhoneNumbers() != null) // return false; // // return true; // } // // @Override // public int hashCode() { // return super.hashCode(); // } // } // // Path: iron/src/androidTest/java/io/fabianterhorst/iron/testdata/TestDataGenerator.java // @NonNull // public static <T extends Person> T genPerson(T p, int i) { // p.setAge(i); // p.setBikes(new String[2]); // p.getBikes()[0] = "Kellys gen#" + i; // p.getBikes()[1] = "Trek gen#" + i; // p.setPhoneNumbers(new ArrayList<String>()); // p.getPhoneNumbers().add("0-KEEP-CALM" + i); // p.getPhoneNumbers().add("0-USE-IRON" + i); // return p; // } // // Path: iron/src/androidTest/java/io/fabianterhorst/iron/testdata/TestDataGenerator.java // public static List<Person> genPersonList(int size) { // List<Person> list = new ArrayList<>(); // for (int i = 0; i < size; i++) { // Person p = genPerson(new Person(), i); // list.add(p); // } // return list; // } // // Path: iron/src/androidTest/java/io/fabianterhorst/iron/testdata/TestDataGenerator.java // public static Map<Integer, Person> genPersonMap(int size) { // HashMap<Integer, Person> map = new HashMap<>(); // int i = 0; // for (Person person : genPersonList(size)) { // map.put(i++, person); // } // return map; // } // Path: iron/src/androidTest/java/io/fabianterhorst/iron/DataTest.java import android.support.test.runner.AndroidJUnit4; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.GregorianCalendar; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import io.fabianterhorst.iron.testdata.Person; import io.fabianterhorst.iron.testdata.PersonArg; import static android.support.test.InstrumentationRegistry.getTargetContext; import static io.fabianterhorst.iron.testdata.TestDataGenerator.genPerson; import static io.fabianterhorst.iron.testdata.TestDataGenerator.genPersonList; import static io.fabianterhorst.iron.testdata.TestDataGenerator.genPersonMap; import static org.assertj.core.api.Assertions.assertThat; List list = Collections.singletonList("item"); assertThat(testReadWrite(list)).isEqualTo(list.getClass()); } @Test public void testPutSingletonSet() { Set set = Collections.singleton("item"); assertThat(testReadWrite(set)).isEqualTo(set.getClass()); } @Test public void testPutSingletonMap() { Map map = Collections.singletonMap("key", "value"); assertThat(testReadWrite(map)).isEqualTo(map.getClass()); } @Test public void testPutGeorgianCalendar() { GregorianCalendar calendar = new GregorianCalendar(); assertThat(testReadWrite(calendar)).isEqualTo(calendar.getClass()); } @Test public void testPutSynchronizedList() { List list = Collections.synchronizedList(new ArrayList<>()); assertThat(testReadWrite(list)).isEqualTo(list.getClass()); } @Test public void testReadWriteClassWithoutNoArgConstructor() {
PersonArg constructor = new PersonArg("name");
FabianTerhorst/Iron
iron/src/androidTest/java/io/fabianterhorst/iron/IronTest.java
// Path: iron/src/androidTest/java/io/fabianterhorst/iron/testdata/TestDataGenerator.java // public class TestDataGenerator { // public static List<Person> genPersonList(int size) { // List<Person> list = new ArrayList<>(); // for (int i = 0; i < size; i++) { // Person p = genPerson(new Person(), i); // list.add(p); // } // return list; // } // // public static List<PersonArg> genPersonArgList(int size) { // List<PersonArg> list = new ArrayList<>(); // for (int i = 0; i < size; i++) { // PersonArg p = genPerson(new PersonArg("name"), i); // list.add(p); // } // return list; // } // // @NonNull // public static <T extends Person> T genPerson(T p, int i) { // p.setAge(i); // p.setBikes(new String[2]); // p.getBikes()[0] = "Kellys gen#" + i; // p.getBikes()[1] = "Trek gen#" + i; // p.setPhoneNumbers(new ArrayList<String>()); // p.getPhoneNumbers().add("0-KEEP-CALM" + i); // p.getPhoneNumbers().add("0-USE-IRON" + i); // return p; // } // // public static Map<Integer, Person> genPersonMap(int size) { // HashMap<Integer, Person> map = new HashMap<>(); // int i = 0; // for (Person person : genPersonList(size)) { // map.put(i++, person); // } // return map; // } // }
import android.support.test.runner.AndroidJUnit4; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.List; import io.fabianterhorst.iron.testdata.TestDataGenerator; import static android.support.test.InstrumentationRegistry.getTargetContext; import static junit.framework.TestCase.assertTrue; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertFalse;
package io.fabianterhorst.iron; @RunWith(AndroidJUnit4.class) public class IronTest { @Before public void setUp() throws Exception { Iron.init(getTargetContext()); Iron.chest().destroy(); } @Test public void testExist() throws Exception { assertFalse(Iron.chest().exist("persons"));
// Path: iron/src/androidTest/java/io/fabianterhorst/iron/testdata/TestDataGenerator.java // public class TestDataGenerator { // public static List<Person> genPersonList(int size) { // List<Person> list = new ArrayList<>(); // for (int i = 0; i < size; i++) { // Person p = genPerson(new Person(), i); // list.add(p); // } // return list; // } // // public static List<PersonArg> genPersonArgList(int size) { // List<PersonArg> list = new ArrayList<>(); // for (int i = 0; i < size; i++) { // PersonArg p = genPerson(new PersonArg("name"), i); // list.add(p); // } // return list; // } // // @NonNull // public static <T extends Person> T genPerson(T p, int i) { // p.setAge(i); // p.setBikes(new String[2]); // p.getBikes()[0] = "Kellys gen#" + i; // p.getBikes()[1] = "Trek gen#" + i; // p.setPhoneNumbers(new ArrayList<String>()); // p.getPhoneNumbers().add("0-KEEP-CALM" + i); // p.getPhoneNumbers().add("0-USE-IRON" + i); // return p; // } // // public static Map<Integer, Person> genPersonMap(int size) { // HashMap<Integer, Person> map = new HashMap<>(); // int i = 0; // for (Person person : genPersonList(size)) { // map.put(i++, person); // } // return map; // } // } // Path: iron/src/androidTest/java/io/fabianterhorst/iron/IronTest.java import android.support.test.runner.AndroidJUnit4; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.List; import io.fabianterhorst.iron.testdata.TestDataGenerator; import static android.support.test.InstrumentationRegistry.getTargetContext; import static junit.framework.TestCase.assertTrue; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertFalse; package io.fabianterhorst.iron; @RunWith(AndroidJUnit4.class) public class IronTest { @Before public void setUp() throws Exception { Iron.init(getTargetContext()); Iron.chest().destroy(); } @Test public void testExist() throws Exception { assertFalse(Iron.chest().exist("persons"));
Iron.chest().write("persons", TestDataGenerator.genPersonList(10));
FabianTerhorst/Iron
iron-encryption/src/main/java/io/fabianterhorst/iron/encryption/AesCbcWithIntegrity.java
// Path: iron/src/main/java/io/fabianterhorst/iron/IronException.java // public class IronException extends RuntimeException { // public IronException(String detailMessage) { // super(detailMessage); // } // // public IronException(Throwable throwable) { // super(throwable); // } // // public IronException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // }
import android.os.Build; import android.os.Process; import android.util.Base64; import android.util.Log; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.security.GeneralSecurityException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.Provider; import java.security.SecureRandom; import java.security.SecureRandomSpi; import java.security.Security; import java.security.spec.KeySpec; import java.util.Arrays; import java.util.concurrent.atomic.AtomicBoolean; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.Mac; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.PBEKeySpec; import io.fabianterhorst.iron.IronException;
} /** * Gets the hardware serial number of this device. * * @return serial number or {@code null} if not available. */ private static String getDeviceSerialNumber() { // We're using the Reflection API because Build.SERIAL is only // available since API Level 9 (Gingerbread, Android 2.3). try { return (String) Build.class.getField("SERIAL").get(null); } catch (Exception ignored) { return null; } } private static byte[] getBuildFingerprintAndDeviceSerial() { StringBuilder result = new StringBuilder(); String fingerprint = Build.FINGERPRINT; if (fingerprint != null) { result.append(fingerprint); } String serial = getDeviceSerialNumber(); if (serial != null) { result.append(serial); } try { return result.toString().getBytes("UTF-8"); } catch (UnsupportedEncodingException e) {
// Path: iron/src/main/java/io/fabianterhorst/iron/IronException.java // public class IronException extends RuntimeException { // public IronException(String detailMessage) { // super(detailMessage); // } // // public IronException(Throwable throwable) { // super(throwable); // } // // public IronException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // } // Path: iron-encryption/src/main/java/io/fabianterhorst/iron/encryption/AesCbcWithIntegrity.java import android.os.Build; import android.os.Process; import android.util.Base64; import android.util.Log; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.security.GeneralSecurityException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.Provider; import java.security.SecureRandom; import java.security.SecureRandomSpi; import java.security.Security; import java.security.spec.KeySpec; import java.util.Arrays; import java.util.concurrent.atomic.AtomicBoolean; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.Mac; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.PBEKeySpec; import io.fabianterhorst.iron.IronException; } /** * Gets the hardware serial number of this device. * * @return serial number or {@code null} if not available. */ private static String getDeviceSerialNumber() { // We're using the Reflection API because Build.SERIAL is only // available since API Level 9 (Gingerbread, Android 2.3). try { return (String) Build.class.getField("SERIAL").get(null); } catch (Exception ignored) { return null; } } private static byte[] getBuildFingerprintAndDeviceSerial() { StringBuilder result = new StringBuilder(); String fingerprint = Build.FINGERPRINT; if (fingerprint != null) { result.append(fingerprint); } String serial = getDeviceSerialNumber(); if (serial != null) { result.append(serial); } try { return result.toString().getBytes("UTF-8"); } catch (UnsupportedEncodingException e) {
throw new IronException("UTF-8 encoding not supported");
LGoodDatePicker/LGoodDatePicker
Project/src/main/java/com/github/lgooddatepicker/zinternaltools/DateVetoPolicyMinimumMaximumDate.java
// Path: Project/src/main/java/com/github/lgooddatepicker/optionalusertools/DateInterval.java // public class DateInterval { // // /** firstDate, This is the first date in the interval. */ // public LocalDate firstDate = null; // // /** lastDate, This is the last date in the interval. */ // public LocalDate lastDate = null; // // /** // * Constructor (Empty), This will create an empty DateInterval instance. An empty date interval // * has both dates set to null. // */ // public DateInterval() {} // // /** Constructor (Normal), This will create a date interval using the supplied dates. */ // public DateInterval(LocalDate intervalStart, LocalDate intervalEnd) { // this.firstDate = intervalStart; // this.lastDate = intervalEnd; // } // // /** isEmpty, This will return true if both dates are null. Otherwise, this returns false. */ // public boolean isEmpty() { // return ((firstDate == null) && (lastDate == null)); // } // } // // Path: Project/src/main/java/com/github/lgooddatepicker/optionalusertools/DateVetoPolicy.java // public interface DateVetoPolicy { // // /** // * isDateAllowed, Implement this function to indicate which dates are allowed, and which ones are // * vetoed. Vetoed dates can not be selected with the keyboard or mouse. Return true to indicate // * that a date is allowed, or return false to indicate that a date is vetoed. // * // * <p>To disallow empty dates, set "DatePickerSettings.allowEmptyDates" to false. // * // * <p>The value of null will never be passed to this function, under any case. // */ // public boolean isDateAllowed(LocalDate date); // }
import com.github.lgooddatepicker.optionalusertools.DateInterval; import com.github.lgooddatepicker.optionalusertools.DateVetoPolicy; import java.time.LocalDate;
/* * The MIT License * * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.lgooddatepicker.zinternaltools; /** * DateVetoPolicyMinimumMaximumDate, This class implements a veto policy that can set a minimum and * a maximum value for the dates allowed in a DatePicker or a CalendarPanel. * * <p>Pass in the first and the last allowed date to the constructor. If one of the values is null, * then there will be no limiting date on the associated side of the date range. Only one of the two * limiting dates can be null. If both dates are supplied, then the lastAllowedDate must be greater * than or equal to the firstAllowedDate. */ public class DateVetoPolicyMinimumMaximumDate implements DateVetoPolicy { /** * firstAllowedDate, This is the first date that will be allowed. If this is null, then there will * be no lower bound on the date. Only one of the two limiting dates can be null. */ private LocalDate firstAllowedDate = null; /** * lastAllowedDate, This is the last date that will be allowed. If this is null, then there will * be no upper bound on the date. Only one of the two limiting dates can be null. */ private LocalDate lastAllowedDate = null; /** * Constructor. Pass in the first and the last allowed date. If one of the values is null, then * there will be no limiting date on the associated side of the date range. Only one of the two * limiting dates can be null. If both dates are supplied, then the lastAllowedDate must be * greater than or equal to the firstAllowedDate. */ public DateVetoPolicyMinimumMaximumDate(LocalDate firstAllowedDate, LocalDate lastAllowedDate) { setDateRangeLimits(firstAllowedDate, lastAllowedDate); } /** getDateRangeLimits, This returns the currently used date limits, as a DateInterval object. */
// Path: Project/src/main/java/com/github/lgooddatepicker/optionalusertools/DateInterval.java // public class DateInterval { // // /** firstDate, This is the first date in the interval. */ // public LocalDate firstDate = null; // // /** lastDate, This is the last date in the interval. */ // public LocalDate lastDate = null; // // /** // * Constructor (Empty), This will create an empty DateInterval instance. An empty date interval // * has both dates set to null. // */ // public DateInterval() {} // // /** Constructor (Normal), This will create a date interval using the supplied dates. */ // public DateInterval(LocalDate intervalStart, LocalDate intervalEnd) { // this.firstDate = intervalStart; // this.lastDate = intervalEnd; // } // // /** isEmpty, This will return true if both dates are null. Otherwise, this returns false. */ // public boolean isEmpty() { // return ((firstDate == null) && (lastDate == null)); // } // } // // Path: Project/src/main/java/com/github/lgooddatepicker/optionalusertools/DateVetoPolicy.java // public interface DateVetoPolicy { // // /** // * isDateAllowed, Implement this function to indicate which dates are allowed, and which ones are // * vetoed. Vetoed dates can not be selected with the keyboard or mouse. Return true to indicate // * that a date is allowed, or return false to indicate that a date is vetoed. // * // * <p>To disallow empty dates, set "DatePickerSettings.allowEmptyDates" to false. // * // * <p>The value of null will never be passed to this function, under any case. // */ // public boolean isDateAllowed(LocalDate date); // } // Path: Project/src/main/java/com/github/lgooddatepicker/zinternaltools/DateVetoPolicyMinimumMaximumDate.java import com.github.lgooddatepicker.optionalusertools.DateInterval; import com.github.lgooddatepicker.optionalusertools.DateVetoPolicy; import java.time.LocalDate; /* * The MIT License * * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.lgooddatepicker.zinternaltools; /** * DateVetoPolicyMinimumMaximumDate, This class implements a veto policy that can set a minimum and * a maximum value for the dates allowed in a DatePicker or a CalendarPanel. * * <p>Pass in the first and the last allowed date to the constructor. If one of the values is null, * then there will be no limiting date on the associated side of the date range. Only one of the two * limiting dates can be null. If both dates are supplied, then the lastAllowedDate must be greater * than or equal to the firstAllowedDate. */ public class DateVetoPolicyMinimumMaximumDate implements DateVetoPolicy { /** * firstAllowedDate, This is the first date that will be allowed. If this is null, then there will * be no lower bound on the date. Only one of the two limiting dates can be null. */ private LocalDate firstAllowedDate = null; /** * lastAllowedDate, This is the last date that will be allowed. If this is null, then there will * be no upper bound on the date. Only one of the two limiting dates can be null. */ private LocalDate lastAllowedDate = null; /** * Constructor. Pass in the first and the last allowed date. If one of the values is null, then * there will be no limiting date on the associated side of the date range. Only one of the two * limiting dates can be null. If both dates are supplied, then the lastAllowedDate must be * greater than or equal to the firstAllowedDate. */ public DateVetoPolicyMinimumMaximumDate(LocalDate firstAllowedDate, LocalDate lastAllowedDate) { setDateRangeLimits(firstAllowedDate, lastAllowedDate); } /** getDateRangeLimits, This returns the currently used date limits, as a DateInterval object. */
public DateInterval getDateRangeLimits() {
LGoodDatePicker/LGoodDatePicker
Project/src/test/java/com/github/lgooddatepicker/TestHelpers.java
// Path: Project/src/main/java/com/github/lgooddatepicker/zinternaltools/Pair.java // public class Pair<A, B> { // // public A first; // public B second; // // public Pair(A first, B second) { // this.first = first; // this.second = second; // } // }
import java.time.ZoneOffset; import com.github.lgooddatepicker.zinternaltools.Pair; import java.lang.reflect.InvocationTargetException; import java.time.Clock; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.Month; import java.time.ZoneId;
int year, Month month, int day, int hours, int minutes) { LocalDateTime fixedInstant = LocalDateTime.of(LocalDate.of(year, month, day), LocalTime.of(hours, minutes)); return Clock.fixed(fixedInstant.toInstant(ZoneOffset.UTC), ZoneId.of("Z")); } // detect funcionality of UI, which is not available on most CI systems public static boolean isUiAvailable() { return !java.awt.GraphicsEnvironment.isHeadless(); } public static void registerUncaughtExceptionHandlerToAllThreads( Thread.UncaughtExceptionHandler handler) { Thread.setDefaultUncaughtExceptionHandler(handler); // activeCount is only an estimation int activeCountOversize = 1; Thread[] threads; do { threads = new Thread[Thread.activeCount() + activeCountOversize]; Thread.enumerate(threads); activeCountOversize++; } while (threads[threads.length - 1] != null); for (Thread thread : threads) { if (thread != null) { thread.setUncaughtExceptionHandler(handler); } } } public static class ExceptionInfo {
// Path: Project/src/main/java/com/github/lgooddatepicker/zinternaltools/Pair.java // public class Pair<A, B> { // // public A first; // public B second; // // public Pair(A first, B second) { // this.first = first; // this.second = second; // } // } // Path: Project/src/test/java/com/github/lgooddatepicker/TestHelpers.java import java.time.ZoneOffset; import com.github.lgooddatepicker.zinternaltools.Pair; import java.lang.reflect.InvocationTargetException; import java.time.Clock; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.Month; import java.time.ZoneId; int year, Month month, int day, int hours, int minutes) { LocalDateTime fixedInstant = LocalDateTime.of(LocalDate.of(year, month, day), LocalTime.of(hours, minutes)); return Clock.fixed(fixedInstant.toInstant(ZoneOffset.UTC), ZoneId.of("Z")); } // detect funcionality of UI, which is not available on most CI systems public static boolean isUiAvailable() { return !java.awt.GraphicsEnvironment.isHeadless(); } public static void registerUncaughtExceptionHandlerToAllThreads( Thread.UncaughtExceptionHandler handler) { Thread.setDefaultUncaughtExceptionHandler(handler); // activeCount is only an estimation int activeCountOversize = 1; Thread[] threads; do { threads = new Thread[Thread.activeCount() + activeCountOversize]; Thread.enumerate(threads); activeCountOversize++; } while (threads[threads.length - 1] != null); for (Thread thread : threads) { if (thread != null) { thread.setUncaughtExceptionHandler(handler); } } } public static class ExceptionInfo {
Pair<String, Throwable> info = new Pair<>("", null);
LGoodDatePicker/LGoodDatePicker
Project/src/main/java/com/privatejgoodies/common/internal/ResourceBundleLocalizer.java
// Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static <T> T checkNotNull(T reference, String message) { // if (reference == null) { // throw new NullPointerException(message); // } // return reference; // } // // Path: Project/src/main/java/com/privatejgoodies/common/internal/Messages.java // public static final String MUST_NOT_BE_NULL = "The %1$s must not be null.";
import static com.privatejgoodies.common.internal.Messages.MUST_NOT_BE_NULL; import java.util.MissingResourceException; import java.util.ResourceBundle; import static com.privatejgoodies.common.base.Preconditions.checkNotNull;
/* * Copyright (c) 2009-2013 JGoodies Software GmbH. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * o Neither the name of JGoodies Software GmbH nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.privatejgoodies.common.internal; /** * Turns a ResourceBundle into a {@link StringLocalizer}. * * <p><strong>Note:</strong> This class is not part of the public JGoodies Common API. It's intended * for implementation purposes only. The class's API may change at any time. * * @author Karsten Lentzsch * @since 1.5.1 */ public final class ResourceBundleLocalizer implements StringLocalizer { private final ResourceBundle bundle; // Instance Creation ****************************************************** public ResourceBundleLocalizer(ResourceBundle bundle) {
// Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static <T> T checkNotNull(T reference, String message) { // if (reference == null) { // throw new NullPointerException(message); // } // return reference; // } // // Path: Project/src/main/java/com/privatejgoodies/common/internal/Messages.java // public static final String MUST_NOT_BE_NULL = "The %1$s must not be null."; // Path: Project/src/main/java/com/privatejgoodies/common/internal/ResourceBundleLocalizer.java import static com.privatejgoodies.common.internal.Messages.MUST_NOT_BE_NULL; import java.util.MissingResourceException; import java.util.ResourceBundle; import static com.privatejgoodies.common.base.Preconditions.checkNotNull; /* * Copyright (c) 2009-2013 JGoodies Software GmbH. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * o Neither the name of JGoodies Software GmbH nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.privatejgoodies.common.internal; /** * Turns a ResourceBundle into a {@link StringLocalizer}. * * <p><strong>Note:</strong> This class is not part of the public JGoodies Common API. It's intended * for implementation purposes only. The class's API may change at any time. * * @author Karsten Lentzsch * @since 1.5.1 */ public final class ResourceBundleLocalizer implements StringLocalizer { private final ResourceBundle bundle; // Instance Creation ****************************************************** public ResourceBundleLocalizer(ResourceBundle bundle) {
this.bundle = checkNotNull(bundle, MUST_NOT_BE_NULL, "resource bundle");
LGoodDatePicker/LGoodDatePicker
Project/src/main/java/com/privatejgoodies/common/internal/ResourceBundleLocalizer.java
// Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static <T> T checkNotNull(T reference, String message) { // if (reference == null) { // throw new NullPointerException(message); // } // return reference; // } // // Path: Project/src/main/java/com/privatejgoodies/common/internal/Messages.java // public static final String MUST_NOT_BE_NULL = "The %1$s must not be null.";
import static com.privatejgoodies.common.internal.Messages.MUST_NOT_BE_NULL; import java.util.MissingResourceException; import java.util.ResourceBundle; import static com.privatejgoodies.common.base.Preconditions.checkNotNull;
/* * Copyright (c) 2009-2013 JGoodies Software GmbH. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * o Neither the name of JGoodies Software GmbH nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.privatejgoodies.common.internal; /** * Turns a ResourceBundle into a {@link StringLocalizer}. * * <p><strong>Note:</strong> This class is not part of the public JGoodies Common API. It's intended * for implementation purposes only. The class's API may change at any time. * * @author Karsten Lentzsch * @since 1.5.1 */ public final class ResourceBundleLocalizer implements StringLocalizer { private final ResourceBundle bundle; // Instance Creation ****************************************************** public ResourceBundleLocalizer(ResourceBundle bundle) {
// Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static <T> T checkNotNull(T reference, String message) { // if (reference == null) { // throw new NullPointerException(message); // } // return reference; // } // // Path: Project/src/main/java/com/privatejgoodies/common/internal/Messages.java // public static final String MUST_NOT_BE_NULL = "The %1$s must not be null."; // Path: Project/src/main/java/com/privatejgoodies/common/internal/ResourceBundleLocalizer.java import static com.privatejgoodies.common.internal.Messages.MUST_NOT_BE_NULL; import java.util.MissingResourceException; import java.util.ResourceBundle; import static com.privatejgoodies.common.base.Preconditions.checkNotNull; /* * Copyright (c) 2009-2013 JGoodies Software GmbH. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * o Neither the name of JGoodies Software GmbH nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.privatejgoodies.common.internal; /** * Turns a ResourceBundle into a {@link StringLocalizer}. * * <p><strong>Note:</strong> This class is not part of the public JGoodies Common API. It's intended * for implementation purposes only. The class's API may change at any time. * * @author Karsten Lentzsch * @since 1.5.1 */ public final class ResourceBundleLocalizer implements StringLocalizer { private final ResourceBundle bundle; // Instance Creation ****************************************************** public ResourceBundleLocalizer(ResourceBundle bundle) {
this.bundle = checkNotNull(bundle, MUST_NOT_BE_NULL, "resource bundle");
LGoodDatePicker/LGoodDatePicker
Project/src/main/java/com/privatejgoodies/forms/layout/FormLayout.java
// Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static <T> T checkNotNull(T reference, String message) { // if (reference == null) { // throw new NullPointerException(message); // } // return reference; // } // // Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static void checkState(boolean expression, String message) { // if (!expression) { // throw new IllegalStateException(message); // } // } // // Path: Project/src/main/java/com/privatejgoodies/common/base/Objects.java // public final class Objects { // // private Objects() { // // Override default constructor; prevents instantiation. // } // // // API ******************************************************************** // /** // * Provides a means to copy objects that do not implement Cloneable. Performs a deep copy where // * the copied object has no references to the original object for any object that implements // * Serializable. If the original is {@code null}, this method just returns {@code null}. // * // * @param <T> the type of the object to be cloned // * @param original the object to copied, may be {@code null} // * @return the copied object // * @since 1.1.1 // */ // public static <T extends Serializable> T deepCopy(T original) { // if (original == null) { // return null; // } // try { // final ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); // final ObjectOutputStream oas = new ObjectOutputStream(baos); // oas.writeObject(original); // oas.flush(); // // close is unnecessary // final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); // final ObjectInputStream ois = new ObjectInputStream(bais); // @SuppressWarnings("unchecked") // T readObject = (T) ois.readObject(); // return readObject; // } catch (Throwable e) { // throw new RuntimeException("Deep copy failed", e); // } // } // // /** // * Checks and answers if the two objects are both {@code null} or equal. // * // * <pre> // * Objects.equals(null, null) == true // * Objects.equals("Hi", "Hi") == true // * Objects.equals("Hi", null) == false // * Objects.equals(null, "Hi") == false // * Objects.equals("Hi", "Ho") == false // * </pre> // * // * @param o1 the first object to compare // * @param o2 the second object to compare // * @return boolean {@code true} if and only if both objects are {@code null} or equal according to // * {@link Object#equals(Object) equals} invoked on the first object // */ // public static boolean equals(Object o1, Object o2) { // return o1 == o2 || o1 != null && o1.equals(o2); // } // }
import static com.privatejgoodies.common.base.Preconditions.checkNotNull; import static com.privatejgoodies.common.base.Preconditions.checkState; import com.privatejgoodies.common.base.Objects; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Insets; import java.awt.LayoutManager2; import java.awt.Rectangle; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.swing.JComponent;
* @throws NullPointerException if {@code encodedColumnSpecs}, {@code encodedRowSpecs}, or {@code * layoutMap} is {@code null} * @since 1.2 */ public FormLayout(String encodedColumnSpecs, String encodedRowSpecs, LayoutMap layoutMap) { this( ColumnSpec.decodeSpecs(encodedColumnSpecs, layoutMap), RowSpec.decodeSpecs(encodedRowSpecs, layoutMap)); } /** * Constructs a FormLayout using the given column specifications. The constructed layout has no * rows; these must be added before components can be added to the layout container. * * @param colSpecs an array of column specifications. * @throws NullPointerException if {@code colSpecs} is {@code null} * @since 1.1 */ public FormLayout(ColumnSpec[] colSpecs) { this(colSpecs, new RowSpec[] {}); } /** * Constructs a FormLayout using the given column and row specifications. * * @param colSpecs an array of column specifications. * @param rowSpecs an array of row specifications. * @throws NullPointerException if {@code colSpecs} or {@code rowSpecs} is {@code null} */ public FormLayout(ColumnSpec[] colSpecs, RowSpec[] rowSpecs) {
// Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static <T> T checkNotNull(T reference, String message) { // if (reference == null) { // throw new NullPointerException(message); // } // return reference; // } // // Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static void checkState(boolean expression, String message) { // if (!expression) { // throw new IllegalStateException(message); // } // } // // Path: Project/src/main/java/com/privatejgoodies/common/base/Objects.java // public final class Objects { // // private Objects() { // // Override default constructor; prevents instantiation. // } // // // API ******************************************************************** // /** // * Provides a means to copy objects that do not implement Cloneable. Performs a deep copy where // * the copied object has no references to the original object for any object that implements // * Serializable. If the original is {@code null}, this method just returns {@code null}. // * // * @param <T> the type of the object to be cloned // * @param original the object to copied, may be {@code null} // * @return the copied object // * @since 1.1.1 // */ // public static <T extends Serializable> T deepCopy(T original) { // if (original == null) { // return null; // } // try { // final ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); // final ObjectOutputStream oas = new ObjectOutputStream(baos); // oas.writeObject(original); // oas.flush(); // // close is unnecessary // final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); // final ObjectInputStream ois = new ObjectInputStream(bais); // @SuppressWarnings("unchecked") // T readObject = (T) ois.readObject(); // return readObject; // } catch (Throwable e) { // throw new RuntimeException("Deep copy failed", e); // } // } // // /** // * Checks and answers if the two objects are both {@code null} or equal. // * // * <pre> // * Objects.equals(null, null) == true // * Objects.equals("Hi", "Hi") == true // * Objects.equals("Hi", null) == false // * Objects.equals(null, "Hi") == false // * Objects.equals("Hi", "Ho") == false // * </pre> // * // * @param o1 the first object to compare // * @param o2 the second object to compare // * @return boolean {@code true} if and only if both objects are {@code null} or equal according to // * {@link Object#equals(Object) equals} invoked on the first object // */ // public static boolean equals(Object o1, Object o2) { // return o1 == o2 || o1 != null && o1.equals(o2); // } // } // Path: Project/src/main/java/com/privatejgoodies/forms/layout/FormLayout.java import static com.privatejgoodies.common.base.Preconditions.checkNotNull; import static com.privatejgoodies.common.base.Preconditions.checkState; import com.privatejgoodies.common.base.Objects; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Insets; import java.awt.LayoutManager2; import java.awt.Rectangle; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.swing.JComponent; * @throws NullPointerException if {@code encodedColumnSpecs}, {@code encodedRowSpecs}, or {@code * layoutMap} is {@code null} * @since 1.2 */ public FormLayout(String encodedColumnSpecs, String encodedRowSpecs, LayoutMap layoutMap) { this( ColumnSpec.decodeSpecs(encodedColumnSpecs, layoutMap), RowSpec.decodeSpecs(encodedRowSpecs, layoutMap)); } /** * Constructs a FormLayout using the given column specifications. The constructed layout has no * rows; these must be added before components can be added to the layout container. * * @param colSpecs an array of column specifications. * @throws NullPointerException if {@code colSpecs} is {@code null} * @since 1.1 */ public FormLayout(ColumnSpec[] colSpecs) { this(colSpecs, new RowSpec[] {}); } /** * Constructs a FormLayout using the given column and row specifications. * * @param colSpecs an array of column specifications. * @param rowSpecs an array of row specifications. * @throws NullPointerException if {@code colSpecs} or {@code rowSpecs} is {@code null} */ public FormLayout(ColumnSpec[] colSpecs, RowSpec[] rowSpecs) {
checkNotNull(colSpecs, "The column specifications must not be null.");
LGoodDatePicker/LGoodDatePicker
Project/src/main/java/com/privatejgoodies/forms/layout/FormLayout.java
// Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static <T> T checkNotNull(T reference, String message) { // if (reference == null) { // throw new NullPointerException(message); // } // return reference; // } // // Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static void checkState(boolean expression, String message) { // if (!expression) { // throw new IllegalStateException(message); // } // } // // Path: Project/src/main/java/com/privatejgoodies/common/base/Objects.java // public final class Objects { // // private Objects() { // // Override default constructor; prevents instantiation. // } // // // API ******************************************************************** // /** // * Provides a means to copy objects that do not implement Cloneable. Performs a deep copy where // * the copied object has no references to the original object for any object that implements // * Serializable. If the original is {@code null}, this method just returns {@code null}. // * // * @param <T> the type of the object to be cloned // * @param original the object to copied, may be {@code null} // * @return the copied object // * @since 1.1.1 // */ // public static <T extends Serializable> T deepCopy(T original) { // if (original == null) { // return null; // } // try { // final ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); // final ObjectOutputStream oas = new ObjectOutputStream(baos); // oas.writeObject(original); // oas.flush(); // // close is unnecessary // final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); // final ObjectInputStream ois = new ObjectInputStream(bais); // @SuppressWarnings("unchecked") // T readObject = (T) ois.readObject(); // return readObject; // } catch (Throwable e) { // throw new RuntimeException("Deep copy failed", e); // } // } // // /** // * Checks and answers if the two objects are both {@code null} or equal. // * // * <pre> // * Objects.equals(null, null) == true // * Objects.equals("Hi", "Hi") == true // * Objects.equals("Hi", null) == false // * Objects.equals(null, "Hi") == false // * Objects.equals("Hi", "Ho") == false // * </pre> // * // * @param o1 the first object to compare // * @param o2 the second object to compare // * @return boolean {@code true} if and only if both objects are {@code null} or equal according to // * {@link Object#equals(Object) equals} invoked on the first object // */ // public static boolean equals(Object o1, Object o2) { // return o1 == o2 || o1 != null && o1.equals(o2); // } // }
import static com.privatejgoodies.common.base.Preconditions.checkNotNull; import static com.privatejgoodies.common.base.Preconditions.checkState; import com.privatejgoodies.common.base.Objects; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Insets; import java.awt.LayoutManager2; import java.awt.Rectangle; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.swing.JComponent;
int[] groupIndices = allGroupIndice; for (int i = 0; i < groupIndices.length; i++) { int index = groupIndices[i]; if (index == modifiedIndex && remove) { throw new IllegalStateException( "The removed index " + modifiedIndex + " must not be grouped."); } else if (index >= modifiedIndex) { groupIndices[i] += offset; } } } } // Accessing Constraints ************************************************ /** * Looks up and returns the constraints for the specified component. A copy of the * actualCellConstraints object is returned. * * @param component the component to be queried * @return the CellConstraints for the specified component * @throws NullPointerException if {@code component} is {@code null} * @throws IllegalStateException if {@code component} has not been added to the container */ public CellConstraints getConstraints(Component component) { return (CellConstraints) getConstraints0(component).clone(); } private CellConstraints getConstraints0(Component component) { checkNotNull(component, "The component must not be null."); CellConstraints constraints = constraintMap.get(component);
// Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static <T> T checkNotNull(T reference, String message) { // if (reference == null) { // throw new NullPointerException(message); // } // return reference; // } // // Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static void checkState(boolean expression, String message) { // if (!expression) { // throw new IllegalStateException(message); // } // } // // Path: Project/src/main/java/com/privatejgoodies/common/base/Objects.java // public final class Objects { // // private Objects() { // // Override default constructor; prevents instantiation. // } // // // API ******************************************************************** // /** // * Provides a means to copy objects that do not implement Cloneable. Performs a deep copy where // * the copied object has no references to the original object for any object that implements // * Serializable. If the original is {@code null}, this method just returns {@code null}. // * // * @param <T> the type of the object to be cloned // * @param original the object to copied, may be {@code null} // * @return the copied object // * @since 1.1.1 // */ // public static <T extends Serializable> T deepCopy(T original) { // if (original == null) { // return null; // } // try { // final ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); // final ObjectOutputStream oas = new ObjectOutputStream(baos); // oas.writeObject(original); // oas.flush(); // // close is unnecessary // final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); // final ObjectInputStream ois = new ObjectInputStream(bais); // @SuppressWarnings("unchecked") // T readObject = (T) ois.readObject(); // return readObject; // } catch (Throwable e) { // throw new RuntimeException("Deep copy failed", e); // } // } // // /** // * Checks and answers if the two objects are both {@code null} or equal. // * // * <pre> // * Objects.equals(null, null) == true // * Objects.equals("Hi", "Hi") == true // * Objects.equals("Hi", null) == false // * Objects.equals(null, "Hi") == false // * Objects.equals("Hi", "Ho") == false // * </pre> // * // * @param o1 the first object to compare // * @param o2 the second object to compare // * @return boolean {@code true} if and only if both objects are {@code null} or equal according to // * {@link Object#equals(Object) equals} invoked on the first object // */ // public static boolean equals(Object o1, Object o2) { // return o1 == o2 || o1 != null && o1.equals(o2); // } // } // Path: Project/src/main/java/com/privatejgoodies/forms/layout/FormLayout.java import static com.privatejgoodies.common.base.Preconditions.checkNotNull; import static com.privatejgoodies.common.base.Preconditions.checkState; import com.privatejgoodies.common.base.Objects; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Insets; import java.awt.LayoutManager2; import java.awt.Rectangle; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.swing.JComponent; int[] groupIndices = allGroupIndice; for (int i = 0; i < groupIndices.length; i++) { int index = groupIndices[i]; if (index == modifiedIndex && remove) { throw new IllegalStateException( "The removed index " + modifiedIndex + " must not be grouped."); } else if (index >= modifiedIndex) { groupIndices[i] += offset; } } } } // Accessing Constraints ************************************************ /** * Looks up and returns the constraints for the specified component. A copy of the * actualCellConstraints object is returned. * * @param component the component to be queried * @return the CellConstraints for the specified component * @throws NullPointerException if {@code component} is {@code null} * @throws IllegalStateException if {@code component} has not been added to the container */ public CellConstraints getConstraints(Component component) { return (CellConstraints) getConstraints0(component).clone(); } private CellConstraints getConstraints0(Component component) { checkNotNull(component, "The component must not be null."); CellConstraints constraints = constraintMap.get(component);
checkState(constraints != null, "The component has not been added to the container.");
LGoodDatePicker/LGoodDatePicker
Project/src/main/java/com/privatejgoodies/forms/layout/FormLayout.java
// Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static <T> T checkNotNull(T reference, String message) { // if (reference == null) { // throw new NullPointerException(message); // } // return reference; // } // // Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static void checkState(boolean expression, String message) { // if (!expression) { // throw new IllegalStateException(message); // } // } // // Path: Project/src/main/java/com/privatejgoodies/common/base/Objects.java // public final class Objects { // // private Objects() { // // Override default constructor; prevents instantiation. // } // // // API ******************************************************************** // /** // * Provides a means to copy objects that do not implement Cloneable. Performs a deep copy where // * the copied object has no references to the original object for any object that implements // * Serializable. If the original is {@code null}, this method just returns {@code null}. // * // * @param <T> the type of the object to be cloned // * @param original the object to copied, may be {@code null} // * @return the copied object // * @since 1.1.1 // */ // public static <T extends Serializable> T deepCopy(T original) { // if (original == null) { // return null; // } // try { // final ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); // final ObjectOutputStream oas = new ObjectOutputStream(baos); // oas.writeObject(original); // oas.flush(); // // close is unnecessary // final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); // final ObjectInputStream ois = new ObjectInputStream(bais); // @SuppressWarnings("unchecked") // T readObject = (T) ois.readObject(); // return readObject; // } catch (Throwable e) { // throw new RuntimeException("Deep copy failed", e); // } // } // // /** // * Checks and answers if the two objects are both {@code null} or equal. // * // * <pre> // * Objects.equals(null, null) == true // * Objects.equals("Hi", "Hi") == true // * Objects.equals("Hi", null) == false // * Objects.equals(null, "Hi") == false // * Objects.equals("Hi", "Ho") == false // * </pre> // * // * @param o1 the first object to compare // * @param o2 the second object to compare // * @return boolean {@code true} if and only if both objects are {@code null} or equal according to // * {@link Object#equals(Object) equals} invoked on the first object // */ // public static boolean equals(Object o1, Object o2) { // return o1 == o2 || o1 != null && o1.equals(o2); // } // }
import static com.privatejgoodies.common.base.Preconditions.checkNotNull; import static com.privatejgoodies.common.base.Preconditions.checkState; import com.privatejgoodies.common.base.Objects; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Insets; import java.awt.LayoutManager2; import java.awt.Rectangle; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.swing.JComponent;
*/ public void setHonorsVisibility(boolean b) { boolean oldHonorsVisibility = getHonorsVisibility(); if (oldHonorsVisibility == b) { return; } honorsVisibility = b; Set componentSet = constraintMap.keySet(); if (componentSet.isEmpty()) { return; } Component firstComponent = (Component) componentSet.iterator().next(); Container container = firstComponent.getParent(); invalidateAndRepaint(container); } /** * Specifies whether the given component shall be taken into account for sizing and positioning. * This setting overrides the container-wide default. See {@link #setHonorsVisibility(boolean)} * for details. * * @param component the component that shall get an individual setting * @param b {@code Boolean.TRUE} to override the container default and honor the visibility for * the given component, {@code Boolean.FALSE} to override the container default and ignore the * visibility for the given component, {@code null} to use the container default value as * specified by {@link #getHonorsVisibility()}. * @since 1.2 */ public void setHonorsVisibility(Component component, Boolean b) { CellConstraints constraints = getConstraints0(component);
// Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static <T> T checkNotNull(T reference, String message) { // if (reference == null) { // throw new NullPointerException(message); // } // return reference; // } // // Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static void checkState(boolean expression, String message) { // if (!expression) { // throw new IllegalStateException(message); // } // } // // Path: Project/src/main/java/com/privatejgoodies/common/base/Objects.java // public final class Objects { // // private Objects() { // // Override default constructor; prevents instantiation. // } // // // API ******************************************************************** // /** // * Provides a means to copy objects that do not implement Cloneable. Performs a deep copy where // * the copied object has no references to the original object for any object that implements // * Serializable. If the original is {@code null}, this method just returns {@code null}. // * // * @param <T> the type of the object to be cloned // * @param original the object to copied, may be {@code null} // * @return the copied object // * @since 1.1.1 // */ // public static <T extends Serializable> T deepCopy(T original) { // if (original == null) { // return null; // } // try { // final ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); // final ObjectOutputStream oas = new ObjectOutputStream(baos); // oas.writeObject(original); // oas.flush(); // // close is unnecessary // final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); // final ObjectInputStream ois = new ObjectInputStream(bais); // @SuppressWarnings("unchecked") // T readObject = (T) ois.readObject(); // return readObject; // } catch (Throwable e) { // throw new RuntimeException("Deep copy failed", e); // } // } // // /** // * Checks and answers if the two objects are both {@code null} or equal. // * // * <pre> // * Objects.equals(null, null) == true // * Objects.equals("Hi", "Hi") == true // * Objects.equals("Hi", null) == false // * Objects.equals(null, "Hi") == false // * Objects.equals("Hi", "Ho") == false // * </pre> // * // * @param o1 the first object to compare // * @param o2 the second object to compare // * @return boolean {@code true} if and only if both objects are {@code null} or equal according to // * {@link Object#equals(Object) equals} invoked on the first object // */ // public static boolean equals(Object o1, Object o2) { // return o1 == o2 || o1 != null && o1.equals(o2); // } // } // Path: Project/src/main/java/com/privatejgoodies/forms/layout/FormLayout.java import static com.privatejgoodies.common.base.Preconditions.checkNotNull; import static com.privatejgoodies.common.base.Preconditions.checkState; import com.privatejgoodies.common.base.Objects; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Insets; import java.awt.LayoutManager2; import java.awt.Rectangle; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.swing.JComponent; */ public void setHonorsVisibility(boolean b) { boolean oldHonorsVisibility = getHonorsVisibility(); if (oldHonorsVisibility == b) { return; } honorsVisibility = b; Set componentSet = constraintMap.keySet(); if (componentSet.isEmpty()) { return; } Component firstComponent = (Component) componentSet.iterator().next(); Container container = firstComponent.getParent(); invalidateAndRepaint(container); } /** * Specifies whether the given component shall be taken into account for sizing and positioning. * This setting overrides the container-wide default. See {@link #setHonorsVisibility(boolean)} * for details. * * @param component the component that shall get an individual setting * @param b {@code Boolean.TRUE} to override the container default and honor the visibility for * the given component, {@code Boolean.FALSE} to override the container default and ignore the * visibility for the given component, {@code null} to use the container default value as * specified by {@link #getHonorsVisibility()}. * @since 1.2 */ public void setHonorsVisibility(Component component, Boolean b) { CellConstraints constraints = getConstraints0(component);
if (Objects.equals(b, constraints.honorsVisibility)) {
LGoodDatePicker/LGoodDatePicker
Project/src/main/java/com/privatejgoodies/forms/layout/FormSpecParser.java
// Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static <T> T checkNotNull(T reference, String message) { // if (reference == null) { // throw new NullPointerException(message); // } // return reference; // }
import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.privatejgoodies.common.base.Preconditions.checkNotNull;
/* * Copyright (c) 2002-2013 JGoodies Software GmbH. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * o Neither the name of JGoodies Software GmbH nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.privatejgoodies.forms.layout; /** * Parses encoded column and row specifications. Returns ColumnSpec or RowSpec arrays if successful, * and aims to provide useful information in case of a syntax error. * * @author Karsten Lentzsch * @version $Revision: 1.12 $ * @see ColumnSpec * @see RowSpec */ public final class FormSpecParser { // Parser Patterns ****************************************************** private static final Pattern MULTIPLIER_PREFIX_PATTERN = Pattern.compile("\\d+\\s*\\*\\s*\\("); private static final Pattern DIGIT_PATTERN = Pattern.compile("\\d+"); // Instance Fields ******************************************************** private final String source; private final LayoutMap layoutMap; // Instance Creation ****************************************************** /** * Constructs a parser for the given encoded column/row specification, the given LayoutMap, and * orientation. * * @param source the raw encoded column or row specification as provided by the user * @param description describes the source, e.g. "column specification" * @param layoutMap maps layout variable names to ColumnSpec and RowSpec objects * @param horizontal {@code true} for columns, {@code false} for rows * @throws NullPointerException if {@code source} or {@code layoutMap} is {@code null} */ private FormSpecParser( String source, String description, LayoutMap layoutMap, boolean horizontal) {
// Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static <T> T checkNotNull(T reference, String message) { // if (reference == null) { // throw new NullPointerException(message); // } // return reference; // } // Path: Project/src/main/java/com/privatejgoodies/forms/layout/FormSpecParser.java import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.privatejgoodies.common.base.Preconditions.checkNotNull; /* * Copyright (c) 2002-2013 JGoodies Software GmbH. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * o Neither the name of JGoodies Software GmbH nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.privatejgoodies.forms.layout; /** * Parses encoded column and row specifications. Returns ColumnSpec or RowSpec arrays if successful, * and aims to provide useful information in case of a syntax error. * * @author Karsten Lentzsch * @version $Revision: 1.12 $ * @see ColumnSpec * @see RowSpec */ public final class FormSpecParser { // Parser Patterns ****************************************************** private static final Pattern MULTIPLIER_PREFIX_PATTERN = Pattern.compile("\\d+\\s*\\*\\s*\\("); private static final Pattern DIGIT_PATTERN = Pattern.compile("\\d+"); // Instance Fields ******************************************************** private final String source; private final LayoutMap layoutMap; // Instance Creation ****************************************************** /** * Constructs a parser for the given encoded column/row specification, the given LayoutMap, and * orientation. * * @param source the raw encoded column or row specification as provided by the user * @param description describes the source, e.g. "column specification" * @param layoutMap maps layout variable names to ColumnSpec and RowSpec objects * @param horizontal {@code true} for columns, {@code false} for rows * @throws NullPointerException if {@code source} or {@code layoutMap} is {@code null} */ private FormSpecParser( String source, String description, LayoutMap layoutMap, boolean horizontal) {
checkNotNull(source, "The %S must not be null.", description);
LGoodDatePicker/LGoodDatePicker
Project/src/main/java/com/privatejgoodies/forms/layout/BoundedSize.java
// Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static <T> T checkNotNull(T reference, String message) { // if (reference == null) { // throw new NullPointerException(message); // } // return reference; // }
import java.awt.Container; import java.io.Serializable; import java.util.List; import static com.privatejgoodies.common.base.Preconditions.checkNotNull;
/* * Copyright (c) 2002-2013 JGoodies Software GmbH. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * o Neither the name of JGoodies Software GmbH nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.privatejgoodies.forms.layout; /** * Describes sizes that provide lower and upper bounds as used by the JGoodies FormLayout. * * @author Karsten Lentzsch * @version $Revision: 1.21 $ * @see Sizes * @see ConstantSize */ public final class BoundedSize implements Size, Serializable { /** Holds the base size. */ private final Size basis; /** Holds an optional lower bound. */ private final Size lowerBound; /** Holds an optional upper bound. */ private final Size upperBound; // Instance Creation **************************************************** /** * Constructs a BoundedSize for the given basis using the specified lower and upper bounds. * * @param basis the base size * @param lowerBound the lower bound size * @param upperBound the upper bound size * @throws NullPointerException if {@code basis}, {@code lowerBound}, or {@code upperBound} is * {@code null} * @since 1.1 */ public BoundedSize(Size basis, Size lowerBound, Size upperBound) {
// Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static <T> T checkNotNull(T reference, String message) { // if (reference == null) { // throw new NullPointerException(message); // } // return reference; // } // Path: Project/src/main/java/com/privatejgoodies/forms/layout/BoundedSize.java import java.awt.Container; import java.io.Serializable; import java.util.List; import static com.privatejgoodies.common.base.Preconditions.checkNotNull; /* * Copyright (c) 2002-2013 JGoodies Software GmbH. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * o Neither the name of JGoodies Software GmbH nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.privatejgoodies.forms.layout; /** * Describes sizes that provide lower and upper bounds as used by the JGoodies FormLayout. * * @author Karsten Lentzsch * @version $Revision: 1.21 $ * @see Sizes * @see ConstantSize */ public final class BoundedSize implements Size, Serializable { /** Holds the base size. */ private final Size basis; /** Holds an optional lower bound. */ private final Size lowerBound; /** Holds an optional upper bound. */ private final Size upperBound; // Instance Creation **************************************************** /** * Constructs a BoundedSize for the given basis using the specified lower and upper bounds. * * @param basis the base size * @param lowerBound the lower bound size * @param upperBound the upper bound size * @throws NullPointerException if {@code basis}, {@code lowerBound}, or {@code upperBound} is * {@code null} * @since 1.1 */ public BoundedSize(Size basis, Size lowerBound, Size upperBound) {
this.basis = checkNotNull(basis, "The basis must not be null.");
LGoodDatePicker/LGoodDatePicker
Project/src/test/java/com/github/lgooddatepicker/components/TestDatePicker.java
// Path: Project/src/test/java/com/github/lgooddatepicker/TestHelpers.java // public class TestHelpers { // // static boolean isClassAvailable(String className) { // try { // Class.forName(className); // } catch (ClassNotFoundException ex) { // return false; // } // return true; // } // // public static Object readPrivateField(Class<?> clazz, Object instance, String field) // throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { // java.lang.reflect.Field private_field = clazz.getDeclaredField(field); // private_field.setAccessible(true); // return private_field.get(instance); // } // // public static java.lang.reflect.Method accessPrivateMethod( // Class<?> clazz, String method, Class<?>... argclasses) // throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { // java.lang.reflect.Method private_method = clazz.getDeclaredMethod(method, argclasses); // private_method.setAccessible(true); // return private_method; // } // // public static Clock getClockFixedToInstant( // int year, Month month, int day, int hours, int minutes) { // LocalDateTime fixedInstant = // LocalDateTime.of(LocalDate.of(year, month, day), LocalTime.of(hours, minutes)); // return Clock.fixed(fixedInstant.toInstant(ZoneOffset.UTC), ZoneId.of("Z")); // } // // // detect funcionality of UI, which is not available on most CI systems // public static boolean isUiAvailable() { // return !java.awt.GraphicsEnvironment.isHeadless(); // } // // public static void registerUncaughtExceptionHandlerToAllThreads( // Thread.UncaughtExceptionHandler handler) { // Thread.setDefaultUncaughtExceptionHandler(handler); // // activeCount is only an estimation // int activeCountOversize = 1; // Thread[] threads; // do { // threads = new Thread[Thread.activeCount() + activeCountOversize]; // Thread.enumerate(threads); // activeCountOversize++; // } while (threads[threads.length - 1] != null); // for (Thread thread : threads) { // if (thread != null) { // thread.setUncaughtExceptionHandler(handler); // } // } // } // // public static class ExceptionInfo { // Pair<String, Throwable> info = new Pair<>("", null); // // synchronized boolean wasSet() { // return !info.first.isEmpty() || info.second != null; // } // // synchronized void set(String threadname, Throwable ex) { // info.first = threadname; // info.second = ex; // } // // synchronized String getThreadName() { // return info.first; // } // // synchronized String getExceptionMessage() { // return info.second != null ? info.second.getMessage() : ""; // } // // synchronized String getStackTrace() { // String result = ""; // if (info.second != null) { // for (StackTraceElement elem : info.second.getStackTrace()) { // result += elem.toString() + "\n"; // } // } // return result; // } // } // }
import java.time.Month; import java.time.YearMonth; import java.time.ZoneId; import java.util.Locale; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.github.lgooddatepicker.TestHelpers; import java.awt.Color; import java.lang.reflect.InvocationTargetException; import java.time.Clock; import java.time.LocalDate;
/* * The MIT License * * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.lgooddatepicker.components; public class TestDatePicker { @Test(expected = Test.None.class /* no exception expected */) public void TestCustomClockDateSettings() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { DatePickerSettings settings = new DatePickerSettings(); assertTrue("Default clock must be available", settings.getClock() != null); assertTrue( "Default clock must be in system default time zone", settings.getClock().getZone().equals(ZoneId.systemDefault())); settings = new DatePickerSettings(Locale.ENGLISH); assertTrue("Default clock must be available", settings.getClock() != null); assertTrue( "Default clock must be in system default time zone", settings.getClock().getZone().equals(ZoneId.systemDefault())); Clock myClock = Clock.systemUTC(); settings.setClock(myClock); assertTrue("Set clock must be returned", settings.getClock() == myClock);
// Path: Project/src/test/java/com/github/lgooddatepicker/TestHelpers.java // public class TestHelpers { // // static boolean isClassAvailable(String className) { // try { // Class.forName(className); // } catch (ClassNotFoundException ex) { // return false; // } // return true; // } // // public static Object readPrivateField(Class<?> clazz, Object instance, String field) // throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { // java.lang.reflect.Field private_field = clazz.getDeclaredField(field); // private_field.setAccessible(true); // return private_field.get(instance); // } // // public static java.lang.reflect.Method accessPrivateMethod( // Class<?> clazz, String method, Class<?>... argclasses) // throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { // java.lang.reflect.Method private_method = clazz.getDeclaredMethod(method, argclasses); // private_method.setAccessible(true); // return private_method; // } // // public static Clock getClockFixedToInstant( // int year, Month month, int day, int hours, int minutes) { // LocalDateTime fixedInstant = // LocalDateTime.of(LocalDate.of(year, month, day), LocalTime.of(hours, minutes)); // return Clock.fixed(fixedInstant.toInstant(ZoneOffset.UTC), ZoneId.of("Z")); // } // // // detect funcionality of UI, which is not available on most CI systems // public static boolean isUiAvailable() { // return !java.awt.GraphicsEnvironment.isHeadless(); // } // // public static void registerUncaughtExceptionHandlerToAllThreads( // Thread.UncaughtExceptionHandler handler) { // Thread.setDefaultUncaughtExceptionHandler(handler); // // activeCount is only an estimation // int activeCountOversize = 1; // Thread[] threads; // do { // threads = new Thread[Thread.activeCount() + activeCountOversize]; // Thread.enumerate(threads); // activeCountOversize++; // } while (threads[threads.length - 1] != null); // for (Thread thread : threads) { // if (thread != null) { // thread.setUncaughtExceptionHandler(handler); // } // } // } // // public static class ExceptionInfo { // Pair<String, Throwable> info = new Pair<>("", null); // // synchronized boolean wasSet() { // return !info.first.isEmpty() || info.second != null; // } // // synchronized void set(String threadname, Throwable ex) { // info.first = threadname; // info.second = ex; // } // // synchronized String getThreadName() { // return info.first; // } // // synchronized String getExceptionMessage() { // return info.second != null ? info.second.getMessage() : ""; // } // // synchronized String getStackTrace() { // String result = ""; // if (info.second != null) { // for (StackTraceElement elem : info.second.getStackTrace()) { // result += elem.toString() + "\n"; // } // } // return result; // } // } // } // Path: Project/src/test/java/com/github/lgooddatepicker/components/TestDatePicker.java import java.time.Month; import java.time.YearMonth; import java.time.ZoneId; import java.util.Locale; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.github.lgooddatepicker.TestHelpers; import java.awt.Color; import java.lang.reflect.InvocationTargetException; import java.time.Clock; import java.time.LocalDate; /* * The MIT License * * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.lgooddatepicker.components; public class TestDatePicker { @Test(expected = Test.None.class /* no exception expected */) public void TestCustomClockDateSettings() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { DatePickerSettings settings = new DatePickerSettings(); assertTrue("Default clock must be available", settings.getClock() != null); assertTrue( "Default clock must be in system default time zone", settings.getClock().getZone().equals(ZoneId.systemDefault())); settings = new DatePickerSettings(Locale.ENGLISH); assertTrue("Default clock must be available", settings.getClock() != null); assertTrue( "Default clock must be in system default time zone", settings.getClock().getZone().equals(ZoneId.systemDefault())); Clock myClock = Clock.systemUTC(); settings.setClock(myClock); assertTrue("Set clock must be returned", settings.getClock() == myClock);
settings.setClock(TestHelpers.getClockFixedToInstant(1993, Month.MARCH, 15, 12, 00));
LGoodDatePicker/LGoodDatePicker
Project/src/main/java/com/github/lgooddatepicker/optionalusertools/CalendarListener.java
// Path: Project/src/main/java/com/github/lgooddatepicker/zinternaltools/CalendarSelectionEvent.java // public class CalendarSelectionEvent { // // /** Constructor. */ // public CalendarSelectionEvent(CalendarPanel source, LocalDate newDate, LocalDate oldDate) { // this.source = source; // this.newDate = newDate; // this.oldDate = oldDate; // } // // /** source, This is the calendar panel that generated the event. */ // private CalendarPanel source; // // /** newDate, This holds the value of the new selected date. */ // private LocalDate newDate; // // /** oldDate, This holds the value of the old selected date. */ // private LocalDate oldDate; // // /** getSource, Returns the calendar panel that generated the event. */ // public CalendarPanel getSource() { // return source; // } // // /** getNewDate, Returns the new selected date. */ // public LocalDate getNewDate() { // return newDate; // } // // /** getOldDate, Returns the old selected date. */ // public LocalDate getOldDate() { // return oldDate; // } // // /** // * isDuplicate, Returns true if the new date is the same as the old date, or if both values are // * null. Otherwise returns false. // */ // public boolean isDuplicate() { // return (PickerUtilities.isSameLocalDate(newDate, oldDate)); // } // } // // Path: Project/src/main/java/com/github/lgooddatepicker/zinternaltools/YearMonthChangeEvent.java // public class YearMonthChangeEvent { // // /** Constructor. */ // public YearMonthChangeEvent( // CalendarPanel source, YearMonth newYearMonth, YearMonth oldYearMonth) { // this.source = source; // this.newYearMonth = newYearMonth; // this.oldYearMonth = oldYearMonth; // } // // /** source, This is the calendar panel that generated the event. */ // private CalendarPanel source; // // /** newYearMonth, This holds the value of the new YearMonth. */ // private YearMonth newYearMonth; // // /** oldYearMonth, This holds the value of the old YearMonth. */ // private YearMonth oldYearMonth; // // /** getSource, Returns the calendar panel that generated the event. */ // public CalendarPanel getSource() { // return source; // } // // /** getNewYearMonth, Returns the new YearMonth. This will never return null. */ // public YearMonth getNewYearMonth() { // return newYearMonth; // } // // /** getOldYearMonth, Returns the old YearMonth. This will never return null. */ // public YearMonth getOldYearMonth() { // return oldYearMonth; // } // // /** // * isDuplicate, Returns true if the new YearMonth is the same as the old YearMonth. Otherwise // * returns false. // */ // public boolean isDuplicate() { // return (PickerUtilities.isSameYearMonth(newYearMonth, oldYearMonth)); // } // }
import com.github.lgooddatepicker.zinternaltools.CalendarSelectionEvent; import com.github.lgooddatepicker.zinternaltools.YearMonthChangeEvent;
/* * The MIT License * * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.lgooddatepicker.optionalusertools; /** * CalendarListener, This interface can be implemented to create a calendar listener. Any calendar * listeners that are registered with a CalendarPanel will be notified each time that a calendar * date is selected, or if the YearMonth is changed. */ public interface CalendarListener { /** * selectedDateChanged, This function will be called each time that a date is selected in the * applicable CalendarPanel. The selected date is supplied in the event object. Note that the * selected date may contain null, which represents a cleared or empty date. * * <p>This function will be called each time that the user selects any date or the clear button in * the calendar, even if the same date value is selected twice in a row. All duplicate selection * events are marked as duplicates in the event object. */ public void selectedDateChanged(CalendarSelectionEvent event); /** * yearMonthChanged, This function will be called each time that the YearMonth may have changed in * the applicable CalendarPanel. The selected YearMonth is supplied in the event object. * * <p>This function will be called each time that the user makes any change that requires * redrawing the calendar, even if the same YearMonth value is displayed twice in a row. All * duplicate yearMonthChanged events are marked as duplicates in the event object. * * <p>Implementation Note: This is called each time the calendar is redrawn. */
// Path: Project/src/main/java/com/github/lgooddatepicker/zinternaltools/CalendarSelectionEvent.java // public class CalendarSelectionEvent { // // /** Constructor. */ // public CalendarSelectionEvent(CalendarPanel source, LocalDate newDate, LocalDate oldDate) { // this.source = source; // this.newDate = newDate; // this.oldDate = oldDate; // } // // /** source, This is the calendar panel that generated the event. */ // private CalendarPanel source; // // /** newDate, This holds the value of the new selected date. */ // private LocalDate newDate; // // /** oldDate, This holds the value of the old selected date. */ // private LocalDate oldDate; // // /** getSource, Returns the calendar panel that generated the event. */ // public CalendarPanel getSource() { // return source; // } // // /** getNewDate, Returns the new selected date. */ // public LocalDate getNewDate() { // return newDate; // } // // /** getOldDate, Returns the old selected date. */ // public LocalDate getOldDate() { // return oldDate; // } // // /** // * isDuplicate, Returns true if the new date is the same as the old date, or if both values are // * null. Otherwise returns false. // */ // public boolean isDuplicate() { // return (PickerUtilities.isSameLocalDate(newDate, oldDate)); // } // } // // Path: Project/src/main/java/com/github/lgooddatepicker/zinternaltools/YearMonthChangeEvent.java // public class YearMonthChangeEvent { // // /** Constructor. */ // public YearMonthChangeEvent( // CalendarPanel source, YearMonth newYearMonth, YearMonth oldYearMonth) { // this.source = source; // this.newYearMonth = newYearMonth; // this.oldYearMonth = oldYearMonth; // } // // /** source, This is the calendar panel that generated the event. */ // private CalendarPanel source; // // /** newYearMonth, This holds the value of the new YearMonth. */ // private YearMonth newYearMonth; // // /** oldYearMonth, This holds the value of the old YearMonth. */ // private YearMonth oldYearMonth; // // /** getSource, Returns the calendar panel that generated the event. */ // public CalendarPanel getSource() { // return source; // } // // /** getNewYearMonth, Returns the new YearMonth. This will never return null. */ // public YearMonth getNewYearMonth() { // return newYearMonth; // } // // /** getOldYearMonth, Returns the old YearMonth. This will never return null. */ // public YearMonth getOldYearMonth() { // return oldYearMonth; // } // // /** // * isDuplicate, Returns true if the new YearMonth is the same as the old YearMonth. Otherwise // * returns false. // */ // public boolean isDuplicate() { // return (PickerUtilities.isSameYearMonth(newYearMonth, oldYearMonth)); // } // } // Path: Project/src/main/java/com/github/lgooddatepicker/optionalusertools/CalendarListener.java import com.github.lgooddatepicker.zinternaltools.CalendarSelectionEvent; import com.github.lgooddatepicker.zinternaltools.YearMonthChangeEvent; /* * The MIT License * * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.lgooddatepicker.optionalusertools; /** * CalendarListener, This interface can be implemented to create a calendar listener. Any calendar * listeners that are registered with a CalendarPanel will be notified each time that a calendar * date is selected, or if the YearMonth is changed. */ public interface CalendarListener { /** * selectedDateChanged, This function will be called each time that a date is selected in the * applicable CalendarPanel. The selected date is supplied in the event object. Note that the * selected date may contain null, which represents a cleared or empty date. * * <p>This function will be called each time that the user selects any date or the clear button in * the calendar, even if the same date value is selected twice in a row. All duplicate selection * events are marked as duplicates in the event object. */ public void selectedDateChanged(CalendarSelectionEvent event); /** * yearMonthChanged, This function will be called each time that the YearMonth may have changed in * the applicable CalendarPanel. The selected YearMonth is supplied in the event object. * * <p>This function will be called each time that the user makes any change that requires * redrawing the calendar, even if the same YearMonth value is displayed twice in a row. All * duplicate yearMonthChanged events are marked as duplicates in the event object. * * <p>Implementation Note: This is called each time the calendar is redrawn. */
public void yearMonthChanged(YearMonthChangeEvent event);
LGoodDatePicker/LGoodDatePicker
Project/src/main/java/com/privatejgoodies/forms/layout/FormSpec.java
// Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static void checkArgument(boolean expression, String message) { // if (!expression) { // throw new IllegalArgumentException(message); // } // } // // Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static String checkNotBlank(String str, String message) { // checkNotNull(str, message); // checkArgument(Strings.isNotBlank(str), message); // return str; // } // // Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static <T> T checkNotNull(T reference, String message) { // if (reference == null) { // throw new NullPointerException(message); // } // return reference; // }
import static com.privatejgoodies.common.base.Preconditions.checkNotBlank; import static com.privatejgoodies.common.base.Preconditions.checkNotNull; import java.awt.Container; import java.io.Serializable; import java.util.List; import java.util.Locale; import java.util.regex.Pattern; import static com.privatejgoodies.common.base.Preconditions.checkArgument;
/* * Copyright (c) 2002-2013 JGoodies Software GmbH. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * o Neither the name of JGoodies Software GmbH nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.privatejgoodies.forms.layout; /** * An abstract class that specifies columns and rows in FormLayout by their default alignment, start * size and resizing behavior. API users will use the subclasses {@link ColumnSpec} and {@link * RowSpec} . * * <p>Also implements the parser for encoded column and row specifications and provides parser * convenience behavior for its subclasses ColumnSpec and RowSpec. * * <p>TODO: Consider extracting the parser role to a separate class. * * @author Karsten Lentzsch * @version $Revision: 1.25 $ * @see ColumnSpec * @see RowSpec * @see FormLayout * @see CellConstraints */ public abstract class FormSpec implements Serializable { // Horizontal and Vertical Default Alignments *************************** /** By default put components in the left. */ static final DefaultAlignment LEFT_ALIGN = new DefaultAlignment("left"); /** By default put components in the right. */ static final DefaultAlignment RIGHT_ALIGN = new DefaultAlignment("right"); /** By default put the components in the top. */ static final DefaultAlignment TOP_ALIGN = new DefaultAlignment("top"); /** By default put the components in the bottom. */ static final DefaultAlignment BOTTOM_ALIGN = new DefaultAlignment("bottom"); /** By default put the components in the center. */ static final DefaultAlignment CENTER_ALIGN = new DefaultAlignment("center"); /** By default fill the column or row. */ static final DefaultAlignment FILL_ALIGN = new DefaultAlignment("fill"); /** An array of all enumeration values used to canonicalize deserialized default alignments. */ private static final DefaultAlignment[] VALUES = { LEFT_ALIGN, RIGHT_ALIGN, TOP_ALIGN, BOTTOM_ALIGN, CENTER_ALIGN, FILL_ALIGN }; // Resizing Weights ***************************************************** /** Gives a column or row a fixed size. */ public static final double NO_GROW = 0.0d; /** The default resize weight. */ public static final double DEFAULT_GROW = 1.0d; // Parser Patterns ****************************************************** private static final Pattern TOKEN_SEPARATOR_PATTERN = Pattern.compile(":"); private static final Pattern BOUNDS_SEPARATOR_PATTERN = Pattern.compile("\\s*,\\s*"); // Fields *************************************************************** /** Holds the default alignment that will be used if a cell does not override this default. */ private DefaultAlignment defaultAlignment; /** Holds the size that describes how to size this column or row. */ private Size size; /** Holds the resize weight; is 0 if not used. */ private double resizeWeight; // Instance Creation **************************************************** /** * Constructs a {@code FormSpec} for the given default alignment, size, and resize weight. The * resize weight must be a non-negative double; you can use {@code NONE} as a convenience value * for no resize. * * @param defaultAlignment the spec's default alignment * @param size a constant, component or bounded size * @param resizeWeight the spec resize weight * @throws NullPointerException if the {@code size} is {@code null} * @throws IllegalArgumentException if the {@code resizeWeight} is negative */ protected FormSpec(DefaultAlignment defaultAlignment, Size size, double resizeWeight) {
// Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static void checkArgument(boolean expression, String message) { // if (!expression) { // throw new IllegalArgumentException(message); // } // } // // Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static String checkNotBlank(String str, String message) { // checkNotNull(str, message); // checkArgument(Strings.isNotBlank(str), message); // return str; // } // // Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static <T> T checkNotNull(T reference, String message) { // if (reference == null) { // throw new NullPointerException(message); // } // return reference; // } // Path: Project/src/main/java/com/privatejgoodies/forms/layout/FormSpec.java import static com.privatejgoodies.common.base.Preconditions.checkNotBlank; import static com.privatejgoodies.common.base.Preconditions.checkNotNull; import java.awt.Container; import java.io.Serializable; import java.util.List; import java.util.Locale; import java.util.regex.Pattern; import static com.privatejgoodies.common.base.Preconditions.checkArgument; /* * Copyright (c) 2002-2013 JGoodies Software GmbH. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * o Neither the name of JGoodies Software GmbH nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.privatejgoodies.forms.layout; /** * An abstract class that specifies columns and rows in FormLayout by their default alignment, start * size and resizing behavior. API users will use the subclasses {@link ColumnSpec} and {@link * RowSpec} . * * <p>Also implements the parser for encoded column and row specifications and provides parser * convenience behavior for its subclasses ColumnSpec and RowSpec. * * <p>TODO: Consider extracting the parser role to a separate class. * * @author Karsten Lentzsch * @version $Revision: 1.25 $ * @see ColumnSpec * @see RowSpec * @see FormLayout * @see CellConstraints */ public abstract class FormSpec implements Serializable { // Horizontal and Vertical Default Alignments *************************** /** By default put components in the left. */ static final DefaultAlignment LEFT_ALIGN = new DefaultAlignment("left"); /** By default put components in the right. */ static final DefaultAlignment RIGHT_ALIGN = new DefaultAlignment("right"); /** By default put the components in the top. */ static final DefaultAlignment TOP_ALIGN = new DefaultAlignment("top"); /** By default put the components in the bottom. */ static final DefaultAlignment BOTTOM_ALIGN = new DefaultAlignment("bottom"); /** By default put the components in the center. */ static final DefaultAlignment CENTER_ALIGN = new DefaultAlignment("center"); /** By default fill the column or row. */ static final DefaultAlignment FILL_ALIGN = new DefaultAlignment("fill"); /** An array of all enumeration values used to canonicalize deserialized default alignments. */ private static final DefaultAlignment[] VALUES = { LEFT_ALIGN, RIGHT_ALIGN, TOP_ALIGN, BOTTOM_ALIGN, CENTER_ALIGN, FILL_ALIGN }; // Resizing Weights ***************************************************** /** Gives a column or row a fixed size. */ public static final double NO_GROW = 0.0d; /** The default resize weight. */ public static final double DEFAULT_GROW = 1.0d; // Parser Patterns ****************************************************** private static final Pattern TOKEN_SEPARATOR_PATTERN = Pattern.compile(":"); private static final Pattern BOUNDS_SEPARATOR_PATTERN = Pattern.compile("\\s*,\\s*"); // Fields *************************************************************** /** Holds the default alignment that will be used if a cell does not override this default. */ private DefaultAlignment defaultAlignment; /** Holds the size that describes how to size this column or row. */ private Size size; /** Holds the resize weight; is 0 if not used. */ private double resizeWeight; // Instance Creation **************************************************** /** * Constructs a {@code FormSpec} for the given default alignment, size, and resize weight. The * resize weight must be a non-negative double; you can use {@code NONE} as a convenience value * for no resize. * * @param defaultAlignment the spec's default alignment * @param size a constant, component or bounded size * @param resizeWeight the spec resize weight * @throws NullPointerException if the {@code size} is {@code null} * @throws IllegalArgumentException if the {@code resizeWeight} is negative */ protected FormSpec(DefaultAlignment defaultAlignment, Size size, double resizeWeight) {
checkNotNull(size, "The size must not be null.");
LGoodDatePicker/LGoodDatePicker
Project/src/main/java/com/privatejgoodies/forms/layout/FormSpec.java
// Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static void checkArgument(boolean expression, String message) { // if (!expression) { // throw new IllegalArgumentException(message); // } // } // // Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static String checkNotBlank(String str, String message) { // checkNotNull(str, message); // checkArgument(Strings.isNotBlank(str), message); // return str; // } // // Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static <T> T checkNotNull(T reference, String message) { // if (reference == null) { // throw new NullPointerException(message); // } // return reference; // }
import static com.privatejgoodies.common.base.Preconditions.checkNotBlank; import static com.privatejgoodies.common.base.Preconditions.checkNotNull; import java.awt.Container; import java.io.Serializable; import java.util.List; import java.util.Locale; import java.util.regex.Pattern; import static com.privatejgoodies.common.base.Preconditions.checkArgument;
/* * Copyright (c) 2002-2013 JGoodies Software GmbH. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * o Neither the name of JGoodies Software GmbH nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.privatejgoodies.forms.layout; /** * An abstract class that specifies columns and rows in FormLayout by their default alignment, start * size and resizing behavior. API users will use the subclasses {@link ColumnSpec} and {@link * RowSpec} . * * <p>Also implements the parser for encoded column and row specifications and provides parser * convenience behavior for its subclasses ColumnSpec and RowSpec. * * <p>TODO: Consider extracting the parser role to a separate class. * * @author Karsten Lentzsch * @version $Revision: 1.25 $ * @see ColumnSpec * @see RowSpec * @see FormLayout * @see CellConstraints */ public abstract class FormSpec implements Serializable { // Horizontal and Vertical Default Alignments *************************** /** By default put components in the left. */ static final DefaultAlignment LEFT_ALIGN = new DefaultAlignment("left"); /** By default put components in the right. */ static final DefaultAlignment RIGHT_ALIGN = new DefaultAlignment("right"); /** By default put the components in the top. */ static final DefaultAlignment TOP_ALIGN = new DefaultAlignment("top"); /** By default put the components in the bottom. */ static final DefaultAlignment BOTTOM_ALIGN = new DefaultAlignment("bottom"); /** By default put the components in the center. */ static final DefaultAlignment CENTER_ALIGN = new DefaultAlignment("center"); /** By default fill the column or row. */ static final DefaultAlignment FILL_ALIGN = new DefaultAlignment("fill"); /** An array of all enumeration values used to canonicalize deserialized default alignments. */ private static final DefaultAlignment[] VALUES = { LEFT_ALIGN, RIGHT_ALIGN, TOP_ALIGN, BOTTOM_ALIGN, CENTER_ALIGN, FILL_ALIGN }; // Resizing Weights ***************************************************** /** Gives a column or row a fixed size. */ public static final double NO_GROW = 0.0d; /** The default resize weight. */ public static final double DEFAULT_GROW = 1.0d; // Parser Patterns ****************************************************** private static final Pattern TOKEN_SEPARATOR_PATTERN = Pattern.compile(":"); private static final Pattern BOUNDS_SEPARATOR_PATTERN = Pattern.compile("\\s*,\\s*"); // Fields *************************************************************** /** Holds the default alignment that will be used if a cell does not override this default. */ private DefaultAlignment defaultAlignment; /** Holds the size that describes how to size this column or row. */ private Size size; /** Holds the resize weight; is 0 if not used. */ private double resizeWeight; // Instance Creation **************************************************** /** * Constructs a {@code FormSpec} for the given default alignment, size, and resize weight. The * resize weight must be a non-negative double; you can use {@code NONE} as a convenience value * for no resize. * * @param defaultAlignment the spec's default alignment * @param size a constant, component or bounded size * @param resizeWeight the spec resize weight * @throws NullPointerException if the {@code size} is {@code null} * @throws IllegalArgumentException if the {@code resizeWeight} is negative */ protected FormSpec(DefaultAlignment defaultAlignment, Size size, double resizeWeight) { checkNotNull(size, "The size must not be null.");
// Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static void checkArgument(boolean expression, String message) { // if (!expression) { // throw new IllegalArgumentException(message); // } // } // // Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static String checkNotBlank(String str, String message) { // checkNotNull(str, message); // checkArgument(Strings.isNotBlank(str), message); // return str; // } // // Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static <T> T checkNotNull(T reference, String message) { // if (reference == null) { // throw new NullPointerException(message); // } // return reference; // } // Path: Project/src/main/java/com/privatejgoodies/forms/layout/FormSpec.java import static com.privatejgoodies.common.base.Preconditions.checkNotBlank; import static com.privatejgoodies.common.base.Preconditions.checkNotNull; import java.awt.Container; import java.io.Serializable; import java.util.List; import java.util.Locale; import java.util.regex.Pattern; import static com.privatejgoodies.common.base.Preconditions.checkArgument; /* * Copyright (c) 2002-2013 JGoodies Software GmbH. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * o Neither the name of JGoodies Software GmbH nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.privatejgoodies.forms.layout; /** * An abstract class that specifies columns and rows in FormLayout by their default alignment, start * size and resizing behavior. API users will use the subclasses {@link ColumnSpec} and {@link * RowSpec} . * * <p>Also implements the parser for encoded column and row specifications and provides parser * convenience behavior for its subclasses ColumnSpec and RowSpec. * * <p>TODO: Consider extracting the parser role to a separate class. * * @author Karsten Lentzsch * @version $Revision: 1.25 $ * @see ColumnSpec * @see RowSpec * @see FormLayout * @see CellConstraints */ public abstract class FormSpec implements Serializable { // Horizontal and Vertical Default Alignments *************************** /** By default put components in the left. */ static final DefaultAlignment LEFT_ALIGN = new DefaultAlignment("left"); /** By default put components in the right. */ static final DefaultAlignment RIGHT_ALIGN = new DefaultAlignment("right"); /** By default put the components in the top. */ static final DefaultAlignment TOP_ALIGN = new DefaultAlignment("top"); /** By default put the components in the bottom. */ static final DefaultAlignment BOTTOM_ALIGN = new DefaultAlignment("bottom"); /** By default put the components in the center. */ static final DefaultAlignment CENTER_ALIGN = new DefaultAlignment("center"); /** By default fill the column or row. */ static final DefaultAlignment FILL_ALIGN = new DefaultAlignment("fill"); /** An array of all enumeration values used to canonicalize deserialized default alignments. */ private static final DefaultAlignment[] VALUES = { LEFT_ALIGN, RIGHT_ALIGN, TOP_ALIGN, BOTTOM_ALIGN, CENTER_ALIGN, FILL_ALIGN }; // Resizing Weights ***************************************************** /** Gives a column or row a fixed size. */ public static final double NO_GROW = 0.0d; /** The default resize weight. */ public static final double DEFAULT_GROW = 1.0d; // Parser Patterns ****************************************************** private static final Pattern TOKEN_SEPARATOR_PATTERN = Pattern.compile(":"); private static final Pattern BOUNDS_SEPARATOR_PATTERN = Pattern.compile("\\s*,\\s*"); // Fields *************************************************************** /** Holds the default alignment that will be used if a cell does not override this default. */ private DefaultAlignment defaultAlignment; /** Holds the size that describes how to size this column or row. */ private Size size; /** Holds the resize weight; is 0 if not used. */ private double resizeWeight; // Instance Creation **************************************************** /** * Constructs a {@code FormSpec} for the given default alignment, size, and resize weight. The * resize weight must be a non-negative double; you can use {@code NONE} as a convenience value * for no resize. * * @param defaultAlignment the spec's default alignment * @param size a constant, component or bounded size * @param resizeWeight the spec resize weight * @throws NullPointerException if the {@code size} is {@code null} * @throws IllegalArgumentException if the {@code resizeWeight} is negative */ protected FormSpec(DefaultAlignment defaultAlignment, Size size, double resizeWeight) { checkNotNull(size, "The size must not be null.");
checkArgument(resizeWeight >= 0, "The resize weight must be non-negative.");
LGoodDatePicker/LGoodDatePicker
Project/src/main/java/com/privatejgoodies/forms/layout/FormSpec.java
// Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static void checkArgument(boolean expression, String message) { // if (!expression) { // throw new IllegalArgumentException(message); // } // } // // Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static String checkNotBlank(String str, String message) { // checkNotNull(str, message); // checkArgument(Strings.isNotBlank(str), message); // return str; // } // // Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static <T> T checkNotNull(T reference, String message) { // if (reference == null) { // throw new NullPointerException(message); // } // return reference; // }
import static com.privatejgoodies.common.base.Preconditions.checkNotBlank; import static com.privatejgoodies.common.base.Preconditions.checkNotNull; import java.awt.Container; import java.io.Serializable; import java.util.List; import java.util.Locale; import java.util.regex.Pattern; import static com.privatejgoodies.common.base.Preconditions.checkArgument;
* horizontal and vertical dialog units, which have different conversion factors. * * @return true for horizontal, false for vertical */ abstract boolean isHorizontal(); // Setting Values ********************************************************* void setDefaultAlignment(DefaultAlignment defaultAlignment) { this.defaultAlignment = defaultAlignment; } void setSize(Size size) { this.size = size; } void setResizeWeight(double resizeWeight) { this.resizeWeight = resizeWeight; } // Parsing ************************************************************** /** * Parses an encoded form specification and initializes all required fields. The encoded * description must be in lower case. * * @param encodedDescription the FormSpec in an encoded format * @throws NullPointerException if {@code encodedDescription} is {@code null} * @throws IllegalArgumentException if {@code encodedDescription} is empty, whitespace, has no * size, or is otherwise invalid */ private void parseAndInitValues(String encodedDescription) {
// Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static void checkArgument(boolean expression, String message) { // if (!expression) { // throw new IllegalArgumentException(message); // } // } // // Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static String checkNotBlank(String str, String message) { // checkNotNull(str, message); // checkArgument(Strings.isNotBlank(str), message); // return str; // } // // Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static <T> T checkNotNull(T reference, String message) { // if (reference == null) { // throw new NullPointerException(message); // } // return reference; // } // Path: Project/src/main/java/com/privatejgoodies/forms/layout/FormSpec.java import static com.privatejgoodies.common.base.Preconditions.checkNotBlank; import static com.privatejgoodies.common.base.Preconditions.checkNotNull; import java.awt.Container; import java.io.Serializable; import java.util.List; import java.util.Locale; import java.util.regex.Pattern; import static com.privatejgoodies.common.base.Preconditions.checkArgument; * horizontal and vertical dialog units, which have different conversion factors. * * @return true for horizontal, false for vertical */ abstract boolean isHorizontal(); // Setting Values ********************************************************* void setDefaultAlignment(DefaultAlignment defaultAlignment) { this.defaultAlignment = defaultAlignment; } void setSize(Size size) { this.size = size; } void setResizeWeight(double resizeWeight) { this.resizeWeight = resizeWeight; } // Parsing ************************************************************** /** * Parses an encoded form specification and initializes all required fields. The encoded * description must be in lower case. * * @param encodedDescription the FormSpec in an encoded format * @throws NullPointerException if {@code encodedDescription} is {@code null} * @throws IllegalArgumentException if {@code encodedDescription} is empty, whitespace, has no * size, or is otherwise invalid */ private void parseAndInitValues(String encodedDescription) {
checkNotBlank(
LGoodDatePicker/LGoodDatePicker
Project/src/main/java/com/privatejgoodies/forms/layout/ConstantSize.java
// Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static void checkArgument(boolean expression, String message) { // if (!expression) { // throw new IllegalArgumentException(message); // } // }
import java.awt.Component; import java.awt.Container; import java.io.Serializable; import java.util.List; import static com.privatejgoodies.common.base.Preconditions.checkArgument;
this.unit = unit; } /** * Constructs a ConstantSize for the given size and unit. * * @param value the size value interpreted in the given units * @param unit the size's unit * @since 1.1 */ public ConstantSize(double value, Unit unit) { this.value = value; this.unit = unit; } /** * Creates and returns a ConstantSize from the given encoded size and unit description. * * @param encodedValueAndUnit the size's value and unit as string, trimmed and in lower case * @param horizontal true for horizontal, false for vertical * @return a constant size for the given encoding and unit description * @throws IllegalArgumentException if the unit requires integer but the value is not an integer */ static ConstantSize valueOf(String encodedValueAndUnit, boolean horizontal) { String[] split = ConstantSize.splitValueAndUnit(encodedValueAndUnit); String encodedValue = split[0]; String encodedUnit = split[1]; Unit unit = Unit.valueOf(encodedUnit, horizontal); double value = Double.parseDouble(encodedValue); if (unit.requiresIntegers) {
// Path: Project/src/main/java/com/privatejgoodies/common/base/Preconditions.java // public static void checkArgument(boolean expression, String message) { // if (!expression) { // throw new IllegalArgumentException(message); // } // } // Path: Project/src/main/java/com/privatejgoodies/forms/layout/ConstantSize.java import java.awt.Component; import java.awt.Container; import java.io.Serializable; import java.util.List; import static com.privatejgoodies.common.base.Preconditions.checkArgument; this.unit = unit; } /** * Constructs a ConstantSize for the given size and unit. * * @param value the size value interpreted in the given units * @param unit the size's unit * @since 1.1 */ public ConstantSize(double value, Unit unit) { this.value = value; this.unit = unit; } /** * Creates and returns a ConstantSize from the given encoded size and unit description. * * @param encodedValueAndUnit the size's value and unit as string, trimmed and in lower case * @param horizontal true for horizontal, false for vertical * @return a constant size for the given encoding and unit description * @throws IllegalArgumentException if the unit requires integer but the value is not an integer */ static ConstantSize valueOf(String encodedValueAndUnit, boolean horizontal) { String[] split = ConstantSize.splitValueAndUnit(encodedValueAndUnit); String encodedValue = split[0]; String encodedUnit = split[1]; Unit unit = Unit.valueOf(encodedUnit, horizontal); double value = Double.parseDouble(encodedValue); if (unit.requiresIntegers) {
checkArgument(value == (int) value, "%s value %s must be an integer.", unit, encodedValue);
DavidGoldman/MobSpawnControls2
src/com/mcf/davidee/msc/packet/BiomeListPacket.java
// Path: src/com/mcf/davidee/msc/network/MSCPacketHandler.java // public abstract class MSCPacketHandler { // // public abstract void handleSettings(SettingsPacket pkt, EntityPlayer player); // public abstract void handleAccessDenied(EntityPlayer player); // public abstract void handleHandShake(EntityPlayer player); // public abstract void handleRequest(PacketType packetType, String mod, EntityPlayer player); // public abstract void handleModList(ModListPacket packet, EntityPlayer player); // public abstract void handleCreatureType(CreatureTypePacket packet, EntityPlayer player); // public abstract void handleGroups(GroupsPacket packet, EntityPlayer player); // public abstract void handleBiomeList(BiomeListPacket packet, EntityPlayer player); // public abstract void handleBiomeSetting(BiomeSettingPacket packet, EntityPlayer player); // public abstract void handleEntityList(EntityListPacket packet, EntityPlayer player); // public abstract void handleEntitySetting(EntitySettingPacket packet, EntityPlayer player); // public abstract void handleEvaluatedBiome(EvaluatedBiomePacket packet, EntityPlayer player); // public abstract void handleEvaluatedGroup(EvaluatedGroupPacket packet, EntityPlayer player); // public abstract void handleDebug(DebugPacket packet, EntityPlayer player); // // protected abstract boolean hasPermission(EntityPlayer player); // // public final void handlePacket(MSCPacket packet, EntityPlayer player) { // if (hasPermission(player)) // packet.execute(this, player); // else if (player instanceof EntityPlayerMP) // MobSpawnControls.DISPATCHER.sendTo(MSCPacket.getPacket(PacketType.ACCESS_DENIED), (EntityPlayerMP)player); // } // }
import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import com.mcf.davidee.msc.network.MSCPacketHandler;
package com.mcf.davidee.msc.packet; public class BiomeListPacket extends MSCPacket{ public boolean evalRequest; public String mod; public String[] groups, biomes; @Override public MSCPacket readData(Object... data) { evalRequest = (Boolean) data[0]; mod = (String) data[1]; groups = (String[]) data[2]; biomes = (String[]) data[3]; return this; } @Override public void encodeInto(ChannelHandlerContext ctx, ByteBuf to) throws IOException { to.writeBoolean(evalRequest); writeString(mod, to); writeStringArray(groups, to); writeStringArray(biomes, to); } @Override public void decodeFrom(ChannelHandlerContext ctx, ByteBuf from) throws IOException { evalRequest = from.readBoolean(); mod = readString(from); groups = readStringArray(from); biomes = readStringArray(from); } @Override
// Path: src/com/mcf/davidee/msc/network/MSCPacketHandler.java // public abstract class MSCPacketHandler { // // public abstract void handleSettings(SettingsPacket pkt, EntityPlayer player); // public abstract void handleAccessDenied(EntityPlayer player); // public abstract void handleHandShake(EntityPlayer player); // public abstract void handleRequest(PacketType packetType, String mod, EntityPlayer player); // public abstract void handleModList(ModListPacket packet, EntityPlayer player); // public abstract void handleCreatureType(CreatureTypePacket packet, EntityPlayer player); // public abstract void handleGroups(GroupsPacket packet, EntityPlayer player); // public abstract void handleBiomeList(BiomeListPacket packet, EntityPlayer player); // public abstract void handleBiomeSetting(BiomeSettingPacket packet, EntityPlayer player); // public abstract void handleEntityList(EntityListPacket packet, EntityPlayer player); // public abstract void handleEntitySetting(EntitySettingPacket packet, EntityPlayer player); // public abstract void handleEvaluatedBiome(EvaluatedBiomePacket packet, EntityPlayer player); // public abstract void handleEvaluatedGroup(EvaluatedGroupPacket packet, EntityPlayer player); // public abstract void handleDebug(DebugPacket packet, EntityPlayer player); // // protected abstract boolean hasPermission(EntityPlayer player); // // public final void handlePacket(MSCPacket packet, EntityPlayer player) { // if (hasPermission(player)) // packet.execute(this, player); // else if (player instanceof EntityPlayerMP) // MobSpawnControls.DISPATCHER.sendTo(MSCPacket.getPacket(PacketType.ACCESS_DENIED), (EntityPlayerMP)player); // } // } // Path: src/com/mcf/davidee/msc/packet/BiomeListPacket.java import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import com.mcf.davidee.msc.network.MSCPacketHandler; package com.mcf.davidee.msc.packet; public class BiomeListPacket extends MSCPacket{ public boolean evalRequest; public String mod; public String[] groups, biomes; @Override public MSCPacket readData(Object... data) { evalRequest = (Boolean) data[0]; mod = (String) data[1]; groups = (String[]) data[2]; biomes = (String[]) data[3]; return this; } @Override public void encodeInto(ChannelHandlerContext ctx, ByteBuf to) throws IOException { to.writeBoolean(evalRequest); writeString(mod, to); writeStringArray(groups, to); writeStringArray(biomes, to); } @Override public void decodeFrom(ChannelHandlerContext ctx, ByteBuf from) throws IOException { evalRequest = from.readBoolean(); mod = readString(from); groups = readStringArray(from); biomes = readStringArray(from); } @Override
public void execute(MSCPacketHandler handler, EntityPlayer player) {
DavidGoldman/MobSpawnControls2
src/com/mcf/davidee/msc/gui/edit/EditGroupScreen.java
// Path: src/com/mcf/davidee/msc/gui/MSCScreen.java // public abstract class MSCScreen extends BasicScreen implements ButtonHandler{ // // public MSCScreen(GuiScreen parent) { // super(parent); // // } // // public boolean doesGuiPauseGame() { // return false; // } // // protected void unhandledKeyTyped(char c, int code) { // if (code == Keyboard.KEY_ESCAPE) // mc.displayGuiScreen(null); // } // // public void setEnabled(boolean aFlag, Button... buttons) { // for (Button b : buttons) // b.setEnabled(aFlag); // } // // protected void reopenedGui() { } // public void buttonClicked(Button button) { } // // } // // Path: src/com/mcf/davidee/msc/gui/popup/PopupMessage.java // public class PopupMessage extends MSCPopup { // // private String bText; // private String[] labelStr; // // private Container container; // private Label[] labels; // private Button ok; // // public PopupMessage(BasicScreen bg, String buttonText, String... strings) { // super(bg); // // this.bText = buttonText; // this.labelStr = strings; // } // // @Override // protected void createGui() { // container = new Container(); // ok = new ButtonVanilla(50, 20, bText, new CloseHandler()); // container.addWidgets(ok); // // labels = new Label[labelStr.length]; // for (int i = 0; i < labels.length; ++i) { // labels[i] = new Label(labelStr[i], 0, 0); // labels[i].setShadowedText(false); // } // container.addWidgets(labels); // // containers.add(container); // selectedContainer = container; // } // // @Override // public void revalidateGui() { // super.revalidateGui(); // int startY = (height - HEIGHT) / 2; // ok.setPosition(width / 2 - 25, startY + 100); // container.revalidate(0, 0, width, height); // // for (int i = 0; i < labels.length; ++i) // labels[i].setPosition(width / 2, startY + i * 13); // } // // }
import java.util.List; import com.mcf.davidee.guilib.basic.Label; import com.mcf.davidee.guilib.core.Button; import com.mcf.davidee.guilib.core.Container; import com.mcf.davidee.guilib.core.Scrollbar; import com.mcf.davidee.guilib.focusable.FocusableLabel; import com.mcf.davidee.guilib.focusable.FocusableSpecialLabel; import com.mcf.davidee.guilib.focusable.FocusableWidget; import com.mcf.davidee.guilib.vanilla.ButtonVanilla; import com.mcf.davidee.guilib.vanilla.ScrollbarVanilla; import com.mcf.davidee.msc.gui.MSCScreen; import com.mcf.davidee.msc.gui.popup.PopupMessage;
((GroupsMenu)getParent()).updateDefinition(groupName, sb.toString()); close(); } if (button == add) addGroupDefinition('+' + ((FocusableSpecialLabel)biomes.deleteFocused()).getSpecialText()); if (button == subtract) addGroupDefinition('-' + ((FocusableSpecialLabel)biomes.deleteFocused()).getSpecialText()); if (button == remove) addUnused(((FocusableSpecialLabel)group.deleteFocused()).getSpecialText()); if (button == inspect){ FocusableSpecialLabel lb = (group.hasFocusedWidget()) ? (FocusableSpecialLabel)group.getFocusedWidget() : (FocusableSpecialLabel)biomes.getFocusedWidget(); if (lb.getSpecialText().contains(".")) showBiomePopup(lb.getText(), lb.getSpecialText()); else showGroupPopup(lb.getSpecialText()); setEnabled(false, add, subtract, inspect, remove); } } private void showBiomePopup(String shown, String actual) { if (shown.charAt(0) == '+' || shown.charAt(0) == '-') { shown = shown.substring(1); actual = actual.substring(1); } String s2 = ""; if (actual.length() > 45) { s2 = actual.substring(45); actual = actual.substring(0,45); }
// Path: src/com/mcf/davidee/msc/gui/MSCScreen.java // public abstract class MSCScreen extends BasicScreen implements ButtonHandler{ // // public MSCScreen(GuiScreen parent) { // super(parent); // // } // // public boolean doesGuiPauseGame() { // return false; // } // // protected void unhandledKeyTyped(char c, int code) { // if (code == Keyboard.KEY_ESCAPE) // mc.displayGuiScreen(null); // } // // public void setEnabled(boolean aFlag, Button... buttons) { // for (Button b : buttons) // b.setEnabled(aFlag); // } // // protected void reopenedGui() { } // public void buttonClicked(Button button) { } // // } // // Path: src/com/mcf/davidee/msc/gui/popup/PopupMessage.java // public class PopupMessage extends MSCPopup { // // private String bText; // private String[] labelStr; // // private Container container; // private Label[] labels; // private Button ok; // // public PopupMessage(BasicScreen bg, String buttonText, String... strings) { // super(bg); // // this.bText = buttonText; // this.labelStr = strings; // } // // @Override // protected void createGui() { // container = new Container(); // ok = new ButtonVanilla(50, 20, bText, new CloseHandler()); // container.addWidgets(ok); // // labels = new Label[labelStr.length]; // for (int i = 0; i < labels.length; ++i) { // labels[i] = new Label(labelStr[i], 0, 0); // labels[i].setShadowedText(false); // } // container.addWidgets(labels); // // containers.add(container); // selectedContainer = container; // } // // @Override // public void revalidateGui() { // super.revalidateGui(); // int startY = (height - HEIGHT) / 2; // ok.setPosition(width / 2 - 25, startY + 100); // container.revalidate(0, 0, width, height); // // for (int i = 0; i < labels.length; ++i) // labels[i].setPosition(width / 2, startY + i * 13); // } // // } // Path: src/com/mcf/davidee/msc/gui/edit/EditGroupScreen.java import java.util.List; import com.mcf.davidee.guilib.basic.Label; import com.mcf.davidee.guilib.core.Button; import com.mcf.davidee.guilib.core.Container; import com.mcf.davidee.guilib.core.Scrollbar; import com.mcf.davidee.guilib.focusable.FocusableLabel; import com.mcf.davidee.guilib.focusable.FocusableSpecialLabel; import com.mcf.davidee.guilib.focusable.FocusableWidget; import com.mcf.davidee.guilib.vanilla.ButtonVanilla; import com.mcf.davidee.guilib.vanilla.ScrollbarVanilla; import com.mcf.davidee.msc.gui.MSCScreen; import com.mcf.davidee.msc.gui.popup.PopupMessage; ((GroupsMenu)getParent()).updateDefinition(groupName, sb.toString()); close(); } if (button == add) addGroupDefinition('+' + ((FocusableSpecialLabel)biomes.deleteFocused()).getSpecialText()); if (button == subtract) addGroupDefinition('-' + ((FocusableSpecialLabel)biomes.deleteFocused()).getSpecialText()); if (button == remove) addUnused(((FocusableSpecialLabel)group.deleteFocused()).getSpecialText()); if (button == inspect){ FocusableSpecialLabel lb = (group.hasFocusedWidget()) ? (FocusableSpecialLabel)group.getFocusedWidget() : (FocusableSpecialLabel)biomes.getFocusedWidget(); if (lb.getSpecialText().contains(".")) showBiomePopup(lb.getText(), lb.getSpecialText()); else showGroupPopup(lb.getSpecialText()); setEnabled(false, add, subtract, inspect, remove); } } private void showBiomePopup(String shown, String actual) { if (shown.charAt(0) == '+' || shown.charAt(0) == '-') { shown = shown.substring(1); actual = actual.substring(1); } String s2 = ""; if (actual.length() > 45) { s2 = actual.substring(45); actual = actual.substring(0,45); }
mc.displayGuiScreen(new PopupMessage(this, "OK", "", "Biome \"" + shown + "\"", "", "", actual, s2));
DavidGoldman/MobSpawnControls2
src/com/mcf/davidee/msc/packet/ModListPacket.java
// Path: src/com/mcf/davidee/msc/network/MSCPacketHandler.java // public abstract class MSCPacketHandler { // // public abstract void handleSettings(SettingsPacket pkt, EntityPlayer player); // public abstract void handleAccessDenied(EntityPlayer player); // public abstract void handleHandShake(EntityPlayer player); // public abstract void handleRequest(PacketType packetType, String mod, EntityPlayer player); // public abstract void handleModList(ModListPacket packet, EntityPlayer player); // public abstract void handleCreatureType(CreatureTypePacket packet, EntityPlayer player); // public abstract void handleGroups(GroupsPacket packet, EntityPlayer player); // public abstract void handleBiomeList(BiomeListPacket packet, EntityPlayer player); // public abstract void handleBiomeSetting(BiomeSettingPacket packet, EntityPlayer player); // public abstract void handleEntityList(EntityListPacket packet, EntityPlayer player); // public abstract void handleEntitySetting(EntitySettingPacket packet, EntityPlayer player); // public abstract void handleEvaluatedBiome(EvaluatedBiomePacket packet, EntityPlayer player); // public abstract void handleEvaluatedGroup(EvaluatedGroupPacket packet, EntityPlayer player); // public abstract void handleDebug(DebugPacket packet, EntityPlayer player); // // protected abstract boolean hasPermission(EntityPlayer player); // // public final void handlePacket(MSCPacket packet, EntityPlayer player) { // if (hasPermission(player)) // packet.execute(this, player); // else if (player instanceof EntityPlayerMP) // MobSpawnControls.DISPATCHER.sendTo(MSCPacket.getPacket(PacketType.ACCESS_DENIED), (EntityPlayerMP)player); // } // }
import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import com.mcf.davidee.msc.network.MSCPacketHandler;
package com.mcf.davidee.msc.packet; public class ModListPacket extends MSCPacket { public String[] mods; @Override public MSCPacket readData(Object... data) { mods = (String[]) data[0]; return this; } @Override public void encodeInto(ChannelHandlerContext ctx, ByteBuf to) throws IOException { writeStringArray(mods, to); } @Override public void decodeFrom(ChannelHandlerContext ctx, ByteBuf from) throws IOException { mods = readStringArray(from); } @Override
// Path: src/com/mcf/davidee/msc/network/MSCPacketHandler.java // public abstract class MSCPacketHandler { // // public abstract void handleSettings(SettingsPacket pkt, EntityPlayer player); // public abstract void handleAccessDenied(EntityPlayer player); // public abstract void handleHandShake(EntityPlayer player); // public abstract void handleRequest(PacketType packetType, String mod, EntityPlayer player); // public abstract void handleModList(ModListPacket packet, EntityPlayer player); // public abstract void handleCreatureType(CreatureTypePacket packet, EntityPlayer player); // public abstract void handleGroups(GroupsPacket packet, EntityPlayer player); // public abstract void handleBiomeList(BiomeListPacket packet, EntityPlayer player); // public abstract void handleBiomeSetting(BiomeSettingPacket packet, EntityPlayer player); // public abstract void handleEntityList(EntityListPacket packet, EntityPlayer player); // public abstract void handleEntitySetting(EntitySettingPacket packet, EntityPlayer player); // public abstract void handleEvaluatedBiome(EvaluatedBiomePacket packet, EntityPlayer player); // public abstract void handleEvaluatedGroup(EvaluatedGroupPacket packet, EntityPlayer player); // public abstract void handleDebug(DebugPacket packet, EntityPlayer player); // // protected abstract boolean hasPermission(EntityPlayer player); // // public final void handlePacket(MSCPacket packet, EntityPlayer player) { // if (hasPermission(player)) // packet.execute(this, player); // else if (player instanceof EntityPlayerMP) // MobSpawnControls.DISPATCHER.sendTo(MSCPacket.getPacket(PacketType.ACCESS_DENIED), (EntityPlayerMP)player); // } // } // Path: src/com/mcf/davidee/msc/packet/ModListPacket.java import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import com.mcf.davidee.msc.network.MSCPacketHandler; package com.mcf.davidee.msc.packet; public class ModListPacket extends MSCPacket { public String[] mods; @Override public MSCPacket readData(Object... data) { mods = (String[]) data[0]; return this; } @Override public void encodeInto(ChannelHandlerContext ctx, ByteBuf to) throws IOException { writeStringArray(mods, to); } @Override public void decodeFrom(ChannelHandlerContext ctx, ByteBuf from) throws IOException { mods = readStringArray(from); } @Override
public void execute(MSCPacketHandler handler, EntityPlayer player) {
DavidGoldman/MobSpawnControls2
src/com/mcf/davidee/msc/gui/list/EvaluatedGroupsScreen.java
// Path: src/com/mcf/davidee/msc/gui/MSCScreen.java // public abstract class MSCScreen extends BasicScreen implements ButtonHandler{ // // public MSCScreen(GuiScreen parent) { // super(parent); // // } // // public boolean doesGuiPauseGame() { // return false; // } // // protected void unhandledKeyTyped(char c, int code) { // if (code == Keyboard.KEY_ESCAPE) // mc.displayGuiScreen(null); // } // // public void setEnabled(boolean aFlag, Button... buttons) { // for (Button b : buttons) // b.setEnabled(aFlag); // } // // protected void reopenedGui() { } // public void buttonClicked(Button button) { } // // } // // Path: src/com/mcf/davidee/msc/packet/settings/EvaluatedGroupPacket.java // public class EvaluatedGroupPacket extends MSCPacket { // // public String mod; // public String group; // public String[] biomes; // // @Override // public MSCPacket readData(Object... data) { // mod = (String) data[0]; // group = (String) data[1]; // biomes = (String[]) data[2]; // return this; // } // // @Override // public void encodeInto(ChannelHandlerContext ctx, ByteBuf to) throws IOException { // writeString(mod, to); // writeString(group, to); // writeStringArray(biomes, to); // } // // @Override // public void decodeFrom(ChannelHandlerContext ctx, ByteBuf from) throws IOException { // mod = readString(from); // group = readString(from); // biomes = readStringArray(from); // } // // @Override // public void execute(MSCPacketHandler handler, EntityPlayer player) { // handler.handleEvaluatedGroup(this, player); // } // // }
import java.util.List; import net.minecraft.client.gui.GuiScreen; import com.mcf.davidee.guilib.basic.FocusedContainer; import com.mcf.davidee.guilib.basic.Label; import com.mcf.davidee.guilib.core.Button; import com.mcf.davidee.guilib.core.Container; import com.mcf.davidee.guilib.core.Scrollbar; import com.mcf.davidee.guilib.focusable.FocusableLabel; import com.mcf.davidee.guilib.focusable.FocusableWidget; import com.mcf.davidee.guilib.vanilla.ButtonVanilla; import com.mcf.davidee.guilib.vanilla.ScrollbarVanilla; import com.mcf.davidee.msc.gui.MSCScreen; import com.mcf.davidee.msc.packet.settings.EvaluatedGroupPacket;
package com.mcf.davidee.msc.gui.list; public class EvaluatedGroupsScreen extends MSCScreen { private Label title, subTitle; private Button close; private Scrollbar scrollbar; private Container masterContainer, labelContainer;
// Path: src/com/mcf/davidee/msc/gui/MSCScreen.java // public abstract class MSCScreen extends BasicScreen implements ButtonHandler{ // // public MSCScreen(GuiScreen parent) { // super(parent); // // } // // public boolean doesGuiPauseGame() { // return false; // } // // protected void unhandledKeyTyped(char c, int code) { // if (code == Keyboard.KEY_ESCAPE) // mc.displayGuiScreen(null); // } // // public void setEnabled(boolean aFlag, Button... buttons) { // for (Button b : buttons) // b.setEnabled(aFlag); // } // // protected void reopenedGui() { } // public void buttonClicked(Button button) { } // // } // // Path: src/com/mcf/davidee/msc/packet/settings/EvaluatedGroupPacket.java // public class EvaluatedGroupPacket extends MSCPacket { // // public String mod; // public String group; // public String[] biomes; // // @Override // public MSCPacket readData(Object... data) { // mod = (String) data[0]; // group = (String) data[1]; // biomes = (String[]) data[2]; // return this; // } // // @Override // public void encodeInto(ChannelHandlerContext ctx, ByteBuf to) throws IOException { // writeString(mod, to); // writeString(group, to); // writeStringArray(biomes, to); // } // // @Override // public void decodeFrom(ChannelHandlerContext ctx, ByteBuf from) throws IOException { // mod = readString(from); // group = readString(from); // biomes = readStringArray(from); // } // // @Override // public void execute(MSCPacketHandler handler, EntityPlayer player) { // handler.handleEvaluatedGroup(this, player); // } // // } // Path: src/com/mcf/davidee/msc/gui/list/EvaluatedGroupsScreen.java import java.util.List; import net.minecraft.client.gui.GuiScreen; import com.mcf.davidee.guilib.basic.FocusedContainer; import com.mcf.davidee.guilib.basic.Label; import com.mcf.davidee.guilib.core.Button; import com.mcf.davidee.guilib.core.Container; import com.mcf.davidee.guilib.core.Scrollbar; import com.mcf.davidee.guilib.focusable.FocusableLabel; import com.mcf.davidee.guilib.focusable.FocusableWidget; import com.mcf.davidee.guilib.vanilla.ButtonVanilla; import com.mcf.davidee.guilib.vanilla.ScrollbarVanilla; import com.mcf.davidee.msc.gui.MSCScreen; import com.mcf.davidee.msc.packet.settings.EvaluatedGroupPacket; package com.mcf.davidee.msc.gui.list; public class EvaluatedGroupsScreen extends MSCScreen { private Label title, subTitle; private Button close; private Scrollbar scrollbar; private Container masterContainer, labelContainer;
private EvaluatedGroupPacket packet;
DavidGoldman/MobSpawnControls2
src/com/mcf/davidee/msc/packet/ADPacket.java
// Path: src/com/mcf/davidee/msc/network/MSCPacketHandler.java // public abstract class MSCPacketHandler { // // public abstract void handleSettings(SettingsPacket pkt, EntityPlayer player); // public abstract void handleAccessDenied(EntityPlayer player); // public abstract void handleHandShake(EntityPlayer player); // public abstract void handleRequest(PacketType packetType, String mod, EntityPlayer player); // public abstract void handleModList(ModListPacket packet, EntityPlayer player); // public abstract void handleCreatureType(CreatureTypePacket packet, EntityPlayer player); // public abstract void handleGroups(GroupsPacket packet, EntityPlayer player); // public abstract void handleBiomeList(BiomeListPacket packet, EntityPlayer player); // public abstract void handleBiomeSetting(BiomeSettingPacket packet, EntityPlayer player); // public abstract void handleEntityList(EntityListPacket packet, EntityPlayer player); // public abstract void handleEntitySetting(EntitySettingPacket packet, EntityPlayer player); // public abstract void handleEvaluatedBiome(EvaluatedBiomePacket packet, EntityPlayer player); // public abstract void handleEvaluatedGroup(EvaluatedGroupPacket packet, EntityPlayer player); // public abstract void handleDebug(DebugPacket packet, EntityPlayer player); // // protected abstract boolean hasPermission(EntityPlayer player); // // public final void handlePacket(MSCPacket packet, EntityPlayer player) { // if (hasPermission(player)) // packet.execute(this, player); // else if (player instanceof EntityPlayerMP) // MobSpawnControls.DISPATCHER.sendTo(MSCPacket.getPacket(PacketType.ACCESS_DENIED), (EntityPlayerMP)player); // } // }
import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import com.mcf.davidee.msc.network.MSCPacketHandler;
package com.mcf.davidee.msc.packet; public class ADPacket extends MSCPacket { @Override public MSCPacket readData(Object... data) { return this; } @Override public void encodeInto(ChannelHandlerContext ctx, ByteBuf to) throws IOException { } @Override public void decodeFrom(ChannelHandlerContext ctx, ByteBuf from) throws IOException { } @Override
// Path: src/com/mcf/davidee/msc/network/MSCPacketHandler.java // public abstract class MSCPacketHandler { // // public abstract void handleSettings(SettingsPacket pkt, EntityPlayer player); // public abstract void handleAccessDenied(EntityPlayer player); // public abstract void handleHandShake(EntityPlayer player); // public abstract void handleRequest(PacketType packetType, String mod, EntityPlayer player); // public abstract void handleModList(ModListPacket packet, EntityPlayer player); // public abstract void handleCreatureType(CreatureTypePacket packet, EntityPlayer player); // public abstract void handleGroups(GroupsPacket packet, EntityPlayer player); // public abstract void handleBiomeList(BiomeListPacket packet, EntityPlayer player); // public abstract void handleBiomeSetting(BiomeSettingPacket packet, EntityPlayer player); // public abstract void handleEntityList(EntityListPacket packet, EntityPlayer player); // public abstract void handleEntitySetting(EntitySettingPacket packet, EntityPlayer player); // public abstract void handleEvaluatedBiome(EvaluatedBiomePacket packet, EntityPlayer player); // public abstract void handleEvaluatedGroup(EvaluatedGroupPacket packet, EntityPlayer player); // public abstract void handleDebug(DebugPacket packet, EntityPlayer player); // // protected abstract boolean hasPermission(EntityPlayer player); // // public final void handlePacket(MSCPacket packet, EntityPlayer player) { // if (hasPermission(player)) // packet.execute(this, player); // else if (player instanceof EntityPlayerMP) // MobSpawnControls.DISPATCHER.sendTo(MSCPacket.getPacket(PacketType.ACCESS_DENIED), (EntityPlayerMP)player); // } // } // Path: src/com/mcf/davidee/msc/packet/ADPacket.java import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import com.mcf.davidee.msc.network.MSCPacketHandler; package com.mcf.davidee.msc.packet; public class ADPacket extends MSCPacket { @Override public MSCPacket readData(Object... data) { return this; } @Override public void encodeInto(ChannelHandlerContext ctx, ByteBuf to) throws IOException { } @Override public void decodeFrom(ChannelHandlerContext ctx, ByteBuf from) throws IOException { } @Override
public void execute(MSCPacketHandler handler, EntityPlayer player) {
DavidGoldman/MobSpawnControls2
src/com/mcf/davidee/msc/reflect/SpawnFrequencyHelper.java
// Path: src/com/mcf/davidee/msc/MobSpawnControls.java // @Mod(modid = "MSC2", name="Mob Spawn Controls 2", dependencies = "after:*", version=MobSpawnControls.VERSION) // public class MobSpawnControls{ // // public static final String VERSION = "1.2.1"; // public static final PacketPipeline DISPATCHER = new PacketPipeline(); // // @SidedProxy(clientSide = "com.mcf.davidee.msc.forge.ClientProxy", serverSide = "com.mcf.davidee.msc.forge.CommonProxy") // public static CommonProxy proxy; // @Instance("MSC2") // public static MobSpawnControls instance; // // private static FileHandler logHandler = null; // private static Logger logger = Logger.getLogger("MobSpawnControls"); // // // public static Logger getLogger() { // return logger; // } // // private SpawnConfiguration config, defaultConfig; // private SpawnFreqTicker ticker; // // // @EventHandler // public void preInit(FMLPreInitializationEvent event) { // ModMetadata modMeta = event.getModMetadata(); // modMeta.authorList = Arrays.asList(new String[] { "Davidee" }); // modMeta.autogenerated = false; // modMeta.credits = "Thanks to Mojang, Forge, and all your support."; // modMeta.description = "Allows you to control the vanilla spawning system."; // modMeta.url = "http://www.minecraftforum.net/topic/1909304-/"; // } // // @EventHandler // public void load(FMLInitializationEvent event) { // logger.setLevel(Level.ALL); // // try { // File logfile = new File(proxy.getMinecraftDirectory(),"MobSpawnControls.log"); // if ((logfile.exists() || logfile.createNewFile()) && logfile.canWrite() && logHandler == null) { // logHandler = new FileHandler(logfile.getPath()); // logHandler.setFormatter(new MSCLogFormatter()); // logger.addHandler(logHandler); // } // } catch (SecurityException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // // logger.info("Mob Spawn Controls initializing..."); // // ticker = new SpawnFreqTicker(); // DISPATCHER.initialize(); // } // // @EventHandler // public void modsLoaded(FMLPostInitializationEvent event) { // BiomeClassLoader.loadBiomeClasses(); // logger.info("Generating default creature type map..."); // MobHelper.populateDefaultMap(); // logger.info("Mapping biomes..."); // BiomeNameHelper.initBiomeMap(); // logger.info("Creating default spawn configuration..."); // defaultConfig = new SpawnConfiguration(new File(new File(proxy.getMinecraftDirectory(),"config"), "default_msc")); // defaultConfig.load(); // defaultConfig.save(); // } // // @SubscribeEvent // public void onServerTick(ServerTickEvent event) { // ticker.tick(); // } // // @EventHandler // public void serverStarting(FMLServerStartingEvent event) { // MinecraftServer server = event.getServer(); // WorldServer world = server.worldServerForDimension(0); // if (world != null && world.getSaveHandler() instanceof SaveHandler){ // logger.info("Creating spawn configuration for World \"" + world.getSaveHandler().getWorldDirectoryName() + "\""); // config = new SpawnConfiguration(new File(((SaveHandler)world.getSaveHandler()).getWorldDirectory(),"msc"), defaultConfig); // config.load(); // config.save(); // } // } // // @EventHandler // public void serverStopping(FMLServerStoppingEvent event) { // logger.info("Unloading spawn configuration"); // MSCLogFormatter.log.clear(); // config = null; // } // // public SpawnConfiguration getConfigNoThrow() { // return config; // } // // public SpawnConfiguration getConfig() throws RuntimeException { // if (config != null) // return config; // throw new RuntimeException("MSC: Null Spawn Config"); // } // // // }
import net.minecraft.entity.EnumCreatureType; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import com.mcf.davidee.msc.MobSpawnControls;
package com.mcf.davidee.msc.reflect; public class SpawnFrequencyHelper { public static boolean setSpawnCreature(EnumCreatureType type, boolean value) { try { Field field = EnumCreatureType.class.getDeclaredFields()[8]; field.setAccessible(true); Field modifiers = Field.class.getDeclaredField("modifiers"); modifiers.setAccessible(true); modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL); field.set(type, value); return true; } catch(Exception e){
// Path: src/com/mcf/davidee/msc/MobSpawnControls.java // @Mod(modid = "MSC2", name="Mob Spawn Controls 2", dependencies = "after:*", version=MobSpawnControls.VERSION) // public class MobSpawnControls{ // // public static final String VERSION = "1.2.1"; // public static final PacketPipeline DISPATCHER = new PacketPipeline(); // // @SidedProxy(clientSide = "com.mcf.davidee.msc.forge.ClientProxy", serverSide = "com.mcf.davidee.msc.forge.CommonProxy") // public static CommonProxy proxy; // @Instance("MSC2") // public static MobSpawnControls instance; // // private static FileHandler logHandler = null; // private static Logger logger = Logger.getLogger("MobSpawnControls"); // // // public static Logger getLogger() { // return logger; // } // // private SpawnConfiguration config, defaultConfig; // private SpawnFreqTicker ticker; // // // @EventHandler // public void preInit(FMLPreInitializationEvent event) { // ModMetadata modMeta = event.getModMetadata(); // modMeta.authorList = Arrays.asList(new String[] { "Davidee" }); // modMeta.autogenerated = false; // modMeta.credits = "Thanks to Mojang, Forge, and all your support."; // modMeta.description = "Allows you to control the vanilla spawning system."; // modMeta.url = "http://www.minecraftforum.net/topic/1909304-/"; // } // // @EventHandler // public void load(FMLInitializationEvent event) { // logger.setLevel(Level.ALL); // // try { // File logfile = new File(proxy.getMinecraftDirectory(),"MobSpawnControls.log"); // if ((logfile.exists() || logfile.createNewFile()) && logfile.canWrite() && logHandler == null) { // logHandler = new FileHandler(logfile.getPath()); // logHandler.setFormatter(new MSCLogFormatter()); // logger.addHandler(logHandler); // } // } catch (SecurityException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // // logger.info("Mob Spawn Controls initializing..."); // // ticker = new SpawnFreqTicker(); // DISPATCHER.initialize(); // } // // @EventHandler // public void modsLoaded(FMLPostInitializationEvent event) { // BiomeClassLoader.loadBiomeClasses(); // logger.info("Generating default creature type map..."); // MobHelper.populateDefaultMap(); // logger.info("Mapping biomes..."); // BiomeNameHelper.initBiomeMap(); // logger.info("Creating default spawn configuration..."); // defaultConfig = new SpawnConfiguration(new File(new File(proxy.getMinecraftDirectory(),"config"), "default_msc")); // defaultConfig.load(); // defaultConfig.save(); // } // // @SubscribeEvent // public void onServerTick(ServerTickEvent event) { // ticker.tick(); // } // // @EventHandler // public void serverStarting(FMLServerStartingEvent event) { // MinecraftServer server = event.getServer(); // WorldServer world = server.worldServerForDimension(0); // if (world != null && world.getSaveHandler() instanceof SaveHandler){ // logger.info("Creating spawn configuration for World \"" + world.getSaveHandler().getWorldDirectoryName() + "\""); // config = new SpawnConfiguration(new File(((SaveHandler)world.getSaveHandler()).getWorldDirectory(),"msc"), defaultConfig); // config.load(); // config.save(); // } // } // // @EventHandler // public void serverStopping(FMLServerStoppingEvent event) { // logger.info("Unloading spawn configuration"); // MSCLogFormatter.log.clear(); // config = null; // } // // public SpawnConfiguration getConfigNoThrow() { // return config; // } // // public SpawnConfiguration getConfig() throws RuntimeException { // if (config != null) // return config; // throw new RuntimeException("MSC: Null Spawn Config"); // } // // // } // Path: src/com/mcf/davidee/msc/reflect/SpawnFrequencyHelper.java import net.minecraft.entity.EnumCreatureType; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import com.mcf.davidee.msc.MobSpawnControls; package com.mcf.davidee.msc.reflect; public class SpawnFrequencyHelper { public static boolean setSpawnCreature(EnumCreatureType type, boolean value) { try { Field field = EnumCreatureType.class.getDeclaredFields()[8]; field.setAccessible(true); Field modifiers = Field.class.getDeclaredField("modifiers"); modifiers.setAccessible(true); modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL); field.set(type, value); return true; } catch(Exception e){
MobSpawnControls.getLogger().throwing("SpawnFrequencyHelper", "setSpawnCreature", e);
DavidGoldman/MobSpawnControls2
src/com/mcf/davidee/msc/packet/HSPacket.java
// Path: src/com/mcf/davidee/msc/network/MSCPacketHandler.java // public abstract class MSCPacketHandler { // // public abstract void handleSettings(SettingsPacket pkt, EntityPlayer player); // public abstract void handleAccessDenied(EntityPlayer player); // public abstract void handleHandShake(EntityPlayer player); // public abstract void handleRequest(PacketType packetType, String mod, EntityPlayer player); // public abstract void handleModList(ModListPacket packet, EntityPlayer player); // public abstract void handleCreatureType(CreatureTypePacket packet, EntityPlayer player); // public abstract void handleGroups(GroupsPacket packet, EntityPlayer player); // public abstract void handleBiomeList(BiomeListPacket packet, EntityPlayer player); // public abstract void handleBiomeSetting(BiomeSettingPacket packet, EntityPlayer player); // public abstract void handleEntityList(EntityListPacket packet, EntityPlayer player); // public abstract void handleEntitySetting(EntitySettingPacket packet, EntityPlayer player); // public abstract void handleEvaluatedBiome(EvaluatedBiomePacket packet, EntityPlayer player); // public abstract void handleEvaluatedGroup(EvaluatedGroupPacket packet, EntityPlayer player); // public abstract void handleDebug(DebugPacket packet, EntityPlayer player); // // protected abstract boolean hasPermission(EntityPlayer player); // // public final void handlePacket(MSCPacket packet, EntityPlayer player) { // if (hasPermission(player)) // packet.execute(this, player); // else if (player instanceof EntityPlayerMP) // MobSpawnControls.DISPATCHER.sendTo(MSCPacket.getPacket(PacketType.ACCESS_DENIED), (EntityPlayerMP)player); // } // }
import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import com.mcf.davidee.msc.network.MSCPacketHandler;
package com.mcf.davidee.msc.packet; public class HSPacket extends MSCPacket { @Override public MSCPacket readData(Object... data) { return this; } @Override public void encodeInto(ChannelHandlerContext ctx, ByteBuf to) throws IOException { } @Override public void decodeFrom(ChannelHandlerContext ctx, ByteBuf from) throws IOException { } @Override
// Path: src/com/mcf/davidee/msc/network/MSCPacketHandler.java // public abstract class MSCPacketHandler { // // public abstract void handleSettings(SettingsPacket pkt, EntityPlayer player); // public abstract void handleAccessDenied(EntityPlayer player); // public abstract void handleHandShake(EntityPlayer player); // public abstract void handleRequest(PacketType packetType, String mod, EntityPlayer player); // public abstract void handleModList(ModListPacket packet, EntityPlayer player); // public abstract void handleCreatureType(CreatureTypePacket packet, EntityPlayer player); // public abstract void handleGroups(GroupsPacket packet, EntityPlayer player); // public abstract void handleBiomeList(BiomeListPacket packet, EntityPlayer player); // public abstract void handleBiomeSetting(BiomeSettingPacket packet, EntityPlayer player); // public abstract void handleEntityList(EntityListPacket packet, EntityPlayer player); // public abstract void handleEntitySetting(EntitySettingPacket packet, EntityPlayer player); // public abstract void handleEvaluatedBiome(EvaluatedBiomePacket packet, EntityPlayer player); // public abstract void handleEvaluatedGroup(EvaluatedGroupPacket packet, EntityPlayer player); // public abstract void handleDebug(DebugPacket packet, EntityPlayer player); // // protected abstract boolean hasPermission(EntityPlayer player); // // public final void handlePacket(MSCPacket packet, EntityPlayer player) { // if (hasPermission(player)) // packet.execute(this, player); // else if (player instanceof EntityPlayerMP) // MobSpawnControls.DISPATCHER.sendTo(MSCPacket.getPacket(PacketType.ACCESS_DENIED), (EntityPlayerMP)player); // } // } // Path: src/com/mcf/davidee/msc/packet/HSPacket.java import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import com.mcf.davidee.msc.network.MSCPacketHandler; package com.mcf.davidee.msc.packet; public class HSPacket extends MSCPacket { @Override public MSCPacket readData(Object... data) { return this; } @Override public void encodeInto(ChannelHandlerContext ctx, ByteBuf to) throws IOException { } @Override public void decodeFrom(ChannelHandlerContext ctx, ByteBuf from) throws IOException { } @Override
public void execute(MSCPacketHandler handler, EntityPlayer player) {
DavidGoldman/MobSpawnControls2
src/com/mcf/davidee/msc/spawning/MobHelper.java
// Path: src/com/mcf/davidee/msc/config/ModEntityRecognizer.java // public class ModEntityRecognizer { // // private static ListMultimap<ModContainer, EntityRegistration> registr = getRegistrations(); // // public static List<EntityRegistration> getRegistrations(ModContainer c) { // return registr.get(c); // } // // private static ListMultimap<ModContainer, EntityRegistration> getRegistrations() { // return ObfuscationReflectionHelper.getPrivateValue(EntityRegistry.class, EntityRegistry.instance(), "entityRegistrations"); // } // // @SuppressWarnings("unchecked") // public static List<Class<? extends EntityLiving>> getEntityClasses(ModContainer c) { // if (c == null) // return getVanillaEntityClasses(); // List<EntityRegistration> regs = getRegistrations(c); // List<Class<? extends EntityLiving>> cls = new ArrayList<Class<? extends EntityLiving>>(regs.size()); // for (EntityRegistration r : regs) { // if (isValidEntityClass(r.getEntityClass())) // cls.add((Class<? extends EntityLiving>) r.getEntityClass()); // } // return cls; // } // // @SuppressWarnings("unchecked") // private static List<Class<? extends EntityLiving>> getVanillaEntityClasses() { // List<Class<? extends EntityLiving>> cls = new ArrayList<Class<? extends EntityLiving>>(); // for (Object o : EntityList.classToStringMapping.entrySet()) { // Entry<Class<? extends Entity>, String> entry = (Entry<Class<? extends Entity>, String>) o; // if (isValidEntityClass(entry.getKey()) && EntityRegistry.instance().lookupModSpawn(entry.getKey(),false) == null) // cls.add((Class<? extends EntityLiving>) entry.getKey()); // } // return cls; // // } // // public static boolean hasEntities(ModContainer c) { // for (EntityRegistration r : getRegistrations(c)) // if (isValidEntityClass(r.getEntityClass())) // return true; // return false; // } // // public static boolean isValidEntityClass(Class<?> c) { // return c != null && !Modifier.isAbstract(c.getModifiers()) && EntityLiving.class.isAssignableFrom(c); // } // // } // // Path: src/com/mcf/davidee/msc/reflect/BiomeReflector.java // public class BiomeReflector { // // private static final int MONSTER_INDEX = 72; // // //TODO Cache // public static List<SpawnListEntry> reflectList(BiomeGenBase biome, EnumCreatureType type) { // try { // int ordin = (type == EnumCreatureType.waterCreature) ? 2 : (type == EnumCreatureType.ambient) ? 3 : type.ordinal(); // return reflect(biome,ordin); // } // catch(Exception e){ // MobSpawnControls.getLogger().severe("Unable to reflect list for biome " + BiomeNameHelper.getBiomeName(biome) + " of type " + type); // MobSpawnControls.getLogger().throwing("BiomeReflector", "reflectList", e); // throw new RuntimeException(e); // } // } // // @SuppressWarnings("unchecked") // private static List<SpawnListEntry> reflect(BiomeGenBase biome, int ordinal) throws Exception { // Field f = BiomeGenBase.class.getDeclaredFields()[MONSTER_INDEX+ordinal]; // f.setAccessible(true); // return (List<SpawnListEntry>)f.get(biome); // } // }
import java.util.Set; import net.minecraft.entity.EntityCreature; import net.minecraft.entity.EntityList; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EnumCreatureType; import net.minecraft.entity.monster.IMob; import net.minecraft.entity.passive.EntityAmbientCreature; import net.minecraft.entity.passive.EntityWaterMob; import net.minecraft.world.biome.BiomeGenBase; import net.minecraft.world.biome.BiomeGenBase.SpawnListEntry; import com.mcf.davidee.msc.config.ModEntityRecognizer; import com.mcf.davidee.msc.reflect.BiomeReflector;
package com.mcf.davidee.msc.spawning; public class MobHelper { private static CreatureTypeMap defaultMap = new CreatureTypeMap(); @SuppressWarnings({ "rawtypes", "unchecked" }) public static void populateDefaultMap(){ for (Class c: (Set<Class>)EntityList.classToStringMapping.keySet()){
// Path: src/com/mcf/davidee/msc/config/ModEntityRecognizer.java // public class ModEntityRecognizer { // // private static ListMultimap<ModContainer, EntityRegistration> registr = getRegistrations(); // // public static List<EntityRegistration> getRegistrations(ModContainer c) { // return registr.get(c); // } // // private static ListMultimap<ModContainer, EntityRegistration> getRegistrations() { // return ObfuscationReflectionHelper.getPrivateValue(EntityRegistry.class, EntityRegistry.instance(), "entityRegistrations"); // } // // @SuppressWarnings("unchecked") // public static List<Class<? extends EntityLiving>> getEntityClasses(ModContainer c) { // if (c == null) // return getVanillaEntityClasses(); // List<EntityRegistration> regs = getRegistrations(c); // List<Class<? extends EntityLiving>> cls = new ArrayList<Class<? extends EntityLiving>>(regs.size()); // for (EntityRegistration r : regs) { // if (isValidEntityClass(r.getEntityClass())) // cls.add((Class<? extends EntityLiving>) r.getEntityClass()); // } // return cls; // } // // @SuppressWarnings("unchecked") // private static List<Class<? extends EntityLiving>> getVanillaEntityClasses() { // List<Class<? extends EntityLiving>> cls = new ArrayList<Class<? extends EntityLiving>>(); // for (Object o : EntityList.classToStringMapping.entrySet()) { // Entry<Class<? extends Entity>, String> entry = (Entry<Class<? extends Entity>, String>) o; // if (isValidEntityClass(entry.getKey()) && EntityRegistry.instance().lookupModSpawn(entry.getKey(),false) == null) // cls.add((Class<? extends EntityLiving>) entry.getKey()); // } // return cls; // // } // // public static boolean hasEntities(ModContainer c) { // for (EntityRegistration r : getRegistrations(c)) // if (isValidEntityClass(r.getEntityClass())) // return true; // return false; // } // // public static boolean isValidEntityClass(Class<?> c) { // return c != null && !Modifier.isAbstract(c.getModifiers()) && EntityLiving.class.isAssignableFrom(c); // } // // } // // Path: src/com/mcf/davidee/msc/reflect/BiomeReflector.java // public class BiomeReflector { // // private static final int MONSTER_INDEX = 72; // // //TODO Cache // public static List<SpawnListEntry> reflectList(BiomeGenBase biome, EnumCreatureType type) { // try { // int ordin = (type == EnumCreatureType.waterCreature) ? 2 : (type == EnumCreatureType.ambient) ? 3 : type.ordinal(); // return reflect(biome,ordin); // } // catch(Exception e){ // MobSpawnControls.getLogger().severe("Unable to reflect list for biome " + BiomeNameHelper.getBiomeName(biome) + " of type " + type); // MobSpawnControls.getLogger().throwing("BiomeReflector", "reflectList", e); // throw new RuntimeException(e); // } // } // // @SuppressWarnings("unchecked") // private static List<SpawnListEntry> reflect(BiomeGenBase biome, int ordinal) throws Exception { // Field f = BiomeGenBase.class.getDeclaredFields()[MONSTER_INDEX+ordinal]; // f.setAccessible(true); // return (List<SpawnListEntry>)f.get(biome); // } // } // Path: src/com/mcf/davidee/msc/spawning/MobHelper.java import java.util.Set; import net.minecraft.entity.EntityCreature; import net.minecraft.entity.EntityList; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EnumCreatureType; import net.minecraft.entity.monster.IMob; import net.minecraft.entity.passive.EntityAmbientCreature; import net.minecraft.entity.passive.EntityWaterMob; import net.minecraft.world.biome.BiomeGenBase; import net.minecraft.world.biome.BiomeGenBase.SpawnListEntry; import com.mcf.davidee.msc.config.ModEntityRecognizer; import com.mcf.davidee.msc.reflect.BiomeReflector; package com.mcf.davidee.msc.spawning; public class MobHelper { private static CreatureTypeMap defaultMap = new CreatureTypeMap(); @SuppressWarnings({ "rawtypes", "unchecked" }) public static void populateDefaultMap(){ for (Class c: (Set<Class>)EntityList.classToStringMapping.keySet()){
if (ModEntityRecognizer.isValidEntityClass(c)){
DavidGoldman/MobSpawnControls2
src/com/mcf/davidee/msc/spawning/MobHelper.java
// Path: src/com/mcf/davidee/msc/config/ModEntityRecognizer.java // public class ModEntityRecognizer { // // private static ListMultimap<ModContainer, EntityRegistration> registr = getRegistrations(); // // public static List<EntityRegistration> getRegistrations(ModContainer c) { // return registr.get(c); // } // // private static ListMultimap<ModContainer, EntityRegistration> getRegistrations() { // return ObfuscationReflectionHelper.getPrivateValue(EntityRegistry.class, EntityRegistry.instance(), "entityRegistrations"); // } // // @SuppressWarnings("unchecked") // public static List<Class<? extends EntityLiving>> getEntityClasses(ModContainer c) { // if (c == null) // return getVanillaEntityClasses(); // List<EntityRegistration> regs = getRegistrations(c); // List<Class<? extends EntityLiving>> cls = new ArrayList<Class<? extends EntityLiving>>(regs.size()); // for (EntityRegistration r : regs) { // if (isValidEntityClass(r.getEntityClass())) // cls.add((Class<? extends EntityLiving>) r.getEntityClass()); // } // return cls; // } // // @SuppressWarnings("unchecked") // private static List<Class<? extends EntityLiving>> getVanillaEntityClasses() { // List<Class<? extends EntityLiving>> cls = new ArrayList<Class<? extends EntityLiving>>(); // for (Object o : EntityList.classToStringMapping.entrySet()) { // Entry<Class<? extends Entity>, String> entry = (Entry<Class<? extends Entity>, String>) o; // if (isValidEntityClass(entry.getKey()) && EntityRegistry.instance().lookupModSpawn(entry.getKey(),false) == null) // cls.add((Class<? extends EntityLiving>) entry.getKey()); // } // return cls; // // } // // public static boolean hasEntities(ModContainer c) { // for (EntityRegistration r : getRegistrations(c)) // if (isValidEntityClass(r.getEntityClass())) // return true; // return false; // } // // public static boolean isValidEntityClass(Class<?> c) { // return c != null && !Modifier.isAbstract(c.getModifiers()) && EntityLiving.class.isAssignableFrom(c); // } // // } // // Path: src/com/mcf/davidee/msc/reflect/BiomeReflector.java // public class BiomeReflector { // // private static final int MONSTER_INDEX = 72; // // //TODO Cache // public static List<SpawnListEntry> reflectList(BiomeGenBase biome, EnumCreatureType type) { // try { // int ordin = (type == EnumCreatureType.waterCreature) ? 2 : (type == EnumCreatureType.ambient) ? 3 : type.ordinal(); // return reflect(biome,ordin); // } // catch(Exception e){ // MobSpawnControls.getLogger().severe("Unable to reflect list for biome " + BiomeNameHelper.getBiomeName(biome) + " of type " + type); // MobSpawnControls.getLogger().throwing("BiomeReflector", "reflectList", e); // throw new RuntimeException(e); // } // } // // @SuppressWarnings("unchecked") // private static List<SpawnListEntry> reflect(BiomeGenBase biome, int ordinal) throws Exception { // Field f = BiomeGenBase.class.getDeclaredFields()[MONSTER_INDEX+ordinal]; // f.setAccessible(true); // return (List<SpawnListEntry>)f.get(biome); // } // }
import java.util.Set; import net.minecraft.entity.EntityCreature; import net.minecraft.entity.EntityList; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EnumCreatureType; import net.minecraft.entity.monster.IMob; import net.minecraft.entity.passive.EntityAmbientCreature; import net.minecraft.entity.passive.EntityWaterMob; import net.minecraft.world.biome.BiomeGenBase; import net.minecraft.world.biome.BiomeGenBase.SpawnListEntry; import com.mcf.davidee.msc.config.ModEntityRecognizer; import com.mcf.davidee.msc.reflect.BiomeReflector;
package com.mcf.davidee.msc.spawning; public class MobHelper { private static CreatureTypeMap defaultMap = new CreatureTypeMap(); @SuppressWarnings({ "rawtypes", "unchecked" }) public static void populateDefaultMap(){ for (Class c: (Set<Class>)EntityList.classToStringMapping.keySet()){ if (ModEntityRecognizer.isValidEntityClass(c)){ boolean found = false; outer: for (BiomeGenBase biome: BiomeGenBase.getBiomeGenArray()){ if (biome != null){ for (EnumCreatureType type : EnumCreatureType.values()){ //Inner For
// Path: src/com/mcf/davidee/msc/config/ModEntityRecognizer.java // public class ModEntityRecognizer { // // private static ListMultimap<ModContainer, EntityRegistration> registr = getRegistrations(); // // public static List<EntityRegistration> getRegistrations(ModContainer c) { // return registr.get(c); // } // // private static ListMultimap<ModContainer, EntityRegistration> getRegistrations() { // return ObfuscationReflectionHelper.getPrivateValue(EntityRegistry.class, EntityRegistry.instance(), "entityRegistrations"); // } // // @SuppressWarnings("unchecked") // public static List<Class<? extends EntityLiving>> getEntityClasses(ModContainer c) { // if (c == null) // return getVanillaEntityClasses(); // List<EntityRegistration> regs = getRegistrations(c); // List<Class<? extends EntityLiving>> cls = new ArrayList<Class<? extends EntityLiving>>(regs.size()); // for (EntityRegistration r : regs) { // if (isValidEntityClass(r.getEntityClass())) // cls.add((Class<? extends EntityLiving>) r.getEntityClass()); // } // return cls; // } // // @SuppressWarnings("unchecked") // private static List<Class<? extends EntityLiving>> getVanillaEntityClasses() { // List<Class<? extends EntityLiving>> cls = new ArrayList<Class<? extends EntityLiving>>(); // for (Object o : EntityList.classToStringMapping.entrySet()) { // Entry<Class<? extends Entity>, String> entry = (Entry<Class<? extends Entity>, String>) o; // if (isValidEntityClass(entry.getKey()) && EntityRegistry.instance().lookupModSpawn(entry.getKey(),false) == null) // cls.add((Class<? extends EntityLiving>) entry.getKey()); // } // return cls; // // } // // public static boolean hasEntities(ModContainer c) { // for (EntityRegistration r : getRegistrations(c)) // if (isValidEntityClass(r.getEntityClass())) // return true; // return false; // } // // public static boolean isValidEntityClass(Class<?> c) { // return c != null && !Modifier.isAbstract(c.getModifiers()) && EntityLiving.class.isAssignableFrom(c); // } // // } // // Path: src/com/mcf/davidee/msc/reflect/BiomeReflector.java // public class BiomeReflector { // // private static final int MONSTER_INDEX = 72; // // //TODO Cache // public static List<SpawnListEntry> reflectList(BiomeGenBase biome, EnumCreatureType type) { // try { // int ordin = (type == EnumCreatureType.waterCreature) ? 2 : (type == EnumCreatureType.ambient) ? 3 : type.ordinal(); // return reflect(biome,ordin); // } // catch(Exception e){ // MobSpawnControls.getLogger().severe("Unable to reflect list for biome " + BiomeNameHelper.getBiomeName(biome) + " of type " + type); // MobSpawnControls.getLogger().throwing("BiomeReflector", "reflectList", e); // throw new RuntimeException(e); // } // } // // @SuppressWarnings("unchecked") // private static List<SpawnListEntry> reflect(BiomeGenBase biome, int ordinal) throws Exception { // Field f = BiomeGenBase.class.getDeclaredFields()[MONSTER_INDEX+ordinal]; // f.setAccessible(true); // return (List<SpawnListEntry>)f.get(biome); // } // } // Path: src/com/mcf/davidee/msc/spawning/MobHelper.java import java.util.Set; import net.minecraft.entity.EntityCreature; import net.minecraft.entity.EntityList; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EnumCreatureType; import net.minecraft.entity.monster.IMob; import net.minecraft.entity.passive.EntityAmbientCreature; import net.minecraft.entity.passive.EntityWaterMob; import net.minecraft.world.biome.BiomeGenBase; import net.minecraft.world.biome.BiomeGenBase.SpawnListEntry; import com.mcf.davidee.msc.config.ModEntityRecognizer; import com.mcf.davidee.msc.reflect.BiomeReflector; package com.mcf.davidee.msc.spawning; public class MobHelper { private static CreatureTypeMap defaultMap = new CreatureTypeMap(); @SuppressWarnings({ "rawtypes", "unchecked" }) public static void populateDefaultMap(){ for (Class c: (Set<Class>)EntityList.classToStringMapping.keySet()){ if (ModEntityRecognizer.isValidEntityClass(c)){ boolean found = false; outer: for (BiomeGenBase biome: BiomeGenBase.getBiomeGenArray()){ if (biome != null){ for (EnumCreatureType type : EnumCreatureType.values()){ //Inner For
for (SpawnListEntry entry : BiomeReflector.reflectList(biome, type)){
DavidGoldman/MobSpawnControls2
src/com/mcf/davidee/msc/packet/EntityListPacket.java
// Path: src/com/mcf/davidee/msc/network/MSCPacketHandler.java // public abstract class MSCPacketHandler { // // public abstract void handleSettings(SettingsPacket pkt, EntityPlayer player); // public abstract void handleAccessDenied(EntityPlayer player); // public abstract void handleHandShake(EntityPlayer player); // public abstract void handleRequest(PacketType packetType, String mod, EntityPlayer player); // public abstract void handleModList(ModListPacket packet, EntityPlayer player); // public abstract void handleCreatureType(CreatureTypePacket packet, EntityPlayer player); // public abstract void handleGroups(GroupsPacket packet, EntityPlayer player); // public abstract void handleBiomeList(BiomeListPacket packet, EntityPlayer player); // public abstract void handleBiomeSetting(BiomeSettingPacket packet, EntityPlayer player); // public abstract void handleEntityList(EntityListPacket packet, EntityPlayer player); // public abstract void handleEntitySetting(EntitySettingPacket packet, EntityPlayer player); // public abstract void handleEvaluatedBiome(EvaluatedBiomePacket packet, EntityPlayer player); // public abstract void handleEvaluatedGroup(EvaluatedGroupPacket packet, EntityPlayer player); // public abstract void handleDebug(DebugPacket packet, EntityPlayer player); // // protected abstract boolean hasPermission(EntityPlayer player); // // public final void handlePacket(MSCPacket packet, EntityPlayer player) { // if (hasPermission(player)) // packet.execute(this, player); // else if (player instanceof EntityPlayerMP) // MobSpawnControls.DISPATCHER.sendTo(MSCPacket.getPacket(PacketType.ACCESS_DENIED), (EntityPlayerMP)player); // } // }
import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import com.mcf.davidee.msc.network.MSCPacketHandler;
package com.mcf.davidee.msc.packet; public class EntityListPacket extends MSCPacket{ public String mod; public String[][] entities; @Override public MSCPacket readData(Object... data) { mod = (String) data[0]; entities = (String[][]) data[1]; return this; } @Override public void encodeInto(ChannelHandlerContext ctx, ByteBuf to) throws IOException { writeString(mod, to); for (int i = 0; i < 4; ++i) writeStringArray(entities[i], to); } @Override public void decodeFrom(ChannelHandlerContext ctx, ByteBuf from) throws IOException { mod = readString(from); entities = new String[4][]; for (int i = 0; i < 4; ++i) entities[i] = readStringArray(from); } @Override
// Path: src/com/mcf/davidee/msc/network/MSCPacketHandler.java // public abstract class MSCPacketHandler { // // public abstract void handleSettings(SettingsPacket pkt, EntityPlayer player); // public abstract void handleAccessDenied(EntityPlayer player); // public abstract void handleHandShake(EntityPlayer player); // public abstract void handleRequest(PacketType packetType, String mod, EntityPlayer player); // public abstract void handleModList(ModListPacket packet, EntityPlayer player); // public abstract void handleCreatureType(CreatureTypePacket packet, EntityPlayer player); // public abstract void handleGroups(GroupsPacket packet, EntityPlayer player); // public abstract void handleBiomeList(BiomeListPacket packet, EntityPlayer player); // public abstract void handleBiomeSetting(BiomeSettingPacket packet, EntityPlayer player); // public abstract void handleEntityList(EntityListPacket packet, EntityPlayer player); // public abstract void handleEntitySetting(EntitySettingPacket packet, EntityPlayer player); // public abstract void handleEvaluatedBiome(EvaluatedBiomePacket packet, EntityPlayer player); // public abstract void handleEvaluatedGroup(EvaluatedGroupPacket packet, EntityPlayer player); // public abstract void handleDebug(DebugPacket packet, EntityPlayer player); // // protected abstract boolean hasPermission(EntityPlayer player); // // public final void handlePacket(MSCPacket packet, EntityPlayer player) { // if (hasPermission(player)) // packet.execute(this, player); // else if (player instanceof EntityPlayerMP) // MobSpawnControls.DISPATCHER.sendTo(MSCPacket.getPacket(PacketType.ACCESS_DENIED), (EntityPlayerMP)player); // } // } // Path: src/com/mcf/davidee/msc/packet/EntityListPacket.java import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import com.mcf.davidee.msc.network.MSCPacketHandler; package com.mcf.davidee.msc.packet; public class EntityListPacket extends MSCPacket{ public String mod; public String[][] entities; @Override public MSCPacket readData(Object... data) { mod = (String) data[0]; entities = (String[][]) data[1]; return this; } @Override public void encodeInto(ChannelHandlerContext ctx, ByteBuf to) throws IOException { writeString(mod, to); for (int i = 0; i < 4; ++i) writeStringArray(entities[i], to); } @Override public void decodeFrom(ChannelHandlerContext ctx, ByteBuf from) throws IOException { mod = readString(from); entities = new String[4][]; for (int i = 0; i < 4; ++i) entities[i] = readStringArray(from); } @Override
public void execute(MSCPacketHandler handler, EntityPlayer player) {
DavidGoldman/MobSpawnControls2
src/com/mcf/davidee/msc/gui/list/EvaluatedBiomeScreen.java
// Path: src/com/mcf/davidee/msc/gui/MSCScreen.java // public abstract class MSCScreen extends BasicScreen implements ButtonHandler{ // // public MSCScreen(GuiScreen parent) { // super(parent); // // } // // public boolean doesGuiPauseGame() { // return false; // } // // protected void unhandledKeyTyped(char c, int code) { // if (code == Keyboard.KEY_ESCAPE) // mc.displayGuiScreen(null); // } // // public void setEnabled(boolean aFlag, Button... buttons) { // for (Button b : buttons) // b.setEnabled(aFlag); // } // // protected void reopenedGui() { } // public void buttonClicked(Button button) { } // // } // // Path: src/com/mcf/davidee/msc/packet/settings/EvaluatedBiomePacket.java // public class EvaluatedBiomePacket extends MSCPacket { // // public String mod; // public String biome; // public String[][] entities; // // @Override // public MSCPacket readData(Object... data) { // mod = (String) data[0]; // biome = (String) data[1]; // entities = (String[][]) data[2]; // return this; // } // // @Override // public void encodeInto(ChannelHandlerContext ctx, ByteBuf to) throws IOException { // writeString(mod, to); // writeString(biome, to); // for (int i = 0; i < 4; ++i) // writeStringArray(entities[i], to); // } // // @Override // public void decodeFrom(ChannelHandlerContext ctx, ByteBuf from) throws IOException { // mod = readString(from); // biome = readString(from); // entities = new String[4][]; // for (int i = 0; i < 4; ++i) // entities[i] = readStringArray(from); // } // // @Override // public void execute(MSCPacketHandler handler, EntityPlayer player) { // handler.handleEvaluatedBiome(this, player); // } // // } // // Path: src/com/mcf/davidee/msc/spawning/MobHelper.java // public class MobHelper { // // private static CreatureTypeMap defaultMap = new CreatureTypeMap(); // // @SuppressWarnings({ "rawtypes", "unchecked" }) // public static void populateDefaultMap(){ // for (Class c: (Set<Class>)EntityList.classToStringMapping.keySet()){ // // if (ModEntityRecognizer.isValidEntityClass(c)){ // boolean found = false; // outer: // for (BiomeGenBase biome: BiomeGenBase.getBiomeGenArray()){ // if (biome != null){ // for (EnumCreatureType type : EnumCreatureType.values()){ //Inner For // for (SpawnListEntry entry : BiomeReflector.reflectList(biome, type)){ // if (entry.entityClass == c){ // defaultMap.set(c, type); // found = true; // break outer; // } // } // } // End Inner For // } // // } //End Outer For // // if (!found) // defaultMap.set(c, null); // // } // // } // } // // public static EnumCreatureType getDefaultMobType(Class<? extends EntityLiving> cls) { // EnumCreatureType type = defaultMap.get(cls); // if (type == null) { // if (EntityAmbientCreature.class.isAssignableFrom(cls)) // return EnumCreatureType.ambient; // if (EntityWaterMob.class.isAssignableFrom(cls)) // return EnumCreatureType.waterCreature; // if (IMob.class.isAssignableFrom(cls)) // return EnumCreatureType.monster; // if (EntityCreature.class.isAssignableFrom(cls)) // return EnumCreatureType.creature; // } // return type; // } // // public static EnumCreatureType typeOf(String s) { // for (EnumCreatureType t : EnumCreatureType.values()) // if (t.toString().equalsIgnoreCase(s)) // return t; // return null; // } // }
import java.util.List; import net.minecraft.client.gui.GuiScreen; import com.mcf.davidee.guilib.basic.Label; import com.mcf.davidee.guilib.core.Button; import com.mcf.davidee.guilib.core.Container; import com.mcf.davidee.guilib.core.Scrollbar; import com.mcf.davidee.guilib.focusable.FocusableLabel; import com.mcf.davidee.guilib.focusable.FocusableWidget; import com.mcf.davidee.guilib.vanilla.ButtonVanilla; import com.mcf.davidee.guilib.vanilla.ScrollbarVanilla; import com.mcf.davidee.msc.gui.MSCScreen; import com.mcf.davidee.msc.packet.settings.EvaluatedBiomePacket; import com.mcf.davidee.msc.spawning.MobHelper;
package com.mcf.davidee.msc.gui.list; public class EvaluatedBiomeScreen extends MSCScreen { private Label title, subTitle; private Button close, monster, creature, ambient, water; private Scrollbar scrollbar; private Container masterContainer, labelContainer;
// Path: src/com/mcf/davidee/msc/gui/MSCScreen.java // public abstract class MSCScreen extends BasicScreen implements ButtonHandler{ // // public MSCScreen(GuiScreen parent) { // super(parent); // // } // // public boolean doesGuiPauseGame() { // return false; // } // // protected void unhandledKeyTyped(char c, int code) { // if (code == Keyboard.KEY_ESCAPE) // mc.displayGuiScreen(null); // } // // public void setEnabled(boolean aFlag, Button... buttons) { // for (Button b : buttons) // b.setEnabled(aFlag); // } // // protected void reopenedGui() { } // public void buttonClicked(Button button) { } // // } // // Path: src/com/mcf/davidee/msc/packet/settings/EvaluatedBiomePacket.java // public class EvaluatedBiomePacket extends MSCPacket { // // public String mod; // public String biome; // public String[][] entities; // // @Override // public MSCPacket readData(Object... data) { // mod = (String) data[0]; // biome = (String) data[1]; // entities = (String[][]) data[2]; // return this; // } // // @Override // public void encodeInto(ChannelHandlerContext ctx, ByteBuf to) throws IOException { // writeString(mod, to); // writeString(biome, to); // for (int i = 0; i < 4; ++i) // writeStringArray(entities[i], to); // } // // @Override // public void decodeFrom(ChannelHandlerContext ctx, ByteBuf from) throws IOException { // mod = readString(from); // biome = readString(from); // entities = new String[4][]; // for (int i = 0; i < 4; ++i) // entities[i] = readStringArray(from); // } // // @Override // public void execute(MSCPacketHandler handler, EntityPlayer player) { // handler.handleEvaluatedBiome(this, player); // } // // } // // Path: src/com/mcf/davidee/msc/spawning/MobHelper.java // public class MobHelper { // // private static CreatureTypeMap defaultMap = new CreatureTypeMap(); // // @SuppressWarnings({ "rawtypes", "unchecked" }) // public static void populateDefaultMap(){ // for (Class c: (Set<Class>)EntityList.classToStringMapping.keySet()){ // // if (ModEntityRecognizer.isValidEntityClass(c)){ // boolean found = false; // outer: // for (BiomeGenBase biome: BiomeGenBase.getBiomeGenArray()){ // if (biome != null){ // for (EnumCreatureType type : EnumCreatureType.values()){ //Inner For // for (SpawnListEntry entry : BiomeReflector.reflectList(biome, type)){ // if (entry.entityClass == c){ // defaultMap.set(c, type); // found = true; // break outer; // } // } // } // End Inner For // } // // } //End Outer For // // if (!found) // defaultMap.set(c, null); // // } // // } // } // // public static EnumCreatureType getDefaultMobType(Class<? extends EntityLiving> cls) { // EnumCreatureType type = defaultMap.get(cls); // if (type == null) { // if (EntityAmbientCreature.class.isAssignableFrom(cls)) // return EnumCreatureType.ambient; // if (EntityWaterMob.class.isAssignableFrom(cls)) // return EnumCreatureType.waterCreature; // if (IMob.class.isAssignableFrom(cls)) // return EnumCreatureType.monster; // if (EntityCreature.class.isAssignableFrom(cls)) // return EnumCreatureType.creature; // } // return type; // } // // public static EnumCreatureType typeOf(String s) { // for (EnumCreatureType t : EnumCreatureType.values()) // if (t.toString().equalsIgnoreCase(s)) // return t; // return null; // } // } // Path: src/com/mcf/davidee/msc/gui/list/EvaluatedBiomeScreen.java import java.util.List; import net.minecraft.client.gui.GuiScreen; import com.mcf.davidee.guilib.basic.Label; import com.mcf.davidee.guilib.core.Button; import com.mcf.davidee.guilib.core.Container; import com.mcf.davidee.guilib.core.Scrollbar; import com.mcf.davidee.guilib.focusable.FocusableLabel; import com.mcf.davidee.guilib.focusable.FocusableWidget; import com.mcf.davidee.guilib.vanilla.ButtonVanilla; import com.mcf.davidee.guilib.vanilla.ScrollbarVanilla; import com.mcf.davidee.msc.gui.MSCScreen; import com.mcf.davidee.msc.packet.settings.EvaluatedBiomePacket; import com.mcf.davidee.msc.spawning.MobHelper; package com.mcf.davidee.msc.gui.list; public class EvaluatedBiomeScreen extends MSCScreen { private Label title, subTitle; private Button close, monster, creature, ambient, water; private Scrollbar scrollbar; private Container masterContainer, labelContainer;
private EvaluatedBiomePacket packet;